repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
badoo/Chatto
ChattoAdditions/sources/Chat Items/PhotoMessages/PhotoMessagePresenter.swift
1
4953
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 Chatto open class PhotoMessagePresenter<ViewModelBuilderT, InteractionHandlerT> : BaseMessagePresenter<PhotoBubbleView, ViewModelBuilderT, InteractionHandlerT> where ViewModelBuilderT: ViewModelBuilderProtocol, ViewModelBuilderT.ViewModelT: PhotoMessageViewModelProtocol, InteractionHandlerT: BaseMessageInteractionHandlerProtocol, InteractionHandlerT.MessageType == ViewModelBuilderT.ModelT, InteractionHandlerT.ViewModelType == ViewModelBuilderT.ViewModelT { public typealias ModelT = ViewModelBuilderT.ModelT public typealias ViewModelT = ViewModelBuilderT.ViewModelT public let photoCellStyle: PhotoMessageCollectionViewCellStyleProtocol public init ( messageModel: ModelT, viewModelBuilder: ViewModelBuilderT, interactionHandler: InteractionHandlerT?, sizingCell: PhotoMessageCollectionViewCell, baseCellStyle: BaseMessageCollectionViewCellStyleProtocol, photoCellStyle: PhotoMessageCollectionViewCellStyleProtocol) { self.photoCellStyle = photoCellStyle super.init( messageModel: messageModel, viewModelBuilder: viewModelBuilder, interactionHandler: interactionHandler, sizingCell: sizingCell, cellStyle: baseCellStyle ) } public final override class func registerCells(_ collectionView: UICollectionView) { collectionView.register(PhotoMessageCollectionViewCell.self, forCellWithReuseIdentifier: "photo-message") } open override var isItemUpdateSupported: Bool { return true } public final override func dequeueCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: "photo-message", for: indexPath) } open override func createViewModel() -> ViewModelBuilderT.ViewModelT { let viewModel = self.viewModelBuilder.createViewModel(self.messageModel) let updateClosure = { [weak self] (old: Any, new: Any) -> Void in self?.updateCurrentCell() } viewModel.avatarImage.observe(self, closure: updateClosure) viewModel.image.observe(self, closure: updateClosure) viewModel.transferDirection.observe(self, closure: updateClosure) viewModel.transferProgress.observe(self, closure: updateClosure) viewModel.transferStatus.observe(self, closure: updateClosure) return viewModel } public var photoCell: PhotoMessageCollectionViewCell? { if let cell = self.cell { if let photoCell = cell as? PhotoMessageCollectionViewCell { return photoCell } else { assert(false, "Invalid cell was given to presenter!") } } return nil } open override func configureCell(_ cell: BaseMessageCollectionViewCell<PhotoBubbleView>, decorationAttributes: ChatItemDecorationAttributes, animated: Bool, additionalConfiguration: (() -> Void)?) { guard let cell = cell as? PhotoMessageCollectionViewCell else { assert(false, "Invalid cell received") return } super.configureCell(cell, decorationAttributes: decorationAttributes, animated: animated) { () -> Void in cell.photoMessageViewModel = self.messageViewModel cell.photoMessageStyle = self.photoCellStyle additionalConfiguration?() } } public func updateCurrentCell() { if let cell = self.photoCell, let decorationAttributes = self.decorationAttributes { self.configureCell(cell, decorationAttributes: decorationAttributes, animated: self.itemVisibility != .appearing, additionalConfiguration: nil) } } }
mit
7781a5d8a3aec50fb7d4a0e5ed6d9c00
43.621622
202
0.727842
5.953125
false
true
false
false
sahandnayebaziz/Dana-Hills
Pods/RSBarcodes_Swift/Source/RSUnifiedCodeValidator.swift
1
2266
// // RSUnifiedCodeValidator.swift // RSBarcodesSample // // Created by R0CKSTAR on 10/3/16. // Copyright (c) 2016 P.D.Q. All rights reserved. // import Foundation import AVFoundation open class RSUnifiedCodeValidator { open class var shared: RSUnifiedCodeValidator { return UnifiedCodeValidatorSharedInstance } open func isValid(_ contents:String, machineReadableCodeObjectType: String) -> Bool { var codeGenerator: RSCodeGenerator? switch machineReadableCodeObjectType { case AVMetadataObject.ObjectType.qr.rawValue, AVMetadataObject.ObjectType.pdf417.rawValue, AVMetadataObject.ObjectType.aztec.rawValue: return false case AVMetadataObject.ObjectType.code39.rawValue: codeGenerator = RSCode39Generator() case AVMetadataObject.ObjectType.code39Mod43.rawValue: codeGenerator = RSCode39Mod43Generator() case AVMetadataObject.ObjectType.ean8.rawValue: codeGenerator = RSEAN8Generator() case AVMetadataObject.ObjectType.ean13.rawValue: codeGenerator = RSEAN13Generator() case AVMetadataObject.ObjectType.interleaved2of5.rawValue: codeGenerator = RSITFGenerator() case AVMetadataObject.ObjectType.itf14.rawValue: codeGenerator = RSITF14Generator() case AVMetadataObject.ObjectType.upce.rawValue: codeGenerator = RSUPCEGenerator() case AVMetadataObject.ObjectType.code93.rawValue: codeGenerator = RSCode93Generator() case AVMetadataObject.ObjectType.code128.rawValue: codeGenerator = RSCode128Generator() case AVMetadataObject.ObjectType.dataMatrix.rawValue: codeGenerator = RSCodeDataMatrixGenerator() case RSBarcodesTypeISBN13Code: codeGenerator = RSISBN13Generator() case RSBarcodesTypeISSN13Code: codeGenerator = RSISSN13Generator() case RSBarcodesTypeExtendedCode39Code: codeGenerator = RSExtendedCode39Generator() default: print("No code generator selected.") return false } return codeGenerator!.isValid(contents) } } let UnifiedCodeValidatorSharedInstance = RSUnifiedCodeValidator()
mit
8c1bdaad46d3c9b1f3e99af4076453cc
40.2
142
0.704766
5.622829
false
false
false
false
jeffreybergier/WaterMe2
WaterMe/WaterMe/StyleSheets/UIFont+Font.swift
1
3013
// // UIFont+Font.swift // WaterMe // // Created by Jeffrey Bergier on 9/20/18. // Copyright © 2018 Saturday Apps. // // This file is part of WaterMe. Simple Plant Watering Reminders for iOS. // // WaterMe is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // WaterMe 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 WaterMe. If not, see <http://www.gnu.org/licenses/>. // import UIKit extension Font { static var bodyPlusPlusPlus: UIFont { return UIFont.preferredFont(forTextStyle: .title1) } static var bodyPlusPlus: UIFont { return UIFont.preferredFont(forTextStyle: .title2) } static var bodyPlus: UIFont { return UIFont.preferredFont(forTextStyle: .title3) } static var body: UIFont { return UIFont.preferredFont(forTextStyle: .body) } static var bodyMinus: UIFont { return UIFont.preferredFont(forTextStyle: .callout) } static var bodyMinusBold: UIFont { return UIFont.preferredFont(forTextStyle: .subheadline) } static var bodyPlusBold: UIFont { let body = UIFont.preferredFont(forTextStyle: .title3) return UIFont.boldSystemFont(ofSize: body.pointSize) } static var bodyBold: UIFont { let body = UIFont.preferredFont(forTextStyle: .body) return UIFont.boldSystemFont(ofSize: body.pointSize) } static var bodyIgnoringDynamicType: UIFont { return UIFont.systemFont(ofSize: 18) } static var bodyMinusIgnoringDynamicType: UIFont { return UIFont.systemFont(ofSize: 14) } fileprivate static var cachedEmojiFontWithSize: [CGFloat : UIFont] = [:] static var customEmojiLoaded: Bool = false static func emojiFont(ofSize size: CGFloat) -> UIFont { // custom emojis only work on iOS 12 and higher for some reason guard #available(iOS 12.0, *) else { return UIFont.systemFont(ofSize: size) } // look for cached font if let cachedFont = self.cachedEmojiFontWithSize[size] { return cachedFont } // try to load the custom emoji font guard let customFont = UIFont(name: "AppleColorEmoj2", size: size) else { let error = NSError(unableToLoadEmojiFont: nil) log.error(error) Analytics.log(error: error) assertionFailure() return UIFont.systemFont(ofSize: size) } // cache it for later self.cachedEmojiFontWithSize[size] = customFont self.customEmojiLoaded = true return customFont } }
gpl-3.0
6cc89e9881fae2a98341d034bb134a3c
34.857143
85
0.674303
4.403509
false
false
false
false
fvaldez/score_point_ios
scorePoint/SharedData.swift
1
454
// // SharedData.swift // scorePoint // // Created by Adriana Gonzalez on 3/18/16. // Copyright © 2016 Adriana Gonzalez. All rights reserved. // import Foundation class SharedData { static var sharedInstance: SharedData = SharedData() var completeName = "" var firstName = "" var lastName = "" var imgString : URL? var downloadedImg : UIImage? var idnum = "" var mail = "" init() { } }
mit
17a0da46cb8b9b7b148b1ce3434dae8c
15.777778
59
0.596026
4.081081
false
false
false
false
menlatin/jalapeno
digeocache/mobile/iOS/diGeo/diGeo/ExampleDrawerVisualStateManager.swift
3
4169
// Copyright (c) 2014 evolved.io (http://evolved.io) // // 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 enum DrawerAnimationType: Int { case None case Slide case SlideAndScale case SwingingDoor case Parallax case AnimatedBarButton } class ExampleDrawerVisualStateManager: NSObject { var leftDrawerAnimationType: DrawerAnimationType = .Parallax var rightDrawerAnimationType: DrawerAnimationType = .Parallax class var sharedManager: ExampleDrawerVisualStateManager { struct Static { static let instance: ExampleDrawerVisualStateManager = ExampleDrawerVisualStateManager() } return Static.instance } func drawerVisualStateBlockForDrawerSide(drawerSide: DrawerSide) -> DrawerControllerDrawerVisualStateBlock? { var animationType: DrawerAnimationType if drawerSide == DrawerSide.Left { animationType = self.leftDrawerAnimationType } else { animationType = self.rightDrawerAnimationType } var visualStateBlock: DrawerControllerDrawerVisualStateBlock? switch animationType { case .Slide: visualStateBlock = DrawerVisualState.slideVisualStateBlock case .SlideAndScale: visualStateBlock = DrawerVisualState.slideAndScaleVisualStateBlock case .Parallax: visualStateBlock = DrawerVisualState.parallaxVisualStateBlock(2.0) case .SwingingDoor: visualStateBlock = DrawerVisualState.swingingDoorVisualStateBlock case .AnimatedBarButton: visualStateBlock = DrawerVisualState.animatedHamburgerButtonVisualStateBlock default: visualStateBlock = { drawerController, drawerSide, percentVisible in var sideDrawerViewController: UIViewController? var transform = CATransform3DIdentity var maxDrawerWidth: CGFloat = 0.0 if drawerSide == .Left { sideDrawerViewController = drawerController.leftDrawerViewController maxDrawerWidth = drawerController.maximumLeftDrawerWidth } else if drawerSide == .Right { sideDrawerViewController = drawerController.rightDrawerViewController maxDrawerWidth = drawerController.maximumRightDrawerWidth } if percentVisible > 1.0 { transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0) if drawerSide == .Left { transform = CATransform3DTranslate(transform, maxDrawerWidth * (percentVisible - 1.0) / 2, 0.0, 0.0) } else if drawerSide == .Right { transform = CATransform3DTranslate(transform, -maxDrawerWidth * (percentVisible - 1.0) / 2, 0.0, 0.0) } } sideDrawerViewController?.view.layer.transform = transform } } return visualStateBlock } }
mit
9276e63221b8c22dce30e52190f3ef37
42.427083
125
0.662749
5.758287
false
false
false
false
LawrenceHan/iOS-project-playground
iOSRACSwift/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Action.swift
29
7869
/// Represents an action that will do some work when executed with a value of /// type `Input`, then return zero or more values of type `Output` and/or fail /// with an error of type `Error`. If no failure should be possible, NoError can /// be specified for the `Error` parameter. /// /// Actions enforce serial execution. Any attempt to execute an action multiple /// times concurrently will return an error. public final class Action<Input, Output, Error: ErrorType> { private let executeClosure: Input -> SignalProducer<Output, Error> private let eventsObserver: Signal<Event<Output, Error>, NoError>.Observer /// A signal of all events generated from applications of the Action. /// /// In other words, this will send every `Event` from every signal generated /// by each SignalProducer returned from apply(). public let events: Signal<Event<Output, Error>, NoError> /// A signal of all values generated from applications of the Action. /// /// In other words, this will send every value from every signal generated /// by each SignalProducer returned from apply(). public let values: Signal<Output, NoError> /// A signal of all errors generated from applications of the Action. /// /// In other words, this will send errors from every signal generated by /// each SignalProducer returned from apply(). public let errors: Signal<Error, NoError> /// Whether the action is currently executing. public var executing: AnyProperty<Bool> { return AnyProperty(_executing) } private let _executing: MutableProperty<Bool> = MutableProperty(false) /// Whether the action is currently enabled. public var enabled: AnyProperty<Bool> { return AnyProperty(_enabled) } private let _enabled: MutableProperty<Bool> = MutableProperty(false) /// Whether the instantiator of this action wants it to be enabled. private let userEnabled: AnyProperty<Bool> /// Lazy creation and storage of a UI bindable `CocoaAction`. The default behavior /// force casts the AnyObject? input to match the action's `Input` type. This makes /// it unsafe for use when the action is parameterized for something like `Void` /// input. In those cases, explicitly assign a value to this property that transforms /// the input to suit your needs. public lazy var unsafeCocoaAction: CocoaAction = CocoaAction(self) { $0 as! Input } /// This queue is used for read-modify-write operations on the `_executing` /// property. private let executingQueue = dispatch_queue_create("org.reactivecocoa.ReactiveCocoa.Action.executingQueue", DISPATCH_QUEUE_SERIAL) /// Whether the action should be enabled for the given combination of user /// enabledness and executing status. private static func shouldBeEnabled(userEnabled userEnabled: Bool, executing: Bool) -> Bool { return userEnabled && !executing } /// Initializes an action that will be conditionally enabled, and create a /// SignalProducer for each input. public init<P: PropertyType where P.Value == Bool>(enabledIf: P, _ execute: Input -> SignalProducer<Output, Error>) { executeClosure = execute userEnabled = AnyProperty(enabledIf) (events, eventsObserver) = Signal<Event<Output, Error>, NoError>.pipe() values = events.map { $0.value }.ignoreNil() errors = events.map { $0.error }.ignoreNil() _enabled <~ enabledIf.producer .combineLatestWith(executing.producer) .map(Action.shouldBeEnabled) } /// Initializes an action that will be enabled by default, and create a /// SignalProducer for each input. public convenience init(_ execute: Input -> SignalProducer<Output, Error>) { self.init(enabledIf: ConstantProperty(true), execute) } deinit { eventsObserver.sendCompleted() } /// Creates a SignalProducer that, when started, will execute the action /// with the given input, then forward the results upon the produced Signal. /// /// If the action is disabled when the returned SignalProducer is started, /// the produced signal will send `ActionError.NotEnabled`, and nothing will /// be sent upon `values` or `errors` for that particular signal. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func apply(input: Input) -> SignalProducer<Output, ActionError<Error>> { return SignalProducer { observer, disposable in var startedExecuting = false dispatch_sync(self.executingQueue) { if self._enabled.value { self._executing.value = true startedExecuting = true } } if !startedExecuting { observer.sendFailed(.NotEnabled) return } self.executeClosure(input).startWithSignal { signal, signalDisposable in disposable.addDisposable(signalDisposable) signal.observe { event in observer.action(event.mapError { .ProducerError($0) }) self.eventsObserver.sendNext(event) } } disposable.addDisposable { self._executing.value = false } } } } /// Wraps an Action for use by a GUI control (such as `NSControl` or /// `UIControl`), with KVO, or with Cocoa Bindings. public final class CocoaAction: NSObject { /// The selector that a caller should invoke upon a CocoaAction in order to /// execute it. public static let selector: Selector = "execute:" /// Whether the action is enabled. /// /// This property will only change on the main thread, and will generate a /// KVO notification for every change. public var enabled: Bool { return _enabled } /// Whether the action is executing. /// /// This property will only change on the main thread, and will generate a /// KVO notification for every change. public var executing: Bool { return _executing } private var _enabled = false private var _executing = false private let _execute: AnyObject? -> () private let disposable = CompositeDisposable() /// Initializes a Cocoa action that will invoke the given Action by /// transforming the object given to execute(). public init<Input, Output, Error>(_ action: Action<Input, Output, Error>, _ inputTransform: AnyObject? -> Input) { _execute = { input in let producer = action.apply(inputTransform(input)) producer.start() } super.init() disposable += action.enabled.producer .observeOn(UIScheduler()) .startWithNext { [weak self] value in self?.willChangeValueForKey("enabled") self?._enabled = value self?.didChangeValueForKey("enabled") } disposable += action.executing.producer .observeOn(UIScheduler()) .startWithNext { [weak self] value in self?.willChangeValueForKey("executing") self?._executing = value self?.didChangeValueForKey("executing") } } /// Initializes a Cocoa action that will invoke the given Action by /// always providing the given input. public convenience init<Input, Output, Error>(_ action: Action<Input, Output, Error>, input: Input) { self.init(action, { _ in input }) } deinit { disposable.dispose() } /// Attempts to execute the underlying action with the given input, subject /// to the behavior described by the initializer that was used. @IBAction public func execute(input: AnyObject?) { _execute(input) } public override class func automaticallyNotifiesObserversForKey(key: String) -> Bool { return false } } /// The type of error that can occur from Action.apply, where `Error` is the type of /// error that can be generated by the specific Action instance. public enum ActionError<Error: ErrorType>: ErrorType { /// The producer returned from apply() was started while the Action was /// disabled. case NotEnabled /// The producer returned from apply() sent the given error. case ProducerError(Error) } public func == <Error: Equatable>(lhs: ActionError<Error>, rhs: ActionError<Error>) -> Bool { switch (lhs, rhs) { case (.NotEnabled, .NotEnabled): return true case let (.ProducerError(left), .ProducerError(right)): return left == right default: return false } }
mit
ad85adb33c0dfa6fcb4fdac6f701636e
33.665198
131
0.727411
4.122053
false
false
false
false
lanjing99/RxSwiftDemo
23-mvvm-with-rxswift/starter/Tweetie/iOS Tweetie/View Controllers/List Timeline/ListTimelineViewController.swift
1
2063
/* * Copyright (c) 2016-2017 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import RxSwift import Then class ListTimelineViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var messageView: UIView! private let bag = DisposeBag() fileprivate var viewModel: ListTimelineViewModel! fileprivate var navigator: Navigator! static func createWith(navigator: Navigator, storyboard: UIStoryboard, viewModel: ListTimelineViewModel) -> ListTimelineViewController { return storyboard.instantiateViewController(ofType: ListTimelineViewController.self).then { vc in vc.navigator = navigator vc.viewModel = viewModel } } override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 90 tableView.rowHeight = UITableViewAutomaticDimension bindUI() } func bindUI() { //bind button to the people view controller //show tweets in table view //show message when no account available } }
mit
53c0c010bcd389cf9973620f87d2a803
36.509091
138
0.757635
4.923628
false
false
false
false
marcelmueller/MyWeight
MyWeightTests/ListViewControllerTests.swift
1
3278
// // ListViewControllerTests.swift // MyWeight // // Created by Bruno Mazzo on 11/6/16. // Copyright © 2016 Diogo Tridapalli. All rights reserved. // import Quick import Nimble import Nimble_Snapshots @testable import MyWeight class ListViewControllerTests: QuickSpec { var viewController: ListViewController! var massRepositoryMock: MassRepositoryMock! let snapshoService = SnapshotService() override func spec() { describe("ListViewController Layout") { beforeEach { self.massRepositoryMock = MassRepositoryMock() self.viewController = ListViewController(with: self.massRepositoryMock) } context("On empty response") { it("should have the correct portrait layout on all Sizes") { expect(self.viewController.view) == self.snapshoService.snapshot("ListViewController - Empty", sizes: self.snapshoService.iPhonePortraitSizes) } } context("On items") { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy HH:mm" beforeEach { self.massRepositoryMock.fetchResponse = [ Mass(value: Measurement(value: 60, unit: .kilograms), date: dateFormatter.date(from: "10/10/2016 10:10")!), Mass(value: Measurement(value: 62, unit: .kilograms), date: dateFormatter.date(from: "08/10/2016 9:10")!), Mass(value: Measurement(value: 64, unit: .kilograms), date: dateFormatter.date(from: "06/10/2016 11:30")!), Mass(value: Measurement(value: 66, unit: .kilograms), date: dateFormatter.date(from: "02/10/2016 12:00")!), Mass(value: Measurement(value: 68, unit: .kilograms), date: dateFormatter.date(from: "30/09/2016 14:44")!), Mass(value: Measurement(value: 70, unit: .kilograms), date: dateFormatter.date(from: "28/09/2016 16:31")!), Mass(value: Measurement(value: 72, unit: .kilograms), date: dateFormatter.date(from: "26/09/2016 18:20")!), Mass(value: Measurement(value: 74, unit: .kilograms), date: dateFormatter.date(from: "24/09/2016 20:10")!), Mass(value: Measurement(value: 76, unit: .kilograms), date: dateFormatter.date(from: "22/09/2016 22:44")!), ] _ = self.viewController.view self.viewController.viewWillAppear(true) self.viewController.viewDidAppear(true) } it("should have the correct portrait layout on all Sizes") { expect(self.viewController.view) == self.snapshoService.snapshot("ListViewController - With Items", sizes: self.snapshoService.iPhonePortraitSizes) } } } } } class MassRepositoryMock: MassRepository { var fetchResponse: [Mass]? func fetch(_ completion: @escaping (_ results: [Mass]) -> Void) { completion(self.fetchResponse ?? []) } }
mit
d9bf3d5855199ab22c9271b3a007c29c
43.890411
167
0.569423
4.876488
false
false
false
false
goaairlines/capetown-ios
capetown/Views/KeyboardView.swift
1
3361
// // KeyboardView.swift // capetown // // Created by Alex Berger on 1/31/16. // Copyright © 2016 goa airlines. All rights reserved. // import UIKit struct KeyboardViewConstants { static let keyboardHeight: CGFloat = 294.0 static let keyboardKeyContainerHeight: CGFloat = 278.0 static let keyboardInset: CGFloat = 16.0 static let separatorHeight: CGFloat = 2.0 } protocol KeyboardDelegate { func keyboardButtonTapped(keyboardItemButton: KeyboardItemButton) } class KeyboardView: UIView { var delegate: KeyboardDelegate? var keyboardKeyContainer: KeyboardKeyContainer? private var separatorLine: UIView! override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) do { try setupView() } catch UIAssemblyError.UIAssemblyMissing { log.error("Assembly failed") } catch { log.error("Something went wrong") } } override func updateConstraints() { do { try setupConstraints() } catch UIAssemblyError.UIAssemblyMissing { log.error("Assembly failed") } catch { log.error("Something went wrong") } super.updateConstraints() } } extension KeyboardView { private func setupView() throws { separatorLine = UIView() separatorLine.backgroundColor = UIColor.cptwnMidBlueColor() separatorLine.alpha = 0.25 self.addSubview(separatorLine) guard let keyboardKeyContainer = keyboardKeyContainer else { throw UIAssemblyError.UIAssemblyMissing } keyboardKeyContainer.delegate = self self.addSubview(keyboardKeyContainer) } private func setupConstraints() throws { separatorLine.snp_makeConstraints { make in make.top.equalTo(0) make.right.equalTo(-KeyboardViewConstants.keyboardInset) make.left.equalTo(KeyboardViewConstants.keyboardInset) make.height.equalTo(KeyboardViewConstants.separatorHeight) } guard let keyboardKeyContainer = keyboardKeyContainer else { throw UIAssemblyError.UIAssemblyMissing } let aspectRatioConstraint = NSLayoutConstraint( item: keyboardKeyContainer, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: keyboardKeyContainer, attribute: NSLayoutAttribute.Height, multiplier: 375.0 / 325.0, constant: 0.0) keyboardKeyContainer.addConstraint(aspectRatioConstraint) keyboardKeyContainer.snp_makeConstraints { make in make.top.equalTo(KeyboardViewConstants.keyboardInset) make.bottom.greaterThanOrEqualTo(-KeyboardViewConstants.keyboardInset) make.height.equalTo(KeyboardViewConstants.keyboardKeyContainerHeight) make.centerX.equalTo(self) } } } extension KeyboardView: KeyboardKeyContainerDelegate { func keyboardButtonTapped(keyboardItemButton: KeyboardItemButton) { if let delegate = delegate { delegate.keyboardButtonTapped(keyboardItemButton) } } }
mit
cf2032bbde9a1972b3e6752ad03b5be9
27.235294
82
0.644048
5.675676
false
false
false
false
eugenio79/GMIRCClient
Pod/Classes/IRC/message/GMIRCMessageParams.swift
1
2194
// Copyright © 2015 Giuseppe Morana aka Eugenio // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Encapsulates an IRC message params public class GMIRCMessageParams: NSObject { /// Here I put everything I'm not still able to parse private(set) var unparsed: String? /// e.g. the target of a PRIVMSG private(set) var msgTarget: String? /// e.g. the the text of a PRIVMSG private(set) var textToBeSent: String? /// @param stringToParse e.g. "eugenio_ios :Hi, I a€™m Eugenio too" init?(stringToParse: String) { super.init() var idx = stringToParse.characters.indexOf(" ") if idx == nil { unparsed = stringToParse return } msgTarget = stringToParse.substringToIndex(idx!) let remaining = stringToParse.substringFromIndex(idx!.successor()) idx = remaining.characters.indexOf(":") if idx == nil { unparsed = remaining return } textToBeSent = remaining.substringFromIndex(idx!.successor()) } }
mit
61c6493e523e6f7810dfc89ea86e7715
35.533333
80
0.67047
4.752711
false
false
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/UploaderTableViewController.swift
1
7382
// // UploaderTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2016/02/09. // Copyright © 2016年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON import SVProgressHUD protocol UploaderTableViewControllerDelegate { func UploaderFinish(controller: UploaderTableViewController) } class UploaderTableViewController: BaseTableViewController { var uploader: MultiUploader! var delegate: UploaderTableViewControllerDelegate? var progress: ((UploadItem, Float)-> Void)! var success: (Int-> Void)! var failure: ((Int, JSON) -> Void)! enum Mode { case Images, Preview, PostEntry, PostPage func title()->String { switch(self) { case .Images: return NSLocalizedString("Upload images...", comment: "Upload images...") case .Preview: return NSLocalizedString("Make preview...", comment: "Make preview...") case .PostEntry: return NSLocalizedString("Sending entry...", comment: "Sending entry...") case .PostPage: return NSLocalizedString("Sending page...", comment: "Sending page...") } } } var mode = Mode.Images private(set) var result: JSON? let IMAGE_SIZE: CGFloat = 50.0 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() self.title = self.mode.title() self.tableView.registerNib(UINib(nibName: "UploaderTableViewCell", bundle: nil), forCellReuseIdentifier: "UploaderTableViewCell") self.progress = { (item: UploadItem, progress: Float) in self.tableView.reloadData() } self.success = { (processed: Int) in self.result = self.uploader.result self.delegate?.UploaderFinish(self) } self.failure = { (processed: Int, error: JSON) in self.uploadError(error) self.tableView.reloadData() } self.uploader.start(progress: self.progress, success: self.success, failure: self.failure) self.tableView.reloadData() } 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 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return uploader.count() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UploaderTableViewCell", forIndexPath: indexPath) as! UploaderTableViewCell // Configure the cell... let item = self.uploader.items[indexPath.row] cell.uploaded = item.uploaded cell.progress = item.progress cell.nameLabel.text = item.filename item.thumbnail(CGSize(width: IMAGE_SIZE, height: IMAGE_SIZE), completion: { image in cell.thumbView.image = image } ) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return IMAGE_SIZE } /* // 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. } */ func uploadRestart() { let alertController = UIAlertController( title: NSLocalizedString("Upload", comment: "Upload"), message: NSLocalizedString("There is the rest of the items. Are you sure you want to upload again?", comment: "There is the rest of the items. Are you sure you want to upload again?"), preferredStyle: .Alert) let yesAction = UIAlertAction(title: NSLocalizedString("YES", comment: "YES"), style: .Default) { action in self.uploader.restart(progress: self.progress, success: self.success, failure: self.failure) } let noAction = UIAlertAction(title: NSLocalizedString("NO", comment: "NO"), style: .Default) { action in self.delegate?.UploaderFinish(self) } alertController.addAction(noAction) alertController.addAction(yesAction) self.presentViewController(alertController, animated: true, completion: nil) } func uploadError(error: JSON) { let alertController = UIAlertController( title: NSLocalizedString("Upload error", comment: "Upload error"), message: error["message"].stringValue, preferredStyle: .Alert) let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: "OK"), style: .Default) { action in if self.uploader.queueCount() > 0 { self.uploadRestart() } } alertController.addAction(okAction) self.presentViewController(alertController, animated: true, completion: nil) } }
mit
3c012d66f165b05407e24023504733f5
35.349754
196
0.638433
5.370451
false
false
false
false
OrdnanceSurvey/OS-Maps-API
Sample Code/OS API Response -Swift/OSAPIResponse/Header.swift
1
1020
// // Header.swift // OSAPIResponse // // Created by Dave Hardiman on 14/03/2016 // Copyright (c) Ordnance Survey. All rights reserved. // import Foundation import OSJSON @objc(OSHeader) public class Header: NSObject, Decodable { // MARK: Properties public let uri: String public let format: String init(uri: String, format: String) { self.uri = uri self.format = format super.init() } //MARK: JSON initialiser convenience required public init?(json: JSON) { guard let uri = json.stringValueForKey(Header.UriKey), format = json.stringValueForKey(Header.FormatKey) else { return nil } self.init( uri: uri, format: format ) } } extension Header { // MARK: Declaration for string constants to be used to decode and also serialize. @nonobjc internal static let UriKey: String = "uri" @nonobjc internal static let FormatKey: String = "format" }
apache-2.0
73dabc224721aef093604183704186a2
21.666667
86
0.615686
4.180328
false
false
false
false
SnowdogApps/Project-Needs-Partner
CooperationFinder/Async.swift
1
10835
// // Async.swift // // Created by Tobias DM on 15/07/14. // // OS X 10.10+ and iOS 8.0+ // Only use with ARC // // The MIT License (MIT) // Copyright (c) 2014 Tobias Due Munk // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation // MARK: - HACK: For Swift 1.1 extension qos_class_t { public var id:Int { return Int(value) } } // MARK: - DSL for GCD queues private class GCD { /* dispatch_get_queue() */ class func mainQueue() -> dispatch_queue_t { return dispatch_get_main_queue() // Don't ever use dispatch_get_global_queue(qos_class_main().id, 0) re https://gist.github.com/duemunk/34babc7ca8150ff81844 } class func userInteractiveQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE.id, 0) } class func userInitiatedQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED.id, 0) } class func utilityQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_UTILITY.id, 0) } class func backgroundQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_BACKGROUND.id, 0) } } // MARK: - Async – Struct public struct Async { private let block: dispatch_block_t private init(_ block: dispatch_block_t) { self.block = block } } // MARK: - Async – Static methods extension Async { /* dispatch_async() */ private static func async(block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see matching regular Async methods) // Create block with the "inherit" type let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) // Add block to queue dispatch_async(queue, _block) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_block) } public static func main(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.mainQueue()) } public static func userInteractive(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.userInteractiveQueue()) } public static func userInitiated(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.userInitiatedQueue()) } public static func utility(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.utilityQueue()) } public static func background(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.backgroundQueue()) } public static func customQueue(queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return Async.async(block, inQueue: queue) } /* dispatch_after() */ private static func after(seconds: Double, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) return at(time, block: block, inQueue: queue) } private static func at(time: dispatch_time_t, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) dispatch_after(time, queue, _block) return Async(_block) } public static func main(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.mainQueue()) } public static func userInteractive(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.userInteractiveQueue()) } public static func userInitiated(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.userInitiatedQueue()) } public static func utility(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.utilityQueue()) } public static func background(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.backgroundQueue()) } public static func customQueue(#after: Double, queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: queue) } } // MARK: - Async – Regualar methods matching static ones extension Async { /* dispatch_async() */ private func chain(block chainingBlock: dispatch_block_t, runInQueue queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) dispatch_block_notify(self.block, queue, _chainingBlock) return Async(_chainingBlock) } public func main(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.mainQueue()) } public func userInteractive(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.userInteractiveQueue()) } public func userInitiated(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.userInitiatedQueue()) } public func utility(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.utilityQueue()) } public func background(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.backgroundQueue()) } public func customQueue(queue: dispatch_queue_t, chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: queue) } /* dispatch_after() */ private func after(seconds: Double, block chainingBlock: dispatch_block_t, runInQueue queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) // Wrap block to be called when previous block is finished let chainingWrapperBlock: dispatch_block_t = { // Calculate time from now let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_after(time, queue, _chainingBlock) } // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingWrapperBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingWrapperBlock) // Add block to queue *after* previous block is finished dispatch_block_notify(self.block, queue, _chainingWrapperBlock) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_chainingBlock) } public func main(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.mainQueue()) } public func userInteractive(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.userInteractiveQueue()) } public func userInitiated(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.userInitiatedQueue()) } public func utility(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.utilityQueue()) } public func background(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.backgroundQueue()) } public func customQueue(#after: Double, queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: queue) } /* cancel */ public func cancel() { dispatch_block_cancel(block) } /* wait */ /// If optional parameter forSeconds is not provided, use DISPATCH_TIME_FOREVER public func wait(seconds: Double = 0.0) { if seconds != 0.0 { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_block_wait(block, time) } else { dispatch_block_wait(block, DISPATCH_TIME_FOREVER) } } } // MARK: - Apply public struct Apply { // DSL for GCD dispatch_apply() // // Apply runs a block multiple times, before returning. // If you want run the block asynchounusly from the current thread, // wrap it in an Async block, // e.g. Async.main { Apply.background(3) { ... } } public static func userInteractive(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.userInteractiveQueue(), block) } public static func userInitiated(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.userInitiatedQueue(), block) } public static func utility(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.utilityQueue(), block) } public static func background(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.backgroundQueue(), block) } public static func customQueue(iterations: Int, queue: dispatch_queue_t, block: Int -> ()) { dispatch_apply(iterations, queue, block) } } // MARK: - qos_class_t extension qos_class_t { // Convenience description of qos_class_t // Calculated property var description: String { get { switch self.id { case qos_class_main().id: return "Main" case QOS_CLASS_USER_INTERACTIVE.id: return "User Interactive" case QOS_CLASS_USER_INITIATED.id: return "User Initiated" case QOS_CLASS_DEFAULT.id: return "Default" case QOS_CLASS_UTILITY.id: return "Utility" case QOS_CLASS_BACKGROUND.id: return "Background" case QOS_CLASS_UNSPECIFIED.id: return "Unspecified" default: return "Unknown" } } } }
apache-2.0
5e3140e18551cb27af4ecfe20e86e9ed
35.584459
126
0.715486
3.621739
false
false
false
false
ahmedabadie/ABNScheduler
ABNScheduler.swift
1
25476
// The MIT License (MIT) // // Copyright (c) 2016 Ahmed Mohamed // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit /// The maximum allowed notifications to be scheduled at a time by iOS. ///- important: Do not change this value. Changing this value to be over /// 64 will cause some notifications to be discarded by iOS. let MAX_ALLOWED_NOTIFICATIONS = 64 ///- author: Ahmed Mohamed class ABNScheduler { /// The maximum number of allowed UILocalNotification to be scheduled. Four slots /// are reserved if you would like to schedule notifications without them being queued. ///> Feel free to change this value. ///- attention: iOS by default allows a maximum of 64 notifications to be scheduled /// at a time. ///- seealso: `MAX_ALLOWED_NOTIFICATIONS` static let maximumScheduledNotifications = 60 /// The key of the notification's identifier. fileprivate let identifierKey = "ABNIdentifier" /// The key of the notification's identifier. static let identifierKey = "ABNIdentifier" ///- parameters: /// - alertBody: Alert body of the notification. /// - fireDate: The date in which the notification will be fired at. ///- returns: Notification's identifier if it was successfully scheduled, nil otherwise. /// To get an ABNotificaiton instance of this notification, use this identifier with /// `ABNScheduler.notificationWithIdentifier(_:)`. class func schedule(alertBody: String, fireDate: Date) -> String? { let notification = ABNotification(alertBody: alertBody) if let identifier = notification.schedule(fireDate: fireDate) { return identifier } return nil } ///Cancels the specified notification. ///- paramater: Notification to cancel. class func cancel(_ notification: ABNotification) { notification.cancel() } ///Cancels all scheduled UILocalNotification and clears the ABNQueue. class func cancelAllNotifications() { UIApplication.shared.cancelAllLocalNotifications() ABNQueue.queue.clear() let _ = saveQueue() print("All notifications have been cancelled") } ///- returns: ABNotification of the farthest UILocalNotification (last to be fired). class func farthestLocalNotification() -> ABNotification? { if let localNotification = UIApplication.shared.scheduledLocalNotifications?.last { return notificationWithUILocalNotification(localNotification) } return nil } ///- returns: Count of scheduled UILocalNotification by iOS. class func scheduledCount() -> Int { return (UIApplication.shared.scheduledLocalNotifications?.count)! } ///- returns: Count of queued ABNotification. class func queuedCount() -> Int { return ABNQueue.queue.count() } ///- returns: Count of scheduled UILocalNotification and queued ABNotification. class func count() -> Int { return scheduledCount() + queuedCount() } ///Schedules the maximum possible number of ABNotification from the ABNQueue class func scheduleNotificationsFromQueue() { for _ in 0..<(min(maximumScheduledNotifications, MAX_ALLOWED_NOTIFICATIONS) - scheduledCount()) where ABNQueue.queue.count() > 0 { let notification = ABNQueue.queue.pop() let _ = notification.schedule(fireDate: notification.fireDate!) } } ///Creates an ABNotification from a UILocalNotification or from the ABNQueue. ///- parameter identifier: Identifier of the required notification. ///- returns: ABNotification if found, nil otherwise. class func notificationWithIdentifier(_ identifier: String) -> ABNotification? { let notifs = UIApplication.shared.scheduledLocalNotifications let queue = ABNQueue.queue.notificationsQueue() if notifs?.count == 0 && queue.count == 0 { return nil } for note in notifs! { let id = note.userInfo![ABNScheduler.identifierKey] as! String if id == identifier { return notificationWithUILocalNotification(note) } } if let note = ABNQueue.queue.notificationWithIdentifier(identifier) { return note } return nil } ///Instantiates an ABNotification from a UILocalNotification. ///- parameter localNotification: The UILocalNotification to instantiate an ABNotification from. ///- returns: The instantiated ABNotification from the UILocalNotification. class func notificationWithUILocalNotification(_ localNotification: UILocalNotification) -> ABNotification { return ABNotification.notificationWithUILocalNotification(localNotification) } ///Reschedules all notifications by copying them into a temporary array, ///cancelling them, and scheduling them again. class func rescheduleNotifications() { let notificationsCount = count() var notificationsArray = [ABNotification?](repeating: nil, count: notificationsCount) let scheduledNotifications = UIApplication.shared.scheduledLocalNotifications var i = 0 for note in scheduledNotifications! { let notif = notificationWithIdentifier(note.userInfo?[identifierKey] as! String) notificationsArray[i] = notif notif?.cancel() i += 1 } let queuedNotifications = ABNQueue.queue.notificationsQueue() for note in queuedNotifications { notificationsArray[i] = note i += 1 } cancelAllNotifications() for note in notificationsArray { let _ = note?.schedule(fireDate: (note?.fireDate)!) } } ///Retrieves the total scheduled notifications (by iOS and in the notification queue) and returns them as ABNotification array. ///- returns: ABNotification array of scheduled notifications if any, nil otherwise. class func scheduledNotifications() -> [ABNotification]? { if let localNotifications = UIApplication.shared.scheduledLocalNotifications { var notifications = [ABNotification]() for localNotification in localNotifications { notifications.append(ABNotification.notificationWithUILocalNotification(localNotification)) } return notifications } return nil } ///- returns: The notifications queue. class func notificationsQueue() -> [ABNotification] { return ABNQueue.queue.notificationsQueue() } ///Persists the notifications queue to the disk ///> Call this method whenever you need to save changes done to the queue and/or before terminating the app. class func saveQueue() -> Bool { return ABNQueue.queue.save() } //MARK: Testing /// Use this method for development and testing. ///> Prints all scheduled and queued notifications. ///> You can freely modifiy it without worrying about affecting any functionality. class func listScheduledNotifications() { let notifs = UIApplication.shared.scheduledLocalNotifications let notificationQueue = ABNQueue.queue.notificationsQueue() if notifs?.count == 0 && notificationQueue.count == 0 { print("There are no scheduled notifications") return } print("SCHEDULED") var i = 1 for note in notifs! { let id = note.userInfo![identifierKey] as! String print("\(i) Alert body: \(note.alertBody!) - Fire date: \(note.fireDate!) - Repeats: \(ABNotification.calendarUnitToRepeats(calendarUnit: note.repeatInterval)) - Identifier: \(id)") i += 1 } print("QUEUED") for note in notificationQueue { print("\(i) Alert body: \(note.alertBody) - Fire date: \(note.fireDate!) - Repeats: \(note.repeatInterval) - Identifier: \(note.identifier)") i += 1 } print("") } /// Used only for testing. /// - important: This method is only used to test that loading the queue is successful. Do not use it in production. The `ABNQueue().load()` method is called automatically when initially accessing the notification queue. /// - returns: Array of notifications read from disk. class func loadQueue() -> [ABNotification]? { return ABNQueue().load() } } //MARK:- ///- author: Ahmed Mohamed private class ABNQueue : NSObject { fileprivate var notifQueue = [ABNotification]() static let queue = ABNQueue() let ArchiveURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("notifications.abnqueue") override init() { super.init() if let notificationQueue = self.load() { notifQueue = notificationQueue } } ///- paramater notification ABNotification to push. fileprivate func push(_ notification: ABNotification) { notifQueue.insert(notification, at: findInsertionPoint(notification)) } /// Finds the position at which the new ABNotification is inserted in the queue. /// - parameter notification: ABNotification to insert. /// - returns: Index to insert the ABNotification at. /// - seealso: [swift-algorithm-club](https://github.com/hollance/swift-algorithm-club/tree/master/Ordered%20Array) fileprivate func findInsertionPoint(_ notification: ABNotification) -> Int { let range = 0..<notifQueue.count var rangeLowerBound = range.lowerBound var rangeUpperBound = range.upperBound while rangeLowerBound < rangeUpperBound { let midIndex = rangeLowerBound + (rangeUpperBound - rangeLowerBound) / 2 if notifQueue[midIndex] == notification { return midIndex } else if notifQueue[midIndex] < notification { rangeLowerBound = midIndex + 1 } else { rangeUpperBound = midIndex } } return rangeLowerBound } ///Removes and returns the head of the queue. ///- returns: The head of the queue. fileprivate func pop() -> ABNotification { return notifQueue.removeFirst() } ///- returns: The head of the queue. fileprivate func peek() -> ABNotification? { return notifQueue.last } ///Clears the queue. fileprivate func clear() { notifQueue.removeAll() } ///Called when an ABNotification is cancelled. ///- parameter index: Index of ABNotification to remove. fileprivate func removeAtIndex(_ index: Int) { notifQueue.remove(at: index) } ///- returns: Count of ABNotification in the queue. fileprivate func count() -> Int { return notifQueue.count } ///- returns: The notifications queue. fileprivate func notificationsQueue() -> [ABNotification] { let queue = notifQueue return queue } ///- parameter identifier: Identifier of the notification to return. ///- returns: ABNotification if found, nil otherwise. fileprivate func notificationWithIdentifier(_ identifier: String) -> ABNotification? { for note in notifQueue { if note.identifier == identifier { return note } } return nil } // MARK: NSCoding ///Save queue on disk. ///- returns: The success of the saving operation. fileprivate func save() -> Bool { return NSKeyedArchiver.archiveRootObject(self.notifQueue, toFile: ArchiveURL.path) } ///Load queue from disk. ///Called first when instantiating the ABNQueue singleton. ///You do not need to manually call this method and therefore do not declare it as public. fileprivate func load() -> [ABNotification]? { return NSKeyedUnarchiver.unarchiveObject(withFile: ArchiveURL.path) as? [ABNotification] } } //MARK:- ///- author: Ahmed Mohamed enum Repeats: String { case None, Hourly, Daily, Weekly, Monthly, Yearly } ///A wrapper class around UILocalNotification. ///- author: Ahmed Mohamed open class ABNotification : NSObject, NSCoding, Comparable { fileprivate var localNotification: UILocalNotification var alertBody: String var alertAction: String? var soundName: String? var repeatInterval = Repeats.None var userInfo: Dictionary<String, AnyObject> fileprivate(set) var identifier: String fileprivate var scheduled = false var fireDate: Date? { return localNotification.fireDate } init(alertBody: String) { self.alertBody = alertBody self.localNotification = UILocalNotification() self.identifier = UUID().uuidString self.userInfo = Dictionary<String, AnyObject>() super.init() } init(alertBody: String, identifier: String) { self.alertBody = alertBody self.localNotification = UILocalNotification() self.identifier = identifier self.userInfo = Dictionary<String, AnyObject>() super.init() } ///Used to instantiate an ABNotification when loaded from disk. fileprivate init(notification: UILocalNotification, alertBody: String, alertAction: String?, soundName: String?, identifier: String, repeats: Repeats, userInfo: Dictionary<String, AnyObject>, scheduled: Bool) { self.alertBody = alertBody self.alertAction = alertAction self.soundName = soundName; self.localNotification = notification self.identifier = identifier self.userInfo = userInfo self.repeatInterval = repeats self.scheduled = scheduled super.init() } ///Schedules the notification. ///> Checks to see if there is enough room for the notification to be scheduled. Otherwise, the notification is queued. ///- parameter fireDate: The date in which the notification will be fired at. ///- returns: The identifier of the notification. Use this identifier to retrieve the notification using `ABNQueue.notificationWithIdentifier` and `ABNScheduler.notificationWithIdentifier` methods. func schedule(fireDate date: Date) -> String? { if self.scheduled { return nil } else { self.localNotification = UILocalNotification() self.localNotification.alertBody = self.alertBody self.localNotification.alertAction = self.alertAction self.localNotification.fireDate = date.removeSeconds() self.localNotification.soundName = (self.soundName == nil) ? UILocalNotificationDefaultSoundName : self.soundName; self.userInfo[ABNScheduler.identifierKey] = self.identifier as AnyObject? self.localNotification.userInfo = self.userInfo self.soundName = self.localNotification.soundName if repeatInterval != .None { switch repeatInterval { case .Hourly: self.localNotification.repeatInterval = NSCalendar.Unit.hour case .Daily: self.localNotification.repeatInterval = NSCalendar.Unit.day case .Weekly: self.localNotification.repeatInterval = NSCalendar.Unit.weekOfYear case .Monthly: self.localNotification.repeatInterval = NSCalendar.Unit.month case .Yearly: self.localNotification.repeatInterval = NSCalendar.Unit.year default: break } } let count = ABNScheduler.scheduledCount() if count >= min(ABNScheduler.maximumScheduledNotifications, MAX_ALLOWED_NOTIFICATIONS) { if let farthestNotification = ABNScheduler.farthestLocalNotification() { if farthestNotification > self { farthestNotification.cancel() ABNQueue.queue.push(farthestNotification) self.scheduled = true UIApplication.shared.scheduleLocalNotification(self.localNotification) } else { ABNQueue.queue.push(self) } } return self.identifier } self.scheduled = true UIApplication.shared.scheduleLocalNotification(self.localNotification) return self.identifier } } ///Reschedules the notification. ///- parameter fireDate: The date in which the notification will be fired at. func reschedule(fireDate date: Date) { cancel() let _ = schedule(fireDate: date) } ///Cancels the notification if scheduled or queued. func cancel() { UIApplication.shared.cancelLocalNotification(self.localNotification) let queue = ABNQueue.queue.notificationsQueue() var i = 0 for note in queue { if self.identifier == note.identifier { ABNQueue.queue.removeAtIndex(i) break } i += 1 } scheduled = false } ///Snoozes the notification for a number of minutes. ///- parameter minutes: Minutes to snooze the notification for. func snoozeForMinutes(_ minutes: Int) { reschedule(fireDate: self.localNotification.fireDate!.nextMinutes(minutes)) } ///Snoozes the notification for a number of hours. ///- parameter minutes: Hours to snooze the notification for. func snoozeForHours(_ hours: Int) { reschedule(fireDate: self.localNotification.fireDate!.nextHours(hours)) } ///Snoozes the notification for a number of days. ///- parameter minutes: Days to snooze the notification for. func snoozeForDays(_ days: Int) { reschedule(fireDate: self.localNotification.fireDate!.nextDays(days)) } ///- returns: The state of the notification. func isScheduled() -> Bool { return self.scheduled } ///Used by ABNotificationX classes to convert NSCalendarUnit enum to Repeats enum. ///- parameter calendarUnit: NSCalendarUnit to convert. ///- returns: Repeats type that is equivalent to the passed NSCalendarUnit. fileprivate class func calendarUnitToRepeats(calendarUnit cUnit: NSCalendar.Unit) -> Repeats { switch cUnit { case NSCalendar.Unit.hour: return .Hourly case NSCalendar.Unit.day: return .Daily case NSCalendar.Unit.weekOfYear: return .Weekly case NSCalendar.Unit.month: return .Monthly case NSCalendar.Unit.year: return .Yearly default: return Repeats.None } } ///Instantiates an ABNotification from a UILocalNotification. ///- parameter localNotification: The UILocalNotification to instantiate an ABNotification from. ///- returns: The instantiated ABNotification from the UILocalNotification. fileprivate class func notificationWithUILocalNotification(_ localNotification: UILocalNotification) -> ABNotification { let alertBody = localNotification.alertBody! let alertAction = localNotification.alertAction let soundName = localNotification.soundName let identifier = localNotification.userInfo![ABNScheduler.identifierKey] as! String let repeats = self.calendarUnitToRepeats(calendarUnit: localNotification.repeatInterval) let userInfo = localNotification.userInfo! return ABNotification(notification: localNotification, alertBody: alertBody, alertAction: alertAction, soundName: soundName, identifier: identifier, repeats: repeats, userInfo: userInfo as! Dictionary<String, AnyObject>, scheduled: true) } // MARK: NSCoding @objc convenience public required init?(coder aDecoder: NSCoder) { guard let localNotification = aDecoder.decodeObject(forKey: "ABNNotification") as? UILocalNotification else { return nil } guard let alertBody = aDecoder.decodeObject(forKey: "ABNAlertBody") as? String else { return nil } guard let identifier = aDecoder.decodeObject(forKey: "ABNIdentifier") as? String else { return nil } guard let userInfo = aDecoder.decodeObject(forKey: "ABNUserInfo") as? Dictionary<String, AnyObject> else { return nil } guard let repeats = aDecoder.decodeObject(forKey: "ABNRepeats") as? String else { return nil } guard let soundName = aDecoder.decodeObject(forKey: "ABNSoundName") as? String else { return nil } let alertAction = aDecoder.decodeObject(forKey: "ABNAlertAction") as? String self.init(notification: localNotification, alertBody: alertBody, alertAction: alertAction, soundName: soundName, identifier: identifier, repeats: Repeats(rawValue: repeats)!, userInfo: userInfo, scheduled: false) } @objc open func encode(with aCoder: NSCoder) { aCoder.encode(localNotification, forKey: "ABNNotification") aCoder.encode(alertBody, forKey: "ABNAlertBody") aCoder.encode(alertAction, forKey: "ABNAlertAction") aCoder.encode(soundName, forKey: "ABNSoundName") aCoder.encode(identifier, forKey: "ABNIdentifier") aCoder.encode(repeatInterval.rawValue, forKey: "ABNRepeats") aCoder.encode(userInfo, forKey: "ABNUserInfo") } } public func <(lhs: ABNotification, rhs: ABNotification) -> Bool { return lhs.localNotification.fireDate?.compare(rhs.localNotification.fireDate!) == ComparisonResult.orderedAscending } public func ==(lhs: ABNotification, rhs: ABNotification) -> Bool { return lhs.identifier == rhs.identifier } //MARK:- Extensions //MARK: NSDate extension Date { /** Add a number of minutes to a date. > This method can add and subtract minutes. - parameter minutes: The number of minutes to add. - returns: The date after the minutes addition. */ func nextMinutes(_ minutes: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.minute = minutes return (calendar as NSCalendar).date(byAdding: components, to: self, options: NSCalendar.Options(rawValue: 0))! } /** Add a number of hours to a date. > This method can add and subtract hours. - parameter hours: The number of hours to add. - returns: The date after the hours addition. */ func nextHours(_ hours: Int) -> Date { return self.nextMinutes(hours * 60) } /** Add a number of days to a date. >This method can add and subtract days. - parameter days: The number of days to add. - returns: The date after the days addition. */ func nextDays(_ days: Int) -> Date { return nextMinutes(days * 60 * 24) } func removeSeconds() -> Date { let calendar = Calendar.current let components = (calendar as NSCalendar).components([.year, .month, .day, .hour, .minute], from: self) return calendar.date(from: components)! } /** Creates a date object with the given time and offset. The offset is used to align the time with the GMT. - parameter time: The required time of the form HHMM. - parameter offset: The offset in minutes. - returns: Date with the specified time and offset. */ static func dateWithTime(_ time: Int, offset: Int) -> Date { let calendar = Calendar.current var components = (calendar as NSCalendar).components([.year, .month, .day, .hour, .minute], from: Date()) components.minute = (time % 100) + offset % 60 components.hour = (time / 100) + (offset / 60) var date = calendar.date(from: components)! if date < Date() { date = date.nextMinutes(60*24) } return date } } //MARK: Int extension Int { var date: Date { return Date.dateWithTime(self, offset: 0) } }
mit
7bf3ebc508e03527a0eff038e0f08da2
38.620529
245
0.653242
5.357729
false
false
false
false
samhann/SmartAttributedString
Example/SwiftAttributedString/SmartAttributedString.swift
1
6289
// // SmartAttributedString.swift // SwiftAttributedString // // Created by Samhan on 14/03/16. // Copyright © 2016 Samhan. All rights reserved. // import UIKit extension NSMutableParagraphStyle { func addLineSpacing(spacing : CGFloat)->NSMutableParagraphStyle { self.lineSpacing = spacing return self } func addLineHeightMultiple(multiple : CGFloat)->NSMutableParagraphStyle { self.lineHeightMultiple = multiple return self } func addMinimumLineHeight(minLineHeight : CGFloat)->NSMutableParagraphStyle { self.minimumLineHeight = minLineHeight return self } func addMaximumLineHeight(max : CGFloat)->NSMutableParagraphStyle { self.maximumLineHeight = max return self } func addParagraphSpacing(spacing : CGFloat)->NSMutableParagraphStyle { self.paragraphSpacing = spacing return self } func addAlignment(alignment : NSTextAlignment)->NSMutableParagraphStyle { self.alignment = alignment return self } func addHeadIndent(indent : CGFloat)->NSMutableParagraphStyle { self.headIndent = indent return self } func addTailIndent(indent : CGFloat)->NSMutableParagraphStyle { self.tailIndent = indent return self } func addFirstLineHeadIndent(indent : CGFloat)->NSMutableParagraphStyle { self.firstLineHeadIndent = indent return self } func addParagraphSpacingBefore(before : CGFloat)->NSMutableParagraphStyle { self.paragraphSpacingBefore = before return self } } class SmartAttributedString { var lastRange : NSRange? var mutableAttributedString : NSMutableAttributedString init() { mutableAttributedString = NSMutableAttributedString() } func appendAttributedString(attrString: NSAttributedString) { lastRange = NSMakeRange(mutableAttributedString.string.characters.count , attrString.string.characters.count) mutableAttributedString.appendAttributedString(attrString); } func add(let string : NSString)->SmartAttributedString { self.appendAttributedString(NSAttributedString(string: string as String)) return self } func color(let color : UIColor,range : NSRange? = nil)->SmartAttributedString { if let theRange = self.getValidRange(range) { mutableAttributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: theRange) } return self } func strikethrough(color : UIColor? = nil, range:NSRange? = nil)->SmartAttributedString { if let theRange = self.getValidRange(range) { mutableAttributedString.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(bool: true), range: theRange) if let theColor = color { mutableAttributedString.addAttribute(NSStrikethroughColorAttributeName, value: theColor, range: theRange) } } return self } func kerning(kerning : Double , range : NSRange? = nil)->SmartAttributedString { if let theRange = self.getValidRange(range) { mutableAttributedString.addAttribute(NSKernAttributeName, value: NSNumber(double: kerning), range: theRange) } return self } func superscriptStyle(range : NSRange? = nil)->SmartAttributedString { if let theRange = self.getValidRange(range) { mutableAttributedString.addAttribute(kCTSuperscriptAttributeName as String, value: NSNumber(int: 1), range: theRange) } return self } func subscriptStyle(range : NSRange? = nil)->SmartAttributedString { if let theRange = self.getValidRange(range) { mutableAttributedString.addAttribute(kCTSuperscriptAttributeName as String, value: NSNumber(int: -1), range: theRange) } return self } func baselineOffset(offset : Double , range : NSRange? = nil)->SmartAttributedString { if let theRange = self.getValidRange(range) { mutableAttributedString.addAttribute(NSBaselineOffsetAttributeName, value: NSNumber(double: offset), range: theRange) } return self } func paragraphStyle(paragraphStyle : NSParagraphStyle, range : NSRange? = nil)->SmartAttributedString { if let theRange = self.getValidRange(range) { mutableAttributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: theRange) } return self } func backgroundColor(let color : UIColor, range : NSRange? = nil)->SmartAttributedString { if let theRange = self.getValidRange(range) { mutableAttributedString.addAttribute(NSBackgroundColorAttributeName, value: color, range: theRange) } return self } func underline(color : UIColor? = nil,range : NSRange? = nil)->SmartAttributedString { if let theRange = self.getValidRange(range) { mutableAttributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(bool: true), range: theRange) if let theColor = color { mutableAttributedString.addAttribute(NSUnderlineColorAttributeName, value: theColor, range: theRange) } } return self } func getValidRange(range : NSRange?)->NSRange? { if let theRange = range { return theRange } else if let theLastRange = lastRange { return theLastRange } return nil } func font(let font : UIFont,range : NSRange? = nil)->SmartAttributedString { if let aRange = self.getValidRange(range) { mutableAttributedString.addAttribute(NSFontAttributeName, value: font, range: aRange) } return self } }
bsd-2-clause
7d9ba1e220cf7f9a56fea10a8967eb76
27.324324
130
0.62834
5.954545
false
false
false
false
stealthflyer/lock-door
Lock Door/Photon.swift
1
5741
// // Photon.swift // Lock Door // // Created by Aleks R on 9/19/15. // Copyright © 2015 Aleks R. All rights reserved. // import Foundation /// Helper class to control everything about the photon/spark device class Photon { var username = "" var password = "" var device = "" var photon : SparkDevice? /// Initialize the variables to be used by the device /// /// - parameters: /// - username: particle username /// - password: particle password /// - device: particle device name /// - returns: nothing init(username: String, password: String, device: String) { self.username = username self.password = password self.device = device //!!! eventually OAuth will be supported, then switch over } /// Request to log off and release the authentication token /// /// - parameter void /// - returns: nothing func logoff() { if photon != nil { SparkCloud.sharedInstance().logout() } } /// Request a login. Will login if necessary then call the success or failure closure /// /// - parameters: /// - success: function to call when login succeeds or already logged in /// - failure: function to call when login fails /// - returns: integer representing the error or -1 if no error func login(success: (() -> Int)? = nil, failure: ((error: Int) -> Void)? = nil) -> Int { var returnVal = -1 if photon == nil { SparkCloud.sharedInstance().loginWithUser(username, password: password) { (error:NSError!) -> Void in if (error != nil) { print("Wrong credentials or no internet connectivity, please try again", terminator: "\n") if let c = failure { c(error: 0) } } else { print("Logged in", terminator: "\n") SparkCloud.sharedInstance().getDevices { (sparkDevices:[AnyObject]!, error:NSError!) -> Void in if (error != nil) { print("Check your internet connectivity", terminator: "\n") if let c = failure { c(error: 1) } } else { if let devices = sparkDevices as? [SparkDevice] { for device in devices { if device.name == self.device { self.photon = device if let c = success { returnVal = c() } } } } if self.photon == nil { if let c = failure { c(error: 2) } } } } } } } else if let c = success { returnVal = c() } return returnVal } func close(closure: (() -> Void)? = nil) { function("###", closure: closure) } func open(closure: (() -> Void)? = nil) { function("####", closure: closure) } func closed(closure: ((val: Bool) -> Void)) { read("######", closure: closure) } func front(closure: ((val: Bool) -> Void)) { read("########", closure: closure) } func screen(closure: ((val: Bool) -> Void)) { read("#######", closure: closure) } /// Helper function to call a function /// /// - parameters: /// - method: method name /// - closure: function to call when success /// - returns: integer representing login errors func function(method: String, closure: (() -> Void)? = nil) { login({() -> Int in var returnVal = -1 self.photon?.callFunction(method, withArguments: []) { (resultCode : NSNumber!, error : NSError!) -> Void in if (error == nil) { print("\(method) succeeded", terminator: "\n") if let c = closure { c() } returnVal = 1 } else { print("\(method) failed", terminator: "\n") returnVal = 0 } } return returnVal }) } /// Helper function to read a variable and pass the results (assuming boolean for now) /// /// - parameters: /// - variable: variable name /// - closure: function to call when success /// - returns: integer representing login errors func read(variable : String, closure: ((val: Bool) -> Void)? = nil) -> Int { return login({() -> Int in var returnVal = -1 self.photon?.getVariable(variable, completion: { (result:AnyObject!, error:NSError!) -> Void in if (error != nil) { print("Failed get status", terminator: "\n") } else { if let r = result as? Int { returnVal = r if let c = closure { c(val: r == 1); } } } }) return returnVal }) } }
gpl-2.0
579a51b22620c4a2ae05202cc77221a5
33.584337
120
0.43223
5.314815
false
false
false
false
DrippApp/Dripp-iOS
Dripp/AppDelegate.swift
1
6936
// // AppDelegate.swift // Dripp // // Created by Henry Saniuk on 1/28/16. // Copyright © 2016 Henry Saniuk. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { enum ShortcutIdentifier: String { case First // MARK: Initializers init?(fullType: String) { guard let last = fullType.componentsSeparatedByString(".").last else { return nil } self.init(rawValue: last) } // MARK: Properties var type: String { return NSBundle.mainBundle().bundleIdentifier! + ".\(self.rawValue)" } } var window: UIWindow? /// Saved shortcut item used as a result of an app launch, used later when app is activated. var launchedShortcutItem: UIApplicationShortcutItem? func handleShortCutItem(shortcutItem: UIApplicationShortcutItem) -> Bool { var handled = false // Verify that the provided `shortcutItem`'s `type` is one handled by the application. guard ShortcutIdentifier(fullType: shortcutItem.type) != nil else { return false } guard let shortCutType = shortcutItem.type as String? else { return false } let storyboard = UIStoryboard(name: "Main", bundle: nil) var vc = UIViewController() switch (shortCutType) { case ShortcutIdentifier.First.type: // Handle shortcut 1 vc = storyboard.instantiateViewControllerWithIdentifier("startShower") as! ShowerViewController handled = true break default: break } // Display the selected view controller window!.rootViewController?.presentViewController(vc, animated: true, completion: nil) return handled } func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: Bool -> Void) { let handledShortCutItem = handleShortCutItem(shortcutItem) completionHandler(handledShortCutItem) } func applicationDidBecomeActive(application: UIApplication) { guard let shortcut = launchedShortcutItem else { return } handleShortCutItem(shortcut) launchedShortcutItem = nil } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let tabBarController = self.window!.rootViewController as! UITabBarController let tabBar = tabBarController.tabBar as UITabBar let inactiveColor = UIColor(hexString: "#91c8fb") for tabBarItem in tabBar.items! { tabBarItem.title = "" tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0) if let image = tabBarItem.image { tabBarItem.image = image.imageWithColor(inactiveColor).imageWithRenderingMode(.AlwaysOriginal) } } // Add background color to middle tabBarItem let bgColor = UIColor(hexString: "#3983c8") let itemWidth = tabBar.frame.width / CGFloat(tabBar.items!.count) let screenHeight = UIScreen.mainScreen().bounds.size.height let screenWidth = UIScreen.mainScreen().bounds.size.width let bgView = UIView(frame: CGRectMake((screenWidth/2) - (itemWidth/2), 0, itemWidth, tabBar.frame.height)) bgView.backgroundColor = bgColor tabBar.insertSubview(bgView, atIndex: 0) let bgView2 = UIView(frame: CGRectMake((screenWidth/2) - (itemWidth/2), (screenHeight-57), itemWidth, tabBar.frame.height/3)) bgView2.backgroundColor = bgColor bgView2.layer.cornerRadius = bgView2.frame.height/2 bgView2.layer.masksToBounds = false bgView2.clipsToBounds = true self.window!.rootViewController!.view.insertSubview(bgView2, aboveSubview: bgView) UINavigationBar.appearance().barTintColor = UIColor.blueHeader UIToolbar.appearance().barTintColor = UIColor.blueHeader UITabBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().tintColor = UIColor.whiteColor() UIToolbar.appearance().tintColor = UIColor.blueHeader UITabBar.appearance().barTintColor = UIColor.blueHeader UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()] UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blue3], forState: .Normal) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.whiteColor()], forState: .Selected) UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) } 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application( application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } }
mit
8e5dd79f61ea09278ab712c24548048f
43.178344
285
0.680317
5.862215
false
false
false
false
jakubholik/mi-ios
mi-ios/Global.swift
1
959
// // Global.swift // // Created by Jakub Holík on 16.04.17. // Copyright © 2017 Symphony No. 9 s.r.o. All rights reserved. // import Foundation class Global { let dateFormatter = "dd.MM.yyyy" let userDefaults = Foundation.UserDefaults.standard var language = "en" init() { self.loadAppLanguage() } func realmBundleURL(by name: String) -> URL? { return Bundle.main.url(forResource: name, withExtension: "realm") } func loadAppLanguage(){ var languageToSet = AppLanguage.english if let value = userDefaults.string(forKey: "language") { if let lang = AppLanguage(rawValue: value) { languageToSet = lang } } setAppLanguage(lang: languageToSet) } func setAppLanguage(lang: AppLanguage){ language = lang.rawValue userDefaults.set( language, forKey: "language") } } enum AppLanguage: String { case english = "en" case czech = "cs" case german = "de" }
mit
c3171beeae9e2db1890653872eecbff6
14.688525
67
0.649948
3.3
false
false
false
false
daisysomus/DSDanmakuPlayer
DSDanmakuPlayer/DSDanmakuPlayer/DSDanmakuLabel.swift
1
1888
// // DSDanmakuLabel.swift // DSDanmakuPlayer // // Created by liaojinhua on 15/7/15. // Copyright (c) 2015年 Daisy. All rights reserved. // import UIKit class DSDanmakuLabel: UILabel { var remainTime = NSTimeInterval(DSDanmakuAnimationInterval) var originalXPosition = CGFloat(0.0) var attribute:DSSanmakuAttribute = DSSanmakuAttribute() init(danmakuText:String, attribute:DSSanmakuAttribute) { self.attribute = attribute super.init(frame:CGRectZero) self.text = danmakuText self.configLabel() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func configLabel() { self.textColor = attribute.color; self.font = attribute.font self.sizeToFit() } func setPosition(position:CGPoint) { self.frame = CGRectMake(position.x, position.y, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)) originalXPosition = position.x } func calculateReaminTime(standWidth:Double) { remainTime = (NSTimeInterval)(CGRectGetMaxX(self.frame) + CGRectGetWidth(self.frame)) * remainTime/standWidth } func startPlay(complete:(Bool) -> Void) { UIView.animateWithDuration(remainTime, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.frame = CGRectMake(-CGRectGetWidth(self.frame), CGRectGetMinY(self.frame), CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)) }, completion: complete) } func pauseAnimation() { self.frame = self.layer.presentationLayer().frame var ratio = (NSTimeInterval)((CGRectGetMinX(self.frame) + CGRectGetWidth(self.frame))/(originalXPosition + CGRectGetWidth(self.frame))) remainTime = remainTime * ratio self.layer.removeAllAnimations() } }
mit
d00b7ec110dbbe27bccadbdfcb79feb8
31.517241
148
0.671792
4.42723
false
false
false
false
haawa799/WaniPersistance
WaniPersistance/UserSpecific.swift
1
3036
// // UserSpecific.swift // WaniKani // // Created by Andriy K. on 3/31/17. // Copyright © 2017 haawa. All rights reserved. // import Foundation import WaniModel import RealmSwift class UserSpecific: Object { dynamic var srs: String? let srsNumeric = RealmOptional<Int>() dynamic var unlockedDate: Date? dynamic var availableDate: Date? dynamic var burned: Bool = false dynamic var burnedDate: Date? let meaningCorrect = RealmOptional<Int>() let meaningIncorrect = RealmOptional<Int>() let meaningMaxStreak = RealmOptional<Int>() let meaningCurrentStreak = RealmOptional<Int>() let readingCorrect = RealmOptional<Int>() let readingIncorrect = RealmOptional<Int>() let readingMaxStreak = RealmOptional<Int>() let readingCurrentStreak = RealmOptional<Int>() dynamic var meaningNote: String? dynamic var userSynonyms: String? dynamic var readingNote: String? convenience init(userSpecific: WaniModel.UserSpecific) { self.init() self.srs = userSpecific.srs self.srsNumeric.value = userSpecific.srsNumeric self.unlockedDate = userSpecific.unlockedDate self.availableDate = userSpecific.availableDate self.burned = userSpecific.burned self.burnedDate = userSpecific.burnedDate self.meaningCorrect.value = userSpecific.meaningCorrect self.meaningIncorrect.value = userSpecific.meaningIncorrect self.meaningMaxStreak.value = userSpecific.meaningMaxStreak self.meaningCurrentStreak.value = userSpecific.meaningCurrentStreak self.readingCorrect.value = userSpecific.readingCorrect self.readingIncorrect.value = userSpecific.readingIncorrect self.readingMaxStreak.value = userSpecific.readingMaxStreak self.readingCurrentStreak.value = userSpecific.readingCurrentStreak self.meaningNote = userSpecific.meaningNote self.userSynonyms = userSpecific.userSynonyms self.readingNote = userSpecific.readingNote } var waniModelStruct: WaniModel.UserSpecific { return WaniModel.UserSpecific(realmObject: self) } } extension WaniModel.UserSpecific { init(realmObject: WaniPersistance.UserSpecific) { self.srs = realmObject.srs self.srsNumeric = realmObject.srsNumeric.value self.unlockedDate = realmObject.unlockedDate self.availableDate = realmObject.availableDate self.burned = realmObject.burned self.burnedDate = realmObject.burnedDate self.meaningCorrect = realmObject.meaningCorrect.value self.meaningIncorrect = realmObject.meaningIncorrect.value self.meaningMaxStreak = realmObject.meaningMaxStreak.value self.meaningCurrentStreak = realmObject.meaningCurrentStreak.value self.readingCorrect = realmObject.readingCorrect.value self.readingIncorrect = realmObject.readingIncorrect.value self.readingMaxStreak = realmObject.readingMaxStreak.value self.readingCurrentStreak = realmObject.readingCurrentStreak.value self.meaningNote = realmObject.meaningNote self.userSynonyms = realmObject.userSynonyms self.readingNote = realmObject.readingNote } }
mit
6ef3271f1f396192e55a5c61349f9759
36.9375
71
0.782537
4.787066
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Helpers/UIViewController+ErrorAlert.swift
1
4467
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import WireSyncEngine import WireCommonComponents extension UIViewController { func showAlert(for error: LocalizedError, handler: AlertActionHandler? = nil) { present(UIAlertController.alertWithOKButton(title: error.errorDescription, message: error.failureReason ?? "error.user.unkown_error".localized, okActionHandler: handler), animated: true) } func showAlert(for error: Error, handler: AlertActionHandler? = nil) { let nsError: NSError = error as NSError var message = "" if nsError.domain == ZMObjectValidationErrorDomain, let code: ZMManagedObjectValidationErrorCode = ZMManagedObjectValidationErrorCode(rawValue: nsError.code) { switch code { case .tooLong: message = "error.input.too_long".localized case .tooShort: message = "error.input.too_short".localized case .emailAddressIsInvalid: message = "error.email.invalid".localized case .phoneNumberContainsInvalidCharacters: message = "error.phone.invalid".localized default: break } } else if nsError.domain == NSError.ZMUserSessionErrorDomain, let code: ZMUserSessionErrorCode = ZMUserSessionErrorCode(rawValue: UInt(nsError.code)) { switch code { case .noError: message = "" case .needsCredentials: message = "error.user.needs_credentials".localized case .domainBlocked: message = "error.user.domain_blocked".localized case .invalidCredentials: message = "error.user.invalid_credentials".localized case .accountIsPendingActivation: message = "error.user.account_pending_activation".localized case .networkError: message = "error.user.network_error".localized case .emailIsAlreadyRegistered: message = "error.user.email_is_taken".localized case .phoneNumberIsAlreadyRegistered: message = "error.user.phone_is_taken".localized case .invalidPhoneNumberVerificationCode, .invalidEmailVerificationCode, .invalidActivationCode: message = "error.user.phone_code_invalid".localized case .registrationDidFailWithUnknownError: message = "error.user.registration_unknown_error".localized case .invalidPhoneNumber: message = "error.phone.invalid".localized case .invalidEmail: message = "error.email.invalid".localized case .codeRequestIsAlreadyPending: message = "error.user.phone_code_too_many".localized case .clientDeletedRemotely: message = "error.user.device_deleted_remotely".localized case .lastUserIdentityCantBeDeleted: message = "error.user.last_identity_cant_be_deleted".localized case .accountSuspended: message = "error.user.account_suspended".localized case .accountLimitReached: message = "error.user.account_limit_reached".localized case .unknownError: message = "error.user.unkown_error".localized default: message = "error.user.unkown_error".localized } } else { message = error.localizedDescription } let alert = UIAlertController.alertWithOKButton(message: message, okActionHandler: handler) present(alert, animated: true) } }
gpl-3.0
4eedb40ae5ee5ae4c1e59b2c18906ab1
44.121212
120
0.627043
5.158199
false
false
false
false
exponent/exponent
packages/expo-dev-menu-interface/ios/MenuItems/DevMenuExportedCallable.swift
2
1387
// Copyright 2015-present 650 Industries. All rights reserved. import Foundation import UIKit @objc public protocol DevMenuCallableProvider { @objc optional func registerCallable() -> DevMenuExportedCallable? } @objc public class DevMenuExportedCallable: NSObject { @objc public let id: String @objc init(withId id: String) { self.id = id } } @objc public class DevMenuExportedFunction: DevMenuExportedCallable { @objc public var function: ([String: Any]?) -> Void @objc public init(withId id: String, withFunction function: @escaping ([String: Any]?) -> Void) { self.function = function super.init(withId: id) } public func call(args: [String: Any]?) { function(args) } } @objc public class DevMenuExportedAction: DevMenuExportedCallable { @objc public var action: () -> Void @objc public private(set) var keyCommand: UIKeyCommand? @objc public var isAvailable: () -> Bool = { true } @objc public init(withId id: String, withAction action: @escaping () -> Void) { self.action = action super.init(withId: id) } public func call() { action() } @objc public func registerKeyCommand(input: String, modifiers: UIKeyModifierFlags) { keyCommand = UIKeyCommand(input: input, modifierFlags: modifiers, action: #selector(DevMenuUIResponderExtensionProtocol.EXDevMenu_handleKeyCommand(_:))) } }
bsd-3-clause
ed0b6a7488540fbefc91c09f40fda895
20.671875
156
0.703677
4.067449
false
false
false
false
Pluto-tv/RxSwift
RxSwift/Observables/Implementations/Sink.swift
1
1313
// // Sink.swift // Rx // // Created by Krunoslav Zaher on 2/19/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Sink<O : ObserverType> : Disposable { private var _lock = SpinLock() // state private var _observer: O? private var _cancel: Disposable private var _disposed: Bool = false var observer: O? { get { return _lock.calculateLocked { _observer } } } var cancel: Disposable { get { return _lock.calculateLocked { _cancel } } } init(observer: O, cancel: Disposable) { #if TRACE_RESOURCES OSAtomicIncrement32(&resourceCount) #endif _observer = observer _cancel = cancel } func dispose() { let cancel: Disposable? = _lock.calculateLocked { if _disposed { return nil } let cancel = _cancel _disposed = true _observer = nil _cancel = NopDisposable.instance return cancel } if let cancel = cancel { cancel.dispose() } } deinit { #if TRACE_RESOURCES OSAtomicDecrement32(&resourceCount) #endif } }
mit
52d5b0f711a06774a59848c16c4d1775
19.53125
60
0.516375
4.774545
false
false
false
false
LoopKit/LoopKit
LoopKit/InsulinKit/InsulinMath.swift
1
27059
// // InsulinMath.swift // Naterade // // Created by Nathan Racklyeft on 1/30/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit extension DoseEntry { private func continuousDeliveryInsulinOnBoard(at date: Date, model: InsulinModel, delta: TimeInterval) -> Double { let doseDuration = endDate.timeIntervalSince(startDate) // t1 let time = date.timeIntervalSince(startDate) var iob: Double = 0 var doseDate = TimeInterval(0) // i repeat { let segment: Double if doseDuration > 0 { segment = max(0, min(doseDate + delta, doseDuration) - doseDate) / doseDuration } else { segment = 1 } iob += segment * model.percentEffectRemaining(at: time - doseDate) doseDate += delta } while doseDate <= min(floor((time + model.delay) / delta) * delta, doseDuration) return iob } func insulinOnBoard(at date: Date, model: InsulinModel, delta: TimeInterval) -> Double { let time = date.timeIntervalSince(startDate) guard time >= 0 else { return 0 } // Consider doses within the delta time window as momentary if endDate.timeIntervalSince(startDate) <= 1.05 * delta { return netBasalUnits * model.percentEffectRemaining(at: time) } else { return netBasalUnits * continuousDeliveryInsulinOnBoard(at: date, model: model, delta: delta) } } private func continuousDeliveryGlucoseEffect(at date: Date, model: InsulinModel, delta: TimeInterval) -> Double { let doseDuration = endDate.timeIntervalSince(startDate) // t1 let time = date.timeIntervalSince(startDate) var value: Double = 0 var doseDate = TimeInterval(0) // i repeat { let segment: Double if doseDuration > 0 { segment = max(0, min(doseDate + delta, doseDuration) - doseDate) / doseDuration } else { segment = 1 } value += segment * (1.0 - model.percentEffectRemaining(at: time - doseDate)) doseDate += delta } while doseDate <= min(floor((time + model.delay) / delta) * delta, doseDuration) return value } func glucoseEffect(at date: Date, model: InsulinModel, insulinSensitivity: Double, delta: TimeInterval) -> Double { let time = date.timeIntervalSince(startDate) guard time >= 0 else { return 0 } // Consider doses within the delta time window as momentary if endDate.timeIntervalSince(startDate) <= 1.05 * delta { return netBasalUnits * -insulinSensitivity * (1.0 - model.percentEffectRemaining(at: time)) } else { return netBasalUnits * -insulinSensitivity * continuousDeliveryGlucoseEffect(at: date, model: model, delta: delta) } } func trimmed(from start: Date? = nil, to end: Date? = nil, syncIdentifier: String? = nil) -> DoseEntry { let originalDuration = endDate.timeIntervalSince(startDate) let startDate = max(start ?? .distantPast, self.startDate) let endDate = max(startDate, min(end ?? .distantFuture, self.endDate)) var trimmedDeliveredUnits: Double? = deliveredUnits var trimmedValue: Double = value if originalDuration > .ulpOfOne && (startDate > self.startDate || endDate < self.endDate) { let updatedActualDelivery = unitsInDeliverableIncrements * (endDate.timeIntervalSince(startDate) / originalDuration) if deliveredUnits != nil { trimmedDeliveredUnits = updatedActualDelivery } if case .units = unit { trimmedValue = updatedActualDelivery } } return DoseEntry( type: type, startDate: startDate, endDate: endDate, value: trimmedValue, unit: unit, deliveredUnits: trimmedDeliveredUnits, description: description, syncIdentifier: syncIdentifier, scheduledBasalRate: scheduledBasalRate, insulinType: insulinType, automatic: automatic, isMutable: isMutable, wasProgrammedByPumpUI: wasProgrammedByPumpUI ) } } /** It takes a MM x22 pump about 40s to deliver 1 Unit while bolusing See: http://www.healthline.com/diabetesmine/ask-dmine-speed-insulin-pumps#3 The x23 and newer pumps can deliver at 2x, 3x, and 4x that speed, targeting a maximum 5-minute delivery for all boluses (8U - 25U) A basal rate of 30 U/hour (near-max) would deliver an additional 0.5 U/min. */ private let MaximumReservoirDropPerMinute = 6.5 extension Collection where Element: ReservoirValue { /** Converts a continuous, chronological sequence of reservoir values to a sequence of doses This is an O(n) operation. - returns: An array of doses */ var doseEntries: [DoseEntry] { var doses: [DoseEntry] = [] var previousValue: Element? let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal numberFormatter.maximumFractionDigits = 3 for value in self { if let previousValue = previousValue { let volumeDrop = previousValue.unitVolume - value.unitVolume let duration = value.startDate.timeIntervalSince(previousValue.startDate) if duration > 0 && 0 <= volumeDrop && volumeDrop <= MaximumReservoirDropPerMinute * duration.minutes { doses.append(DoseEntry( type: .tempBasal, startDate: previousValue.startDate, endDate: value.startDate, value: volumeDrop, unit: .units )) } } previousValue = value } return doses } /** Whether a span of chronological reservoir values is considered continuous and therefore reliable. Reservoir values of 0 are automatically considered unreliable due to the assumption that an unknown amount of insulin can be delivered after the 0 marker. - parameter startDate: The beginning of the interval in which to validate continuity - parameter endDate: The end of the interval in which to validate continuity - parameter maximumDuration: The maximum interval to consider reliable for a reservoir-derived dose - returns: Whether the reservoir values meet the critera for continuity */ func isContinuous(from start: Date?, to end: Date, within maximumDuration: TimeInterval) -> Bool { guard let firstValue = self.first else { return false } // The first value has to be at least as old as the start date, as a reference point. let startDate = start ?? firstValue.endDate guard firstValue.endDate <= startDate else { return false } var lastValue = firstValue for value in self { defer { lastValue = value } // Volume and interval validation only applies for values in the specified range, guard value.endDate >= startDate && value.startDate <= end else { continue } // We can't trust 0. What else was delivered? guard value.unitVolume > 0 else { return false } // Rises in reservoir volume indicate a rewind + prime, and primes // can be easily confused with boluses. // Small rises (1 U) can be ignored as they're indicative of a mixed-precision sequence. guard value.unitVolume <= lastValue.unitVolume + 1 else { return false } // Ensure no more than the maximum interval has passed guard value.startDate.timeIntervalSince(lastValue.endDate) <= maximumDuration else { return false } } return true } } extension DoseEntry { /// Annotates a dose with the context of the scheduled basal rate /// /// If the dose crosses a schedule boundary, it will be split into multiple doses so each dose has a /// single scheduled basal rate. /// /// - Parameter basalSchedule: The basal rate schedule to apply /// - Returns: An array of annotated doses fileprivate func annotated(with basalSchedule: BasalRateSchedule) -> [DoseEntry] { switch type { case .tempBasal, .suspend, .resume: guard scheduledBasalRate == nil else { return [self] } break case .basal, .bolus: return [self] } var doses: [DoseEntry] = [] let basalItems = basalSchedule.between(start: startDate, end: endDate) for (index, basalItem) in basalItems.enumerated() { let startDate: Date let endDate: Date // If we're splitting into multiple entries, keep the syncIdentifier unique var syncIdentifier = self.syncIdentifier if syncIdentifier != nil, basalItems.count > 1 { syncIdentifier! += " \(index + 1)/\(basalItems.count)" } if index == 0 { startDate = self.startDate } else { startDate = basalItem.startDate } if index == basalItems.count - 1 { endDate = self.endDate } else { endDate = basalItems[index + 1].startDate } var dose = trimmed(from: startDate, to: endDate, syncIdentifier: syncIdentifier) dose.scheduledBasalRate = HKQuantity(unit: DoseEntry.unitsPerHour, doubleValue: basalItem.value) doses.append(dose) } return doses } /// Annotates a dose with the specified insulin type. /// /// - Parameter insulinType: The insulin type to annotate the dose with. /// - Returns: A dose annotated with the insulin model public func annotated(with insulinType: InsulinType) -> DoseEntry { return DoseEntry( type: type, startDate: startDate, endDate: endDate, value: value, unit: unit, deliveredUnits: deliveredUnits, description: description, syncIdentifier: syncIdentifier, scheduledBasalRate: scheduledBasalRate, insulinType: insulinType, isMutable: isMutable, wasProgrammedByPumpUI: wasProgrammedByPumpUI ) } } extension DoseEntry { /// Calculates the timeline of glucose effects for a temp basal dose /// Use case: predict glucose effects of zero temping /// /// - Parameters: /// - insulinModelProvider: A factory that can provide an insulin model given an insulin type /// - longestEffectDuration: The longest duration that a dose could be active. /// - defaultInsulinModelSetting: The model of insulin activity over time /// - insulinSensitivity: The schedule of glucose effect per unit of insulin /// - basalRateSchedule: The schedule of basal rates /// - Returns: An array of glucose effects for the duration of the temp basal dose plus the duration of insulin action public func tempBasalGlucoseEffects( insulinModelProvider: InsulinModelProvider, longestEffectDuration: TimeInterval, insulinSensitivity: InsulinSensitivitySchedule, basalRateSchedule: BasalRateSchedule ) -> [GlucoseEffect] { guard case .tempBasal = type else { return [] } let netTempBasalDoses = self.annotated(with: basalRateSchedule) return netTempBasalDoses.glucoseEffects(insulinModelProvider: insulinModelProvider, longestEffectDuration: longestEffectDuration, insulinSensitivity: insulinSensitivity) } fileprivate var resolvingDelivery: DoseEntry { guard !isMutable, deliveredUnits == nil else { return self } let resolvedUnits: Double if case .units = unit { resolvedUnits = value } else { switch type { case .tempBasal: resolvedUnits = unitsInDeliverableIncrements case .basal: resolvedUnits = programmedUnits default: return self } } return DoseEntry(type: type, startDate: startDate, endDate: endDate, value: value, unit: unit, deliveredUnits: resolvedUnits, description: description, syncIdentifier: syncIdentifier, scheduledBasalRate: scheduledBasalRate, insulinType: insulinType, isMutable: isMutable, wasProgrammedByPumpUI: wasProgrammedByPumpUI) } } extension Collection where Element == DoseEntry { /** Maps a timeline of dose entries with overlapping start and end dates to a timeline of doses that represents actual insulin delivery. - returns: An array of reconciled insulin delivery history, as TempBasal and Bolus records */ func reconciled() -> [DoseEntry] { var reconciled: [DoseEntry] = [] var lastSuspend: DoseEntry? var lastBasal: DoseEntry? for dose in self { switch dose.type { case .bolus: reconciled.append(dose) case .basal, .tempBasal: if lastSuspend == nil, let last = lastBasal { let endDate = Swift.min(last.endDate, dose.startDate) // Ignore 0-duration doses if endDate > last.startDate { reconciled.append(last.trimmed(from: nil, to: endDate, syncIdentifier: last.syncIdentifier)) } } else if let suspend = lastSuspend, dose.type == .tempBasal { // Handle missing resume. Basal following suspend, with no resume. reconciled.append(DoseEntry( type: suspend.type, startDate: suspend.startDate, endDate: dose.startDate, value: suspend.value, unit: suspend.unit, description: suspend.description ?? dose.description, syncIdentifier: suspend.syncIdentifier, insulinType: suspend.insulinType, isMutable: suspend.isMutable, wasProgrammedByPumpUI: suspend.wasProgrammedByPumpUI )) lastSuspend = nil } lastBasal = dose case .resume: if let suspend = lastSuspend { reconciled.append(DoseEntry( type: suspend.type, startDate: suspend.startDate, endDate: dose.startDate, value: suspend.value, unit: suspend.unit, description: suspend.description ?? dose.description, syncIdentifier: suspend.syncIdentifier, insulinType: suspend.insulinType, isMutable: suspend.isMutable, wasProgrammedByPumpUI: suspend.wasProgrammedByPumpUI )) lastSuspend = nil // Continue temp basals that may have started before suspending if let last = lastBasal { if last.endDate > dose.endDate { lastBasal = DoseEntry( type: last.type, startDate: dose.endDate, endDate: last.endDate, value: last.value, unit: last.unit, description: last.description, // We intentionally use the resume's identifier, as the basal entry has already been entered syncIdentifier: dose.syncIdentifier, insulinType: last.insulinType, automatic: last.automatic, isMutable: last.isMutable, wasProgrammedByPumpUI: last.wasProgrammedByPumpUI ) } else { lastBasal = nil } } } case .suspend: if let last = lastBasal { reconciled.append(DoseEntry( type: last.type, startDate: last.startDate, endDate: Swift.min(last.endDate, dose.startDate), value: last.value, unit: last.unit, description: last.description, syncIdentifier: last.syncIdentifier, insulinType: last.insulinType, isMutable: last.isMutable, wasProgrammedByPumpUI: last.wasProgrammedByPumpUI )) if last.endDate <= dose.startDate { lastBasal = nil } } lastSuspend = dose } } if let suspend = lastSuspend { reconciled.append(suspend) } else if let last = lastBasal, last.endDate > last.startDate { reconciled.append(last) } return reconciled.map { $0.resolvingDelivery } } /// Annotates a sequence of dose entries with the configured basal rate schedule. /// /// Doses which cross time boundaries in the basal rate schedule are split into multiple entries. /// /// - Parameter basalSchedule: The basal rate schedule /// - Returns: An array of annotated dose entries func annotated(with basalSchedule: BasalRateSchedule) -> [DoseEntry] { var annotatedDoses: [DoseEntry] = [] for dose in self { annotatedDoses += dose.annotated(with: basalSchedule) } return annotatedDoses } /** Calculates the total insulin delivery for a collection of doses - returns: The total insulin insulin, in Units */ var totalDelivery: Double { return reduce(0) { (total, dose) -> Double in return total + dose.unitsInDeliverableIncrements } } /** Calculates the timeline of insulin remaining for a collection of doses - parameter insulinModelProvider: A factory that can provide an insulin model given an insulin type - parameter longestEffectDuration: The longest duration that a dose could be active. - parameter start: The date to start the timeline - parameter end: The date to end the timeline - parameter delta: The differential between timeline entries - returns: A sequence of insulin amount remaining */ func insulinOnBoard( insulinModelProvider: InsulinModelProvider, longestEffectDuration: TimeInterval, from start: Date? = nil, to end: Date? = nil, delta: TimeInterval = TimeInterval(minutes: 5) ) -> [InsulinValue] { guard let (start, end) = LoopMath.simulationDateRangeForSamples(self, from: start, to: end, duration: longestEffectDuration, delta: delta) else { return [] } var date = start var values = [InsulinValue]() repeat { let value = reduce(0) { (value, dose) -> Double in return value + dose.insulinOnBoard(at: date, model: insulinModelProvider.model(for: dose.insulinType), delta: delta) } values.append(InsulinValue(startDate: date, value: value)) date = date.addingTimeInterval(delta) } while date <= end return values } /// Calculates the timeline of glucose effects for a collection of doses /// /// - Parameters: /// - insulinModelProvider: A factory that can provide an insulin model given an insulin type /// - longestEffectDuration: The longest duration that a dose could be active. /// - insulinSensitivity: The schedule of glucose effect per unit of insulin /// - start: The earliest date of effects to return /// - end: The latest date of effects to return /// - delta: The interval between returned effects /// - Returns: An array of glucose effects for the duration of the doses public func glucoseEffects( insulinModelProvider: InsulinModelProvider, longestEffectDuration: TimeInterval, insulinSensitivity: InsulinSensitivitySchedule, from start: Date? = nil, to end: Date? = nil, delta: TimeInterval = TimeInterval(/* minutes: */60 * 5) ) -> [GlucoseEffect] { guard let (start, end) = LoopMath.simulationDateRangeForSamples(self.filter({ entry in entry.netBasalUnits != 0 }), from: start, to: end, duration: longestEffectDuration, delta: delta) else { return [] } var date = start var values = [GlucoseEffect]() let unit = HKUnit.milligramsPerDeciliter repeat { let value = reduce(0) { (value, dose) -> Double in return value + dose.glucoseEffect(at: date, model: insulinModelProvider.model(for: dose.insulinType), insulinSensitivity: insulinSensitivity.quantity(at: dose.startDate).doubleValue(for: unit), delta: delta) } values.append(GlucoseEffect(startDate: date, quantity: HKQuantity(unit: unit, doubleValue: value))) date = date.addingTimeInterval(delta) } while date <= end return values } /// Applies the current basal schedule to a collection of reconciled doses in chronological order /// /// The scheduled basal rate is associated doses that override it, for later derivation of net delivery /// /// - Parameters: /// - basalSchedule: The active basal schedule during the dose delivery /// - start: The earliest date to apply the basal schedule /// - end: The latest date to include. Doses must end before this time to be included. /// - insertingBasalEntries: Whether basal doses should be created from the schedule. Pass true only for pump models that do not report their basal rates in event history. /// - Returns: An array of doses, func overlayBasalSchedule(_ basalSchedule: BasalRateSchedule, startingAt start: Date, endingAt end: Date = .distantFuture, insertingBasalEntries: Bool) -> [DoseEntry] { let dateFormatter = ISO8601DateFormatter() // GMT-based ISO formatting var newEntries = [DoseEntry]() var lastBasal: DoseEntry? if insertingBasalEntries { // Create a placeholder entry at our start date, so we know the correct duration of the // inserted basal entries lastBasal = DoseEntry(resumeDate: start) } for dose in self { switch dose.type { case .tempBasal, .basal, .suspend: // Only include entries if they have ended by the end date, since they may be cancelled guard dose.endDate <= end else { continue } if let lastBasal = lastBasal { if insertingBasalEntries { // For older pumps which don't report the start/end of scheduled basal delivery, // generate a basal entry from the specified schedule. for scheduled in basalSchedule.between(start: lastBasal.endDate, end: dose.startDate) { // Generate a unique identifier based on the start/end timestamps let start = Swift.max(lastBasal.endDate, scheduled.startDate) let end = Swift.min(dose.startDate, scheduled.endDate) guard end.timeIntervalSince(start) > .ulpOfOne else { continue } let syncIdentifier = "BasalRateSchedule \(dateFormatter.string(from: start)) \(dateFormatter.string(from: end))" newEntries.append(DoseEntry( type: .basal, startDate: start, endDate: end, value: scheduled.value, unit: .unitsPerHour, syncIdentifier: syncIdentifier, scheduledBasalRate: HKQuantity(unit: .internationalUnitsPerHour, doubleValue: scheduled.value), insulinType: lastBasal.insulinType, automatic: lastBasal.automatic )) } } } lastBasal = dose // Only include the last basal entry if has ended by our end date if let lastBasal = lastBasal { newEntries.append(lastBasal) } case .resume: assertionFailure("No resume events should be present in reconciled doses") case .bolus: newEntries.append(dose) } } return newEntries } /// Creates an array of DoseEntry values by unioning another array, de-duplicating by syncIdentifier /// /// - Parameter otherDoses: An array of doses to union /// - Returns: A new array of doses func appendedUnion(with otherDoses: [DoseEntry]) -> [DoseEntry] { var union: [DoseEntry] = [] var syncIdentifiers: Set<String> = [] for dose in (self + otherDoses) { if let syncIdentifier = dose.syncIdentifier { let (inserted, _) = syncIdentifiers.insert(syncIdentifier) if !inserted { continue } } union.append(dose) } return union } } extension BidirectionalCollection where Element == DoseEntry { /// The endDate of the last basal dose in the collection var lastBasalEndDate: Date? { for dose in self.reversed() { if dose.type == .basal || dose.type == .tempBasal || dose.type == .resume { return dose.endDate } } return nil } }
mit
1a8abe08572031209d11c673c18201c9
38.157742
325
0.577981
5.611365
false
false
false
false
PureSwift/GATT
Package.swift
1
3192
// swift-tools-version:5.5 import PackageDescription import class Foundation.ProcessInfo // force building as dynamic library let dynamicLibrary = ProcessInfo.processInfo.environment["SWIFT_BUILD_DYNAMIC_LIBRARY"] != nil let libraryType: PackageDescription.Product.Library.LibraryType? = dynamicLibrary ? .dynamic : nil var package = Package( name: "GATT", platforms: [ .macOS(.v10_15), .iOS(.v13), .watchOS(.v6), .tvOS(.v13), ], products: [ .library( name: "GATT", type: libraryType, targets: ["GATT"] ), .library( name: "DarwinGATT", targets: ["DarwinGATT"] ) ], dependencies: [ .package( url: "https://github.com/PureSwift/Bluetooth.git", .upToNextMajor(from: "6.0.0") ) ], targets: [ .target( name: "GATT", dependencies: [ .product( name: "Bluetooth", package: "Bluetooth" ), .product( name: "BluetoothGATT", package: "Bluetooth", condition: .when(platforms: [.macOS, .linux]) ), .product( name: "BluetoothGAP", package: "Bluetooth", condition: .when(platforms: [.macOS, .linux]) ), .product( name: "BluetoothHCI", package: "Bluetooth", condition: .when(platforms: [.macOS, .linux]) ), ] ), .target( name: "DarwinGATT", dependencies: [ "GATT", .product( name: "BluetoothGATT", package: "Bluetooth", condition: .when(platforms: [.macOS]) ) ] ), .testTarget( name: "GATTTests", dependencies: [ "GATT", .product( name: "Bluetooth", package: "Bluetooth" ), .product( name: "BluetoothGATT", package: "Bluetooth", condition: .when(platforms: [.macOS, .linux]) ), .product( name: "BluetoothGAP", package: "Bluetooth", condition: .when(platforms: [.macOS, .linux]) ), .product( name: "BluetoothHCI", package: "Bluetooth", condition: .when(platforms: [.macOS, .linux]) ) ] ) ] ) // SwiftPM command plugins are only supported by Swift version 5.6 and later. #if swift(>=5.6) let buildDocs = ProcessInfo.processInfo.environment["BUILDING_FOR_DOCUMENTATION_GENERATION"] != nil if buildDocs { package.dependencies += [ .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"), ] } #endif
mit
94f04a619c96fa3d438dd4cd586dd7bc
29.113208
99
0.440163
4.933539
false
false
false
false
rwbutler/TypographyKit
TypographyKit/Classes/Typography.swift
1
10956
// // Typography.swift // TypographyKit // // Created by Ross Butler on 5/16/17. // // import UIKit public struct Typography { public let name: String public let fontName: String? public let maximumPointSize: Float? public let minimumPointSize: Float? public let pointSize: Float? // base point size for font public var letterCase: LetterCase? public var letterSpacing: Double = 0 public var scalingMode: ScalingMode? public var textColor: UIColor? private let textStyle: UIFont.TextStyle private static let contentSizeCategoryMap: [UIContentSizeCategory: Float] = [ UIContentSizeCategory.extraSmall: -3, UIContentSizeCategory.small: -2, UIContentSizeCategory.medium: -1, UIContentSizeCategory.large: 0, UIContentSizeCategory.extraLarge: 1, UIContentSizeCategory.extraExtraLarge: 2, UIContentSizeCategory.extraExtraExtraLarge: 3, UIContentSizeCategory.accessibilityMedium: 4, UIContentSizeCategory.accessibilityLarge: 5, UIContentSizeCategory.accessibilityExtraLarge: 6, UIContentSizeCategory.accessibilityExtraExtraLarge: 7, UIContentSizeCategory.accessibilityExtraExtraExtraLarge: 8 ] private static let fontWeightMap: [String: UIFont.Weight] = [ "black": UIFont.Weight.black, "bold": UIFont.Weight.bold, "heavy": UIFont.Weight.heavy, "light": UIFont.Weight.light, "medium": UIFont.Weight.medium, "regular": UIFont.Weight.regular, "semibold": UIFont.Weight.semibold, "thin": UIFont.Weight.thin, "ultraLight": UIFont.Weight.ultraLight, // Alternatives we wish to make parseable. "semi-bold": UIFont.Weight.semibold, "ultra-light": UIFont.Weight.ultraLight ] private static let boldSystemFontName = "Bold\(systemFontName)" private static let italicSystemFontName = "Italic\(systemFontName)" private static let monospacedDigitSystemFontName = "MonospacedDigit\(systemFontName)" private static let systemFontName = "System" public init?(for textStyle: UIFont.TextStyle, scalingMode: ScalingMode? = nil) { guard let typographyStyle = TypographyKit.fontTextStyles[textStyle.rawValue] else { return nil } self.name = typographyStyle.name self.fontName = typographyStyle.fontName self.maximumPointSize = typographyStyle.maximumPointSize self.minimumPointSize = typographyStyle.minimumPointSize self.pointSize = typographyStyle.pointSize self.letterCase = typographyStyle.letterCase self.letterSpacing = typographyStyle.letterSpacing self.scalingMode = scalingMode ?? typographyStyle.scalingMode self.textColor = typographyStyle.textColor self.textStyle = textStyle } public init( name: String, fontName: String? = nil, fontSize: Float? = nil, letterCase: LetterCase? = nil, letterSpacing: Double = 0, maximumPointSize: Float? = nil, minimumPointSize: Float? = nil, scalingMode: ScalingMode? = nil, textColor: UIColor? = nil ) { self.name = name self.fontName = fontName self.maximumPointSize = maximumPointSize self.minimumPointSize = minimumPointSize self.pointSize = fontSize self.letterCase = letterCase self.letterSpacing = letterSpacing self.scalingMode = scalingMode self.textColor = textColor self.textStyle = UIFont.TextStyle(rawValue: name) } /// Convenience method for retrieving the font for the preferred `UIContentSizeCategory`. public func font() -> UIFont? { return font(UIApplication.shared.preferredContentSizeCategory) } /// Returns a `UIFont` scaled appropriately for the given `UIContentSizeCategory` using the specified scaling /// method. public func font(_ contentSizeCategory: UIContentSizeCategory) -> UIFont? { guard let fontName = self.fontName, let pointSize = self.pointSize else { return nil } switch resolvedScalingMode() { case .fontMetrics: if #available(iOS 11.0, *) { return scaleUsingFontMetrics( fontName, pointSize: pointSize, textStyle: textStyle, contentSizeCategory: contentSizeCategory ) } return nil case .fontMetricsWithSteppingFallback: if #available(iOS 11.0, *), let scaledFont = scaleUsingFontMetrics( fontName, pointSize: pointSize, textStyle: textStyle, contentSizeCategory: contentSizeCategory) { return scaledFont } return scaleUsingStepping(fontName, pointSize: pointSize, contentSize: contentSizeCategory) case .stepping: return scaleUsingStepping(fontName, pointSize: pointSize, contentSize: contentSizeCategory) case .disabled: return font(fontName, pointSize: pointSize) } } /// Convenience method for retrieving the line height. public func lineHeight() -> CGFloat? { return font()?.lineHeight } } private extension Typography { private func resolvedMaxPointSize() -> Float? { return maximumPointSize ?? TypographyKit.maximumPointSize } private func resolvedMinPointSize() -> Float? { return minimumPointSize ?? TypographyKit.minimumPointSize } private func resolvedScalingMode() -> ScalingMode { return scalingMode ?? TypographyKit.scalingMode } /// Resolves font definitions defined in configuration to the system font with the specified `UIFont.Weight`. /// e.g. 'system-ultra-light' resolves to the system font with `UIFont.Weight` of `.ultraLight`. private func resolveSystemFont(_ fontName: String, pointSize: Float) -> UIFont? { let lowerCasedFontName = fontName.lowercased() let points = CGFloat(pointSize) if let unweightedFont = unweightedSystemFont(fontName, pointSize: points) { return unweightedFont } let lowerCasedSystemFontName = type(of: self).systemFontName.lowercased() let lowerCasedMonospacedDigitSystemFontName = type(of: self).monospacedDigitSystemFontName.lowercased() let fontWeights = type(of: self).fontWeightMap for (fontWeightName, fontWeight) in fontWeights { let lowercasedFontWeightName = fontWeightName.lowercased() let systemFontWithWeightName = "\(lowerCasedSystemFontName)-\(lowercasedFontWeightName)" if lowerCasedFontName == systemFontWithWeightName { return UIFont.systemFont(ofSize: points, weight: fontWeight) } let monospacedDigitFontWithWeightName = "\(lowerCasedMonospacedDigitSystemFontName)-\(lowercasedFontWeightName)" if #available(iOS 9.0, *), lowerCasedFontName == monospacedDigitFontWithWeightName { return UIFont.monospacedDigitSystemFont(ofSize: points, weight: fontWeight) } } return nil } /// Scales `UIFont` using a `UIFontMetrics` obtained from a `UIFont.TextStyle` introduced in iOS 11.0. @available(iOS 11.0, *) private func scaleUsingFontMetrics( _ fontName: String, pointSize: Float, textStyle: UIFont.TextStyle, contentSizeCategory: UIContentSizeCategory ) -> UIFont? { guard var newFont = font(fontName, pointSize: pointSize) else { return nil } let traitCollection = UITraitCollection(preferredContentSizeCategory: contentSizeCategory) if let maxPointSize = resolvedMaxPointSize() { newFont = UIFontMetrics.default.scaledFont( for: newFont, maximumPointSize: CGFloat(maxPointSize), compatibleWith: traitCollection ) } else { newFont = UIFontMetrics.default.scaledFont(for: newFont, compatibleWith: traitCollection) } if let minimumPointSize = resolvedMinPointSize(), newFont.pointSize < CGFloat(minimumPointSize) { return font(fontName, pointSize: minimumPointSize) } else { return newFont } } /// Scales `UIFont` using a step size * multiplier increasing in-line with the `UIContentSizeCategory` value. private func scaleUsingStepping(_ fontName: String, pointSize: Float, contentSize: UIContentSizeCategory) -> UIFont? { // No scaling if the UIContentSizeCategory cannot be found in map. let defaultContentSizeCategoryScaling: Float = 0.0 let contentSizeCategoryScaling = type(of: self).contentSizeCategoryMap[contentSize] ?? defaultContentSizeCategoryScaling let stepSizeMultiplier = TypographyKit.pointStepMultiplier let stepSize = TypographyKit.pointStepSize var newPointSize = pointSize + (stepSize * stepSizeMultiplier * contentSizeCategoryScaling) if let minimumPointSize = resolvedMinPointSize(), newPointSize < minimumPointSize { newPointSize = minimumPointSize } if let maximumPointSize = resolvedMaxPointSize(), maximumPointSize < newPointSize { newPointSize = maximumPointSize } return font(fontName, pointSize: newPointSize) } private func font(_ fontName: String, pointSize: Float) -> UIFont? { resolveSystemFont(fontName, pointSize: pointSize) ?? UIFont(name: fontName, size: CGFloat(pointSize)) } /// Resolves font entries in configuration to the following `UIFont` methods: /// System -> systemFont(ofSize: CGFloat) -> UIFont /// BoldSystem -> boldSystemFont(ofSize: CGFloat) -> UIFont /// ItalicSystem -> italicSystemFont(ofSize: CGFloat) -> UIFont private func unweightedSystemFont(_ fontName: String, pointSize: CGFloat) -> UIFont? { let lowerCasedFontName = fontName.lowercased() let lowerCasedSystemFontName = type(of: self).systemFontName.lowercased() let lowerCasedBoldSystemFontName = type(of: self).boldSystemFontName.lowercased() let lowerCasedItalicSystemFontName = type(of: self).italicSystemFontName.lowercased() let points = CGFloat(pointSize) switch lowerCasedFontName { case lowerCasedSystemFontName: return UIFont.systemFont(ofSize: points) case lowerCasedBoldSystemFontName: return UIFont.boldSystemFont(ofSize: points) case lowerCasedItalicSystemFontName: return UIFont.italicSystemFont(ofSize: points) default: return nil } } }
mit
bafe9d12b80f50bac56e438e3de933bf
42.133858
113
0.661647
5.63001
false
false
false
false
joshc89/DeclarativeLayout
DeclarativeLayout/Example Layouts/MaxWidthLayout.swift
1
2051
// // MaxWidthLayout.swift // DeclarativeLayout // // Created by Josh Campion on 16/07/2016. // Copyright © 2016 Josh Campion. All rights reserved. // import UIKit /// Simple `Layout` constraining the width of a child `Layout` to a maximum size. If the width of `child` would exceed that of `boundary` it is centered horizontally within `boundary`. public struct MaxWidthLayout: Layout { /// Maximum width `child` can take. public var maxWidth:CGFloat { didSet { if maxWidth != oldValue { widthConstraint.constant = maxWidth } } } /// Child layout whose width should be restricted by `maxWidth`. public let child: Layout /// Internal variable constraining the width of `child` that is updated with `maxWidth`. let widthConstraint:NSLayoutConstraint /// Default initailiser setting the properties with the given values. public init(child: Layout, maxWidth: CGFloat) { self.child = child self.maxWidth = maxWidth let edges = UILayoutGuide() boundary = edges elements = [edges, child] widthConstraint = child.boundary.widthAnchor.constraint(lessThanOrEqualToConstant: maxWidth) let edgeConstraints = child.boundary.constraintsAligningEdges(to: edges) let cX = child.boundary.centerXAnchor.constraint(equalTo: edges.centerXAnchor) let leading = child.boundary.leadingAnchor.constraint(greaterThanOrEqualTo: edges.leadingAnchor) self.constraints = [edgeConstraints[0], edgeConstraints[2], cX, leading, widthConstraint] } // MARK: Layout Conformance /// The boundary is a UILayoutGuide that `child`'s `boundary` is aligned to. public let boundary: AnchoredObject /// `boundary` and `child`. public let elements: [Layout] /// Constraints internally aligning the edges of `child` to `boundary` with a restricted width. public let constraints: [NSLayoutConstraint] }
mit
acccbade0cc429dd6ea21f479cf218ad
34.344828
184
0.667317
5.012225
false
false
false
false
jkolb/midnightbacon
MidnightBacon/Reddit/Request/PrivateMessages/ComposeRequest.swift
1
2628
// // ComposeRequest.swift // MidnightBacon // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // 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 Common import ModestProposal import FranticApparatus class ComposeRequest : APIRequest { let prototype: NSURLRequest let apiType: APIType = .JSON let captcha: Captcha? let fromSubreddit: String? let subject: String? let text: String? let to: String? init(prototype: NSURLRequest, fromSubreddit: String?, to: String?, subject: String?, text: String?, captcha: Captcha?) { self.prototype = prototype self.fromSubreddit = fromSubreddit self.to = to self.subject = subject self.text = text self.captcha = captcha } typealias ResponseType = Bool func parse(response: URLResponse) throws -> Bool { return try redditJSONMapper(response) { (json) -> Bool in return true } } func build() -> NSMutableURLRequest { var parameters = [String:String](minimumCapacity: 7) parameters["api_type"] = apiType.rawValue parameters["captcha"] = captcha?.text parameters["from_sr"] = fromSubreddit parameters["iden"] = captcha?.iden parameters["subject"] = subject parameters["text"] = text parameters["to"] = to return prototype.POST(path: "/api/read_message", parameters: parameters) } var requiresModhash : Bool { return true } var scope : OAuthScope? { return .PrivateMessages } }
mit
a681b6e139c92456c433f2d83dd7d037
34.04
124
0.681887
4.659574
false
false
false
false
DanielFulton/ImageLibraryTests
Pods/Nuke/Sources/Internal.swift
1
4358
// The MIT License (MIT) // // Copyright (c) 2016 Alexander Grebenyuk (github.com/kean). #if os(OSX) import Cocoa /// Alias for NSImage public typealias Image = NSImage #else import UIKit /// Alias for UIImage public typealias Image = UIImage #endif // MARK: Error Handling func errorWithCode(code: ImageManagerErrorCode) -> NSError { func reason() -> String { switch code { case .Unknown: return "The image manager encountered an error that it cannot interpret." case .Cancelled: return "The image task was cancelled." case .DecodingFailed: return "The image manager failed to decode image data." case .ProcessingFailed: return "The image manager failed to process image data." } } return NSError(domain: ImageManagerErrorDomain, code: code.rawValue, userInfo: [NSLocalizedFailureReasonErrorKey: reason()]) } // MARK: GCD func dispathOnMainThread(closure: (Void) -> Void) { NSThread.isMainThread() ? closure() : dispatch_async(dispatch_get_main_queue(), closure) } extension dispatch_queue_t { func async(block: (Void -> Void)) { dispatch_async(self, block) } } // MARK: NSOperationQueue Extensions extension NSOperationQueue { convenience init(maxConcurrentOperationCount: Int) { self.init() self.maxConcurrentOperationCount = maxConcurrentOperationCount } func addBlock(block: (Void -> Void)) -> NSOperation { let operation = NSBlockOperation(block: block) self.addOperation(operation) return operation } } // MARK: TaskQueue public let SessionTaskDidResumeNotification = "com.github.kean.nuke.sessionTaskDidResume" public let SessionTaskDidCancelNotification = "com.github.kean.nuke.sessionTaskDidCancel" public let SessionTaskDidCompleteNotification = "com.github.kean.nuke.sessionTaskDidComplete" /// Limits number of concurrent tasks, prevents trashing of NSURLSession final class TaskQueue { var maxExecutingTaskCount = 8 var congestionControlEnabled = true private let queue: dispatch_queue_t private var pendingTasks = NSMutableOrderedSet() private var executingTasks = Set<NSURLSessionTask>() private var executing = false init(queue: dispatch_queue_t) { self.queue = queue } func resume(task: NSURLSessionTask) { if !pendingTasks.containsObject(task) && !executingTasks.contains(task) { pendingTasks.addObject(task) setNeedsExecute() } } func cancel(task: NSURLSessionTask) { if pendingTasks.containsObject(task) { pendingTasks.removeObject(task) } else if executingTasks.contains(task) { executingTasks.remove(task) task.cancel() NSNotificationCenter.defaultCenter().postNotificationName(SessionTaskDidCancelNotification, object: task) setNeedsExecute() } } func finish(task: NSURLSessionTask) { if pendingTasks.containsObject(task) { pendingTasks.removeObject(task) } else if executingTasks.contains(task) { executingTasks.remove(task) NSNotificationCenter.defaultCenter().postNotificationName(SessionTaskDidCompleteNotification, object: task) setNeedsExecute() } } func setNeedsExecute() { if !executing { executing = true if congestionControlEnabled { // Executing tasks too frequently might trash NSURLSession to the point it would crash or stop executing tasks let delay = min(30.0, 8.0 + Double(executingTasks.count)) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_MSEC))), queue) { self.execute() } } else { execute() } } } func execute() { executing = false if let task = pendingTasks.firstObject as? NSURLSessionTask where executingTasks.count < maxExecutingTaskCount { pendingTasks.removeObjectAtIndex(0) executingTasks.insert(task) task.resume() NSNotificationCenter.defaultCenter().postNotificationName(SessionTaskDidResumeNotification, object: task) setNeedsExecute() } } }
mit
f103d538f27846377aa0ed1a706c54d5
32.267176
128
0.661083
5.121034
false
false
false
false
yuxiuyu/TrendBet
TrendBetting_0531换首页/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift
4
2105
// // ChartLimitLine.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics /// The limit line is an additional feature for all Line, Bar and ScatterCharts. /// It allows the displaying of an additional line in the chart that marks a certain maximum / limit on the specified axis (x- or y-axis). open class ChartLimitLine: ComponentBase { @objc(ChartLimitLabelPosition) public enum LabelPosition: Int { case leftTop case leftBottom case rightTop case rightBottom } /// limit / maximum (the y-value or xIndex) @objc open var limit = Double(0.0) private var _lineWidth = CGFloat(2.0) @objc open var lineColor = NSUIColor(red: 237.0/255.0, green: 91.0/255.0, blue: 91.0/255.0, alpha: 1.0) @objc open var lineDashPhase = CGFloat(0.0) @objc open var lineDashLengths: [CGFloat]? @objc open var valueTextColor = NSUIColor.black @objc open var valueFont = NSUIFont.systemFont(ofSize: 13.0) @objc open var drawLabelEnabled = true @objc open var label = "" @objc open var labelPosition = LabelPosition.rightTop public override init() { super.init() } @objc public init(limit: Double) { super.init() self.limit = limit } @objc public init(limit: Double, label: String) { super.init() self.limit = limit self.label = label } /// set the line width of the chart (min = 0.2, max = 12); default 2 @objc open var lineWidth: CGFloat { get { return _lineWidth } set { if newValue < 0.2 { _lineWidth = 0.2 } else if newValue > 12.0 { _lineWidth = 12.0 } else { _lineWidth = newValue } } } }
apache-2.0
e84db77d9e07cae509ce8ea84a6a6f6a
23.764706
138
0.570546
4.269777
false
false
false
false
haskellswift/swift-package-manager
Sources/Basic/DictionaryExtensions.swift
1
639
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ extension Dictionary { /// Convenience initializer to create dictionary from tuples. public init<S: Sequence>(items: S) where S.Iterator.Element == (Key, Value) { var result = Dictionary() for (key, value) in items { result[key] = value } self = result } }
apache-2.0
93a0d6d7793e5bc9218d1c25b32cd522
30.95
81
0.685446
4.376712
false
false
false
false
jkolb/FranticApparatus
Sources/FranticApparatus/AllPromises.swift
1
3524
/* The MIT License (MIT) Copyright (c) 2018 Justin Kolb 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. */ public func all<Value, Promises : Collection>(context: ExecutionContext, promises: Promises) -> Promise<[Value]> where Promises.Iterator.Element == Promise<Value> { return Promise<[Value]> { (fulfill, reject) in let all = AllPromises<Int, Value>(count: numericCast(promises.count), fulfill: { (values) in let sortedValues = values.sorted(by: { $0.key < $1.key }).map({ $0.value }) fulfill(sortedValues) }, reject: reject) for (index, promise) in promises.enumerated() { promise.addCallback(context: context, fulfilled: { (value) in all.fulfill(value: value, for: index) }, rejected: { (reason) in all.reject(reason: reason, for: index) }) } } } public func all<Key, Value>(context: ExecutionContext, promises: [Key:Promise<Value>]) -> Promise<[Key:Value]> { return Promise<[Key:Value]> { (fulfill, reject) in let all = AllPromises<Key, Value>(count: numericCast(promises.count), fulfill: fulfill, reject: reject) for (key, promise) in promises { promise.addCallback(context: context, fulfilled: { (value) in all.fulfill(value: value, for: key) }, rejected: { (reason) in all.reject(reason: reason, for: key) }) } } } private final class AllPromises<Key : Hashable, Value> { private let lock: Lock private let count: Int private var values: [Key:Value] private var reasons: [Key:Error] private let fulfill: ([Key:Value]) -> Void private let reject: (Error) -> Void fileprivate init(count: Int, fulfill: @escaping ([Key:Value]) -> Void, reject: @escaping (Error) -> Void) { self.lock = Lock() self.count = count self.values = [Key:Value]() self.reasons = [Key:Error]() self.fulfill = fulfill self.reject = reject } fileprivate func fulfill(value: Value, for key: Key) { lock.lock() values[key] = value if values.count == count { fulfill(values) } lock.unlock() } fileprivate func reject(reason: Error, for key: Key) { lock.lock() reasons[key] = reason if reasons.count == 1 { reject(reason) } lock.unlock() } }
mit
f798f2df658fa5ccd06fdc3d213e1406
36.094737
164
0.631385
4.37764
false
false
false
false
OSzhou/MyTestDemo
PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-COpenSSL.git--4744624199947727386/Package.swift
1
616
// // Package.swift // COpenSSL // // Created by Kyle Jessup on 3/22/16. // Copyright (C) 2016 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PackageDescription let package = Package(name: "COpenSSL")
apache-2.0
bef016be9a482ea8ed08b7db42b79d1b
27
80
0.522727
4.70229
false
false
false
false
CoderXiaoming/Ronaldo
SaleManager/SaleManager/Customer/Controller/SAMCustomerVistManagerController.swift
1
13239
// // SAMCustomerVistManagerController.swift // SaleManager // // Created by apple on 17/2/9. // Copyright © 2017年 YZH. All rights reserved. // import UIKit import MJRefresh ///回访Cell重用标识符 private let SAMCustomerVistSearchCellReuseIdentifier = "SAMCustomerVistSearchCellReuseIdentifier" class SAMCustomerVistManagerController: UIViewController { //MARK: - 对外提供的类方法 class func instance(customerModel: SAMCustomerModel) -> SAMCustomerVistManagerController { let vc = SAMCustomerVistManagerController() vc.customerModel = customerModel return vc } //MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() //初始化UI setupUI() //设置tableView setupTableView() } //MARK: - 初始化UI fileprivate func setupUI() { //设置标题 navigationItem.title = customerModel!.CGUnitName //设置搜索框 searchBar.showsCancelButton = false searchBar.placeholder = "回访内容/回访时间" searchBar.delegate = self } //MARK: - 初始化tableView fileprivate func setupTableView() { //设置代理数据源 tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension //注册cell tableView.register(UINib(nibName: "SAMCustomerVistSearchCell", bundle: nil), forCellReuseIdentifier: SAMCustomerVistSearchCellReuseIdentifier) //设置下拉 tableView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(SAMCustomerVistManagerController.loadNewInfo)) } //MARK: - viewDidAppear override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) //刷新界面数据 tableView.mj_header.beginRefreshing() } //MARK: - 加载新数据 func loadNewInfo() { //处理搜索框的状态 if searchBar.showsCancelButton { searchBarCancelButtonClicked(searchBar) } //创建请求参数 let parameters = ["CGUnitID": customerModel!.id] //发送请求 SAMNetWorker.sharedNetWorker().get("getOneCGUnitFollow.ashx", parameters: parameters, progress: nil, success: {[weak self] (Task, json) in //清空原先数据 self!.listModels.removeAllObjects() //获取模型数组 let Json = json as! [String: AnyObject] let dictArr = Json["body"] as? [[String: AnyObject]] let count = dictArr?.count ?? 0 if count == 0 { //没有模型数据 //提示用户 let _ = SAMHUD.showMessage("暂无数据", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true) }else { //有数据模型 let arr = SAMCustomerVistModel.mj_objectArray(withKeyValuesArray: dictArr)! self!.listModels.addObjects(from: arr as [AnyObject]) } //回到主线程 DispatchQueue.main.async(execute: { //结束上拉 self!.tableView.mj_header.endRefreshing() //刷新数据 self!.tableView.reloadData() }) }) {[weak self] (Task, Error) in //处理上拉 self!.tableView.mj_header.endRefreshing() //提示用户 let _ = SAMHUD.showMessage("请检查网络", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true) } } //MARK: - 属性 ///接收的客户模型数据 fileprivate var customerModel: SAMCustomerModel? ///源模型数组 fileprivate let listModels = NSMutableArray() ///符合搜索结果模型数组 fileprivate let searchResultModels = NSMutableArray() ///记录当前是否在搜索 fileprivate var isSearch: Bool = false //MARK: - XIB链接属性 @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! //MARK: - 其他方法 fileprivate init() { super.init(nibName: nil, bundle: nil) } fileprivate override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func loadView() { view = Bundle.main.loadNibNamed("SAMCustomerVistManagerController", owner: self, options: nil)![0] as! UIView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: - 搜索框代理UISearchBarDelegate extension SAMCustomerVistManagerController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { //清空搜索结果数组,并赋值 searchResultModels.removeAllObjects() searchResultModels.addObjects(from: listModels as [AnyObject]) //获取搜索字符串 let searchStr = NSString(string: searchText.lxm_stringByTrimmingWhitespace()!) if searchStr.length > 0 { //记录正在搜索 isSearch = true //获取搜索字符串数组 let searchItems = searchStr.components(separatedBy: " ") var andMatchPredicates = [NSPredicate]() for item in searchItems { let searchString = item as NSString //strContent搜索谓语 var lhs = NSExpression(forKeyPath: "strContent") let rhs = NSExpression(forConstantValue: searchString) let firstPredicate = NSComparisonPredicate(leftExpression: lhs, rightExpression: rhs, modifier: .direct, type: .contains, options: .caseInsensitive) //startDate搜索谓语 lhs = NSExpression(forKeyPath: "startDate") let secondPredicate = NSComparisonPredicate(leftExpression: lhs, rightExpression: rhs, modifier: .direct, type: .contains, options: .caseInsensitive) let orMatchPredicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: [firstPredicate, secondPredicate]) andMatchPredicates.append(orMatchPredicate) } let finalCompoundPredicate = NSCompoundPredicate.init(andPredicateWithSubpredicates: andMatchPredicates) //存储搜索结果 let arr = searchResultModels.filtered(using: finalCompoundPredicate) searchResultModels.removeAllObjects() searchResultModels.addObjects(from: arr) }else { //记录没有搜索 isSearch = false } //刷新tableView tableView.reloadData() } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { //执行准备动画 UIView.animate(withDuration: 0.3, animations: { self.navigationController!.setNavigationBarHidden(true, animated: true) }, completion: { (_) in UIView.animate(withDuration: 0.2, animations: { searchBar.transform = CGAffineTransform(translationX: 0, y: 20) self.tableView.transform = CGAffineTransform(translationX: 0, y: 20) searchBar.showsCancelButton = true }) }) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { //结束搜索框编辑状态 searchBar.text = "" searchBar.resignFirstResponder() //执行结束动画 UIView.animate(withDuration: 0.3, animations: { self.navigationController!.setNavigationBarHidden(false, animated: false) searchBar.transform = CGAffineTransform.identity self.tableView.transform = CGAffineTransform.identity searchBar.showsCancelButton = false }, completion: { (_) in //结束搜索状态 self.isSearch = false //刷新数据 self.tableView.reloadData() }) } //MARK: - 点击键盘搜索按钮调用 func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBarCancelButtonClicked(searchBar) } } //MARK: - tableView数据源方法 UITableViewDataSource extension SAMCustomerVistManagerController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //根据是否是搜索状态返回不同的数据 let sourceArr = isSearch ? searchResultModels : listModels return sourceArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //获取重用Cell let cell = tableView.dequeueReusableCell(withIdentifier: SAMCustomerVistSearchCellReuseIdentifier) as! SAMCustomerVistSearchCell //根据是否是搜索状态返回不同的数据 let sourceArr = isSearch ? searchResultModels : listModels cell.vistModel = sourceArr[indexPath.row] as? SAMCustomerVistModel return cell } } //MARK: - tableView代理 UITableViewDelegate extension SAMCustomerVistManagerController: UITableViewDelegate { func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { //取出cell let cell = tableView.cellForRow(at: indexPath) as! SAMCustomerVistSearchCell //取出对应模型 let model = cell.vistModel! /******************* 删除按钮 ********************/ let deleteAction = UITableViewRowAction(style: .destructive, title: "删除") { (action, indexPath) in /// alertVC let alertVC = UIAlertController(title: "确定删除?", message: model.strContent!, preferredStyle: .alert) /// cancelAction let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in }) /// deleteAction let deleteAction = UIAlertAction(title: "确定", style: .destructive, handler: { (action) in //设置加载hud let hud = SAMHUD.showAdded(to: KeyWindow!, animated: true) hud!.labelText = NSLocalizedString("", comment: "HUD loading title") //创建请求参数 let parameters = ["id": model.id!] //发送请求 SAMNetWorker.sharedNetWorker().get("CGUnitFollowDelete.ashx", parameters: parameters, progress: nil, success: {[weak self] (Task, json) in //获取删除结果 let Json = json as! [String: AnyObject] let dict = Json["head"] as! [String: String] let status = dict["status"] //回到主线程 DispatchQueue.main.async(execute: { //隐藏hud hud?.hide(true) if status == "success" { //删除成功 //提示用户 let _ = SAMHUD.showMessage("删除成功", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true) //刷新数据 self?.tableView.mj_header.beginRefreshing() }else { //删除失败 //提示用户 let _ = SAMHUD.showMessage("删除失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true) } }) }) { (Task, Error) in //隐藏hud hud?.hide(true) //提示用户 let _ = SAMHUD.showMessage("请检查网络", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true) } }) alertVC.addAction(cancelAction) alertVC.addAction(deleteAction) self.present(alertVC, animated: true, completion: { }) } //操作数组 return[deleteAction] } }
apache-2.0
27fb588946be787fe36a05dc51bed318
34.405714
155
0.563832
5.75569
false
false
false
false
shu223/watchOS-2-Sampler
watchOS2Sampler WatchKit Extension/AnimatedPropertiesInterfaceController.swift
1
2201
// // AnimatedPropertiesInterfaceController.swift // watchOS2Sampler // // Created by Shuichi Tsutsumi on 2015/06/13. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // import WatchKit import Foundation class AnimatedPropertiesInterfaceController: WKInterfaceController { @IBOutlet weak var image: WKInterfaceImage! override func awake(withContext context: Any?) { super.awake(withContext: context) } override func willActivate() { super.willActivate() } override func didDeactivate() { super.didDeactivate() } // ========================================================================= // MARK: - Actions @IBAction func scaleBtnTapped() { animate(withDuration: 0.5) { () -> Void in self.image.setWidth(100) self.image.setHeight(160) } DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.animate(withDuration: 0.5, animations: { () -> Void in self.image.setWidth(50) self.image.setHeight(80) }) } } @IBAction func fadeBtnTapped() { animate(withDuration: 0.5) { () -> Void in self.image.setAlpha(0.0) } DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.animate(withDuration: 0.5, animations: { () -> Void in self.image.setAlpha(1.0) }) } } @IBAction func moveBtnTapped() { animate(withDuration: 0.5) { () -> Void in self.image.setHorizontalAlignment(WKInterfaceObjectHorizontalAlignment.right) } DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { self.animate(withDuration: 0.2) { () -> Void in self.image.setHorizontalAlignment(WKInterfaceObjectHorizontalAlignment.left) } } DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { self.animate(withDuration: 0.5) { () -> Void in self.image.setHorizontalAlignment(WKInterfaceObjectHorizontalAlignment.center) } } } }
mit
f1f6514a34b1942b984157c019737a6f
26.160494
94
0.555
4.793028
false
false
false
false
GuiBayma/PasswordVault
PasswordVault/Scenes/Groups/GroupsTableViewController.swift
1
2864
// // GroupsTableViewController.swift // PasswordVault // // Created by Guilherme Bayma on 7/26/17. // Copyright © 2017 Bayma. All rights reserved. // import UIKit enum GroupsNavigation { case newGroup case groupDetail } class GroupsTableViewController: UIViewController, UITableViewDelegate, NewDataDelegate { // MARK: - Variables fileprivate let tableView = GenericTableView() fileprivate let dataSource = GroupsTableViewDataSource() // MARK: - View initialization override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { self.view = tableView } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Senhas" self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.addGroup(_:))) tableView.register(cellType: GroupTableViewCell.self) tableView.delegate = self tableView.dataSource = dataSource dataSource.tableView = tableView dataSource.setData(GroupManager.sharedInstance.getAllGroups()) } // MARK: - Table view delegte func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let selectedGroup = dataSource.getData(at: indexPath.item) navigate(destination: .groupDetail, group: selectedGroup) } // MARK: - New group delegate func addNewDataAndDismiss(_ viewController: UIViewController, data: NSObject) { if let group = data as? Group { self.dataSource.addData(group) } viewController.dismiss(animated: true) {} } // MARK: - Bar button items func addGroup(_ sender: UIBarButtonItem) { navigate(destination: .newGroup, group: nil) } // MARK: - Navigation func navigate(destination: GroupsNavigation, group: Group?) { switch destination { case .newGroup: let nextView = AddGroupViewController() nextView.delegate = self let navController = UINavigationController(rootViewController: nextView) self.present(navController, animated: true) {} break case .groupDetail: let nextView = GroupDetailTableViewController() nextView.group = group self.navigationController?.pushViewController(nextView, animated: true) } } }
mit
fdbf9874b2d0e214d7320854cb4a446b
29.136842
102
0.637793
5.351402
false
false
false
false
honishi/Hakumai
Hakumai/Controllers/MainWindowController/TableCellView/ColoredView.swift
1
1068
// // ColoredView.swift // Hakumai // // Created by Hiroyuki Onishi on 11/25/14. // Copyright (c) 2014 Hiroyuki Onishi. All rights reserved. // import Foundation import AppKit import QuartzCore final class ColoredView: NSView, CALayerDelegate { var fillColor: NSColor = NSColor.gray { didSet { layer?.setNeedsDisplay() } } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder: NSCoder) { super.init(coder: coder) } } extension ColoredView { override func awakeFromNib() { // calyer implementation based on http://rway.tumblr.com/post/4525503228 let layer = CALayer() layer.delegate = self layer.bounds = bounds layer.needsDisplayOnBoundsChange = true layer.setNeedsDisplay() self.layer = layer wantsLayer = true } } extension ColoredView { override func draw(_ dirtyRect: NSRect) { // http://stackoverflow.com/a/2962882 fillColor.setFill() dirtyRect.fill() super.draw(dirtyRect) } }
mit
565f85c178e56ec8a320ffe43bf8e7ea
22.217391
81
0.642322
4.107692
false
false
false
false
nanthi1990/SwiftCharts
SwiftCharts/Layers/ChartStackedBarsLayer.swift
4
6445
// // ChartStackedBarsLayer.swift // Examples // // Created by ischuetz on 15/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public typealias ChartStackedBarItemModel = (quantity: Double, bgColor: UIColor) public class ChartStackedBarModel: ChartBarModel { let items: [ChartStackedBarItemModel] public init(constant: ChartAxisValue, start: ChartAxisValue, items: [ChartStackedBarItemModel]) { self.items = items let axisValue2Scalar = items.reduce(start.scalar) {sum, item in sum + item.quantity } let axisValue2 = start.copy(axisValue2Scalar) super.init(constant: constant, axisValue1: start, axisValue2: axisValue2) } lazy var totalQuantity: Double = { return self.items.reduce(0) {total, item in total + item.quantity } }() } class ChartStackedBarsViewGenerator<T: ChartStackedBarModel>: ChartBarsViewGenerator<T> { private typealias FrameBuilder = (barModel: ChartStackedBarModel, item: ChartStackedBarItemModel, currentTotalQuantity: Double) -> (frame: ChartPointViewBarStackedFrame, length: CGFloat) override init(horizontal: Bool, xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, chartInnerFrame: CGRect, barWidth barWidthMaybe: CGFloat?, barSpacing barSpacingMaybe: CGFloat?) { super.init(horizontal: horizontal, xAxis: xAxis, yAxis: yAxis, chartInnerFrame: chartInnerFrame, barWidth: barWidthMaybe, barSpacing: barSpacingMaybe) } override func generateView(barModel: T, constantScreenLoc constantScreenLocMaybe: CGFloat? = nil, bgColor: UIColor? = nil, animDuration: Float) -> ChartPointViewBar { let constantScreenLoc = constantScreenLocMaybe ?? self.constantScreenLoc(barModel) let frameBuilder: FrameBuilder = { switch self.direction { case .LeftToRight: return {barModel, item, currentTotalQuantity in let p0 = self.xAxis.screenLocForScalar(currentTotalQuantity) let p1 = self.xAxis.screenLocForScalar(currentTotalQuantity + item.quantity) let length = p1 - p0 let barLeftScreenLoc = self.xAxis.screenLocForScalar(length > 0 ? barModel.axisValue1.scalar : barModel.axisValue2.scalar) return (frame: ChartPointViewBarStackedFrame(rect: CGRectMake( p0 - barLeftScreenLoc, 0, length, self.barWidth), color: item.bgColor), length: length) } case .BottomToTop: return {barModel, item, currentTotalQuantity in let p0 = self.yAxis.screenLocForScalar(currentTotalQuantity) let p1 = self.yAxis.screenLocForScalar(currentTotalQuantity + item.quantity) let length = p1 - p0 let barTopScreenLoc = self.yAxis.screenLocForScalar(length > 0 ? barModel.axisValue1.scalar : barModel.axisValue2.scalar) return (frame: ChartPointViewBarStackedFrame(rect: CGRectMake( 0, p0 - barTopScreenLoc, self.barWidth, length), color: item.bgColor), length: length) } } }() let stackFrames = barModel.items.reduce((currentTotalQuantity: barModel.axisValue1.scalar, currentTotalLength: CGFloat(0), frames: Array<ChartPointViewBarStackedFrame>())) {tuple, item in let frameWithLength = frameBuilder(barModel: barModel, item: item, currentTotalQuantity: tuple.currentTotalQuantity) return (currentTotalQuantity: tuple.currentTotalQuantity + item.quantity, currentTotalLength: tuple.currentTotalLength + frameWithLength.length, frames: tuple.frames + [frameWithLength.frame]) } let viewPoints = self.viewPoints(barModel, constantScreenLoc: constantScreenLoc) return ChartPointViewBarStacked(p1: viewPoints.p1, p2: viewPoints.p2, width: self.barWidth, stackFrames: stackFrames.frames, animDuration: animDuration) } } public class ChartStackedBarsLayer: ChartCoordsSpaceLayer { private let barModels: [ChartStackedBarModel] private let horizontal: Bool private let barWidth: CGFloat? private let barSpacing: CGFloat? private let animDuration: Float public convenience init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, barModels: [ChartStackedBarModel], horizontal: Bool = false, barWidth: CGFloat, animDuration: Float) { self.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, barModels: barModels, horizontal: horizontal, barWidth: barWidth, barSpacing: nil, animDuration: animDuration) } public convenience init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, barModels: [ChartStackedBarModel], horizontal: Bool = false, barSpacing: CGFloat, animDuration: Float) { self.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, barModels: barModels, horizontal: horizontal, barWidth: nil, barSpacing: barSpacing, animDuration: animDuration) } private init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, barModels: [ChartStackedBarModel], horizontal: Bool = false, barWidth: CGFloat? = nil, barSpacing: CGFloat?, animDuration: Float) { self.barModels = barModels self.horizontal = horizontal self.barWidth = barWidth self.barSpacing = barSpacing self.animDuration = animDuration super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame) } public override func chartInitialized(#chart: Chart) { let barsGenerator = ChartStackedBarsViewGenerator(horizontal: self.horizontal, xAxis: self.xAxis, yAxis: self.yAxis, chartInnerFrame: self.innerFrame, barWidth: self.barWidth, barSpacing: self.barSpacing) for barModel in self.barModels { chart.addSubview(barsGenerator.generateView(barModel, animDuration: self.animDuration)) } } }
apache-2.0
5acedf86c49015257efb65d22533d94d
48.576923
214
0.650892
5.513259
false
false
false
false
ohwutup/ReactiveCocoa
ReactiveCocoaTests/SwizzlingSpec.swift
1
1331
@testable import ReactiveCocoa import Quick import Nimble class SwizzledObject: NSObject {} class SwizzlingSpec: QuickSpec { override func spec() { describe("runtime subclassing") { it("should swizzle the instance while still reporting the perceived class in `-class` and `+class`") { let object = SwizzledObject() expect(type(of: object)).to(beIdenticalTo(SwizzledObject.self)) let subclass: AnyClass = swizzleClass(object) expect(type(of: object)).to(beIdenticalTo(subclass)) let objcClass = (object as AnyObject).objcClass expect(objcClass).to(beIdenticalTo(SwizzledObject.self)) expect((objcClass as AnyObject).objcClass).to(beIdenticalTo(SwizzledObject.self)) expect(String(cString: class_getName(subclass))).to(contain("_RACSwift")) } it("should reuse the runtime subclass across instances") { let object = SwizzledObject() let subclass: AnyClass = swizzleClass(object) let object2 = SwizzledObject() let subclass2: AnyClass = swizzleClass(object2) expect(subclass).to(beIdenticalTo(subclass2)) } it("should return the known runtime subclass") { let object = SwizzledObject() let subclass: AnyClass = swizzleClass(object) let subclass2: AnyClass = swizzleClass(object) expect(subclass).to(beIdenticalTo(subclass2)) } } } }
mit
2e5efd88b131f02625a7e8fbb0c75266
29.953488
105
0.725019
4.095385
false
false
false
false
moltin/ios-sdk
Sources/SDK/Models/Brand.swift
1
2371
// // Brand.swift // moltin // // Created by Craig Tweedy on 22/02/2018. // import Foundation /// Represents a `Brand` in Moltin open class Brand: Codable, HasRelationship { /// The id of this brand public let id: String /// The type of this object public let type: String /// The name of this brand public let name: String /// The slug of this brand public let slug: String /// The description of this brand public let description: String /// draft / live public let status: String /// The relationships this brand has public let relationships: Relationships? /// The brands this brand is associated with public var brands: [Brand]? /// The products this brand is associated with public var products: [Product]? /// The children of this brand public var children: [Brand]? required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let includes: IncludesContainer = decoder.userInfo[.includes] as? IncludesContainer ?? [:] self.id = try container.decode(String.self, forKey: .id) self.type = try container.decode(String.self, forKey: .type) self.name = try container.decode(String.self, forKey: .name) self.slug = try container.decode(String.self, forKey: .slug) self.description = try container.decode(String.self, forKey: .description) self.status = try container.decode(String.self, forKey: .status) self.relationships = try container.decodeIfPresent(Relationships.self, forKey: .relationships) self.children = try container.decodeIfPresent([Brand].self, forKey: .children) try self.decodeRelationships(fromRelationships: self.relationships, withIncludes: includes) } } extension Brand { func decodeRelationships( fromRelationships relationships: Relationships?, withIncludes includes: IncludesContainer) throws { self.brands = try self.decodeMany(fromRelationships: self.relationships?[keyPath: \Relationships.brands], withIncludes: includes["brands"]) self.products = try self.decodeMany(fromRelationships: self.relationships?[keyPath: \Relationships.products], withIncludes: includes["products"]) } }
mit
160698c03f18c9a45062f7192b101886
36.634921
117
0.674821
4.704365
false
false
false
false
mlgoogle/viossvc
viossvc/Scenes/User/PriceSelectionCell.swift
1
5119
// // PriceSelectionCell.swift // viossvc // // Created by 陈奕涛 on 17/3/3. // Copyright © 2017年 com.yundian. All rights reserved. // import Foundation protocol PriceSelectionCellDelegate: NSObjectProtocol { func selectedPrice(price: Int) } class PriceSelectionCell: UITableViewCell { weak var delegate:PriceSelectionCellDelegate? var priceInfos:[PriceModel]? lazy var leftPrice:UIButton = { let button = UIButton() button.setBackgroundImage(UIImage.init(named: "price_unselecte"), forState: .Normal) button.setBackgroundImage(UIImage.init(named: "price_selecte"), forState: .Selected) button.setBackgroundImage(UIImage.init(named: "price_selecte"), forState: .Highlighted) button.setTitle("8", forState: .Normal) button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 25, 0) button.titleLabel?.font = UIFont.systemFontOfSize(20) button.setTitleColor(UIColor.init(hexString: "#cccccc"), forState: .Normal) button.setTitleColor(UIColor.init(hexString: "#fffefe"), forState: .Selected) button.setTitleColor(UIColor.init(hexString: "#fffefe"), forState: .Highlighted) button.addTarget(self, action: #selector(selecteAction), forControlEvents: .TouchUpInside) return button }() lazy var middlePrice:UIButton = { let button = UIButton() button.setBackgroundImage(UIImage.init(named: "price_unselecte"), forState: .Normal) button.setBackgroundImage(UIImage.init(named: "price_selecte"), forState: .Selected) button.setBackgroundImage(UIImage.init(named: "price_selecte"), forState: .Highlighted) button.setTitle("88", forState: .Normal) button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 25, 0) button.titleLabel?.font = UIFont.systemFontOfSize(20) button.setTitleColor(UIColor.init(hexString: "#cccccc"), forState: .Normal) button.setTitleColor(UIColor.init(hexString: "#fffefe"), forState: .Selected) button.setTitleColor(UIColor.init(hexString: "#fffefe"), forState: .Highlighted) button.addTarget(self, action: #selector(selecteAction), forControlEvents: .TouchUpInside) return button }() lazy var rightPrice:UIButton = { let button = UIButton() button.setBackgroundImage(UIImage.init(named: "price_unselecte"), forState: .Normal) button.setBackgroundImage(UIImage.init(named: "price_selecte"), forState: .Selected) button.setBackgroundImage(UIImage.init(named: "price_selecte"), forState: .Highlighted) button.setTitle("888", forState: .Normal) button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 25, 0) button.titleLabel?.font = UIFont.systemFontOfSize(20) button.setTitleColor(UIColor.init(hexString: "#cccccc"), forState: .Normal) button.setTitleColor(UIColor.init(hexString: "#fffefe"), forState: .Selected) button.setTitleColor(UIColor.init(hexString: "#fffefe"), forState: .Highlighted) button.addTarget(self, action: #selector(selecteAction), forControlEvents: .TouchUpInside) return button }() var items = [UIButton]() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .None contentView.addSubview(leftPrice) leftPrice.snp_makeConstraints(closure: { (make) in make.left.equalTo(25) make.top.equalTo(7.5) make.width.equalTo(75) make.height.equalTo(98) make.bottom.equalTo(-7.5) }) contentView.addSubview(middlePrice) middlePrice.snp_makeConstraints(closure: { (make) in make.centerX.equalTo(contentView) make.centerY.equalTo(leftPrice) make.width.equalTo(75) make.height.equalTo(98) }) contentView.addSubview(rightPrice) rightPrice.snp_makeConstraints(closure: { (make) in make.right.equalTo(-25) make.centerY.equalTo(leftPrice) make.width.equalTo(75) make.height.equalTo(98) }) items.append(leftPrice) items.append(middlePrice) items.append(rightPrice) } func update(priceInfos: [PriceModel], selectedPrice: Int) { self.priceInfos = priceInfos for i in 0..<3 { items[i].hidden = i >= priceInfos.count guard i < priceInfos.count else { continue } items[i].setTitle("\(priceInfos[i].price)", forState: .Normal) items[i].selected = selectedPrice == priceInfos[i].price } } func selecteAction(sender: UIButton) { for i in 0..<items.count { if items[i] == sender { delegate?.selectedPrice(priceInfos![i].price) break } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
23ae8025a39c0dc95d201a85b7ff8b57
38.612403
98
0.641096
4.502203
false
false
false
false
ArchimboldiMao/remotex-iOS
remotex-iOS/Model/RoleModel.swift
2
906
// // RoleModel.swift // remotex-iOS // // Created by archimboldi on 10/05/2017. // Copyright © 2017 me.archimboldi. All rights reserved. // import UIKit struct RoleModel { let roleID: Int let roleName: String init?(dictionary: JSONDictionary) { guard let roleID = dictionary["id"] as? Int, let roleName = dictionary["name"] as? String else { print("error parsing JSON within RoleModel Init") return nil } self.roleID = roleID self.roleName = roleName } } extension RoleModel { func attrStringForRoleName(withSize size: CGFloat) -> NSAttributedString { let attr = [ NSForegroundColorAttributeName: Constants.CellLayout.TagForegroundColor, NSFontAttributeName: UIFont.systemFont(ofSize: size) ] return NSAttributedString.init(string: roleName, attributes: attr) } }
apache-2.0
001df251f1d624e82b12fe259cd29562
26.424242
104
0.649724
4.309524
false
false
false
false
kickstarter/ios-oss
Library/ProjectActivityItemProvider.swift
1
1220
import KsApi import UIKit public final class ProjectActivityItemProvider: UIActivityItemProvider { private var project: Project? public convenience init(project: Project) { self.init(placeholderItem: project.name) self.project = project } public override func activityViewController( _ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType? ) -> Any? { if let project = self.project { if activityType == .mail || activityType == .message { return self.formattedString(for: project) } else if activityType == .postToTwitter { return Strings.project_checkout_share_twitter_via_kickstarter( project_or_update_title: self.formattedString(for: project) ) } else if activityType == .copyToPasteboard || activityType == .postToFacebook { return project.urls.web.project } else { return self.formattedString(for: project) } } return self.activityViewControllerPlaceholderItem(activityViewController) } private func formattedString(for project: Project) -> String { return [project.name, project.urls.web.project].joined(separator: "\n") } }
apache-2.0
59f33fdf7073d0a67c5fed77f9d5a09b
32.888889
86
0.710656
4.899598
false
false
false
false
Ramesh-P/virtual-tourist
Virtual Tourist/TravelLocationsMapViewController+Region.swift
1
3558
// // TravelLocationsMapViewController+Region.swift // Virtual Tourist // // Created by Ramesh Parthasarathy on 3/7/17. // Copyright © 2017 Ramesh Parthasarathy. All rights reserved. // import Foundation import UIKit import MapKit import CoreData // MARK: TravelLocationsMapViewController+Extension+Region extension TravelLocationsMapViewController { // MARK: Map Region func fetchRegion() { // Fetch preset location and zoom level from data store let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Preset") fetchRequest.fetchLimit = 1 do { let results = try appDelegate.stack.context.fetch(fetchRequest) if let results = results as? [Preset] { if (results.count > 0) { preset = results[0] } } } catch { fatalError("Could not fetch map presets: \(error)") } loadRegion() } func loadRegion() { if (preset != nil) { // Load preset map location and zoom level let latitude = (preset?.latitude)! let longitude = (preset?.longitude)! let latitudeDelta = (preset?.latitudeDelta)! let longitudeDelta = (preset?.longitudeDelta)! // Set map region by previous location and zoom level choice let location = CLLocationCoordinate2DMake(latitude, longitude) let span = MKCoordinateSpanMake(latitudeDelta, longitudeDelta) let region = MKCoordinateRegionMake(location, span) map.setRegion(region, animated: true) } } func setSpan() { // Set span to user selected zoom level let latitudeDelta = map.region.span.latitudeDelta let longitudeDelta = map.region.span.longitudeDelta setRegion(latitudeDelta, longitudeDelta) } func resetSpan() { // Reset span to default zoom level let latitudeDelta = appDelegate.latitudeDelta let longitudeDelta = appDelegate.longitudeDelta setRegion(latitudeDelta, longitudeDelta) } func setRegion(_ latitudeDelta: CLLocationDegrees, _ longitudeDelta: CLLocationDegrees) { // Set map to selected location let latitude = map.region.center.latitude let longitude = map.region.center.longitude // Set map region per location and zoom level choice let location = CLLocationCoordinate2DMake(latitude, longitude) let span = MKCoordinateSpanMake(latitudeDelta, longitudeDelta) let region = MKCoordinateRegionMake(location, span) map.setRegion(region, animated: true) saveRegion(region) } func saveRegion(_ region: MKCoordinateRegion) { // Save map region to user selected location and zoom level if (preset == nil) { preset = Preset(latitude: region.center.latitude, latitudeDelta: region.span.latitudeDelta, longitude: region.center.longitude, longitudeDelta: region.span.longitudeDelta, context: appDelegate.stack.context) } else { preset?.latitude = region.center.latitude preset?.latitudeDelta = region.span.latitudeDelta preset?.longitude = region.center.longitude preset?.longitudeDelta = region.span.longitudeDelta } appDelegate.stack.saveContext() } }
mit
b8a353124c4e679d3e8b12412a4d1e80
32.87619
219
0.619623
5.601575
false
false
false
false
drinkapoint/DrinkPoint-iOS
DrinkPoint/Pods/FacebookShare/Sources/Share/Content/Video/VideoShareContent.swift
1
3619
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright notice shall be // included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation import FBSDKShareKit /** A model for video content to be shared. */ public struct VideoShareContent: ContentProtocol { public typealias Result = PostSharingResult /// Video to be shared. public var video: Video /// The photo that represents the video. public var previewPhoto: Photo? /** Create a `VideoShareContent` with a list of of photos to share. - parameter video: The video to share. - parameter previewPhoto: The photo that represents the video. */ public init(video: Video, previewPhoto: Photo? = nil) { self.video = video self.previewPhoto = previewPhoto } //-------------------------------------- // MARK - ContentProtocol //-------------------------------------- /** URL for the content being shared. This URL will be checked for all link meta tags for linking in platform specific ways. See documentation for [App Links](https://developers.facebook.com/docs/applinks/) */ public var url: NSURL? /// Hashtag for the content being shared. public var hashtag: Hashtag? /** List of IDs for taggable people to tag with this content. See documentation for [Taggable Friends](https://developers.facebook.com/docs/graph-api/reference/user/taggable_friends) */ public var taggedPeopleIds: [String]? /// The ID for a place to tag with this content. public var placeId: String? /// A value to be added to the referrer URL when a person follows a link from this shared content on feed. public var referer: String? } extension VideoShareContent: Equatable { } extension VideoShareContent: SDKBridgedContent { var sdkSharingContentRepresentation: FBSDKSharingContent { let sdkVideoContent = FBSDKShareVideoContent() sdkVideoContent.video = video.sdkVideoRepresentation sdkVideoContent.previewPhoto = previewPhoto?.sdkPhotoRepresentation sdkVideoContent.contentURL = url sdkVideoContent.hashtag = hashtag?.sdkHashtagRepresentation sdkVideoContent.peopleIDs = taggedPeopleIds sdkVideoContent.placeID = placeId sdkVideoContent.ref = referer return sdkVideoContent } } /** Compare two `VideoShareContent`s for equality. - parameter lhs: The first `VideoShareContent` to compare. - parameter rhs: The second `VideoShareContent` to compare. - returns: Whether or not the content are equal. */ public func == (lhs: VideoShareContent, rhs: VideoShareContent) -> Bool { return lhs.sdkSharingContentRepresentation.isEqual(rhs.sdkSharingContentRepresentation) }
mit
b416553cec8f80ded09aa72e478feefd
35.19
123
0.734181
4.831776
false
false
false
false
AntonTheDev/CoreFlightAnimation
CoreFlightAnimation/CoreFlightAnimationDemo/Source/FASequence/FASequenceGroup.swift
1
1002
// // FASequenceAnimator.swift // // // Created by Anton on 8/26/16. // // import Foundation import UIKit public func ==(lhs:FASequenceGroup, rhs:FASequenceGroup) -> Bool { return lhs.animationKey == rhs.animationKey } public class FASequenceGroup : FASequence { public var animationKey : String? public var animatingLayer : CALayer? public var isTimeRelative = true public var progessValue : CGFloat = 0.0 public var triggerOnRemoval : Bool = false // [ Parent : Child ] public var sequenceAnimations = [(parent : FASequenceAnimation , child : FASequenceAnimation)]() override public func startSequence() { guard isAnimating == false else { return } queuedTriggers = sequenceAnimations super.startSequence() } public func appendSequenceAnimation(child : FASequenceAnimation, relativeTo parent : FASequenceAnimation) { self.sequenceAnimations.append((parent : parent , child : child)) } }
mit
9ef1da674a2293af001ef58469880947
25.394737
111
0.680639
4.660465
false
false
false
false
blinker13/UI
Sources/Canvas/Painting/Gradient.swift
1
1578
import Geometry public struct Gradient : Hashable { public enum Shading : Hashable { case linear(Point, Point) case angular(Point, Angle, Angle) case radial(Point, Scalar, Scalar) } public struct Stop : Hashable { public let color: Color public let location: Scalar } public let shading: Shading public let stops: [Stop] @usableFromInline internal init(shading: Shading, stops: [Stop]) { self.shading = shading self.stops = stops } } // MARK: - extension Gradient { @inlinable init(linear stops: [Stop], from origin: Point, to destination: Point) { self.init(shading: .linear(origin, destination), stops: stops) } @inlinable init(linear colors: [Color], from origin: Point, to destination: Point) { self.init(shading: .linear(origin, destination), stops: []) // TODO: map colors } @inlinable init(angular stops: [Stop], origin: Point = .center, start: Angle = .zero, end: Angle = .full) { self.init(shading: .angular(origin, start, end), stops: stops) } @inlinable init(angular colors: [Color], origin: Point = .center, start: Angle = .zero, end: Angle = .full) { self.init(shading: .angular(origin, start, end), stops: []) // TODO: map colors } @inlinable init(radial stops: [Stop], origin: Point = .center, start: Scalar, end: Scalar) { self.init(shading: .radial(origin, start, end), stops: stops) } @inlinable init(radial colors: [Color], origin: Point = .center, start: Scalar, end: Scalar) { self.init(shading: .radial(origin, start, end), stops: []) // TODO: map colors } } // MARK: - extension Gradient { }
mit
b5b837197cd32739fa7d2e2b35b3ff07
25.745763
110
0.681876
3.273859
false
false
false
false
iAladdin/SwiftyFORM
Source/Form/OptionViewController.swift
1
1164
// // OptionViewController.swift // SwiftyFORM // // Created by Simon Strandgaard on 05/11/14. // Copyright (c) 2014 Simon Strandgaard. All rights reserved. // import UIKit class OptionViewController: FormViewController, SelectOptionDelegate { let dismissCommand: CommandProtocol let optionField: OptionPickerFormItem init(dismissCommand: CommandProtocol, optionField: OptionPickerFormItem) { self.dismissCommand = dismissCommand self.optionField = optionField super.init() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func populate(builder: FormBuilder) { DLog("preselect option \(optionField.selected?.title)") builder.navigationTitle = optionField.title for optionRow: OptionRowModel in optionField.options { let option = OptionRowFormItem() option.title(optionRow.title) option.context = optionRow option.selected = (optionRow === optionField.selected) builder.append(option) } } func form_willSelectOption(option: OptionRowFormItem) { DLog("select option \(option.title)") dismissCommand.execute(self, returnObject: option.context) } }
mit
cf1c3229101142481cfff9f73b85d455
26.714286
75
0.756873
3.945763
false
false
false
false
rnine/AMCoreAudio
Source/Public/AudioDevice+Aggregate.swift
1
3804
// AudioDevice+Aggregate.swift // Created by Ryan Francesconi on 2/24/21. // Copyright © 2021 9Labs. All rights reserved. import AudioToolbox.AudioServices import os.log public extension AudioDevice { /// - Returns: `true` if this device is an aggregate one, `false` otherwise. func isAggregateDevice() -> Bool { guard let aggregateDevices = ownedAggregateDevices() else { return false } return !aggregateDevices.isEmpty } /// All the subdevices of this aggregate device /// /// - Returns: An array of `AudioDevice` objects. func ownedAggregateDevices() -> [AudioDevice]? { guard let ownedObjectIDs = ownedObjectIDs() else { return nil } let ownedDevices = ownedObjectIDs.compactMap { (id) -> AudioDevice? in AudioDevice.lookup(by: id) } // only aggregates have non nil owned UIDs. I think? return ownedDevices.filter { $0.uid != nil } } /// All the subdevices of this aggregate device that support input /// /// - Returns: An array of `AudioDevice` objects. func ownedAggregateInputDevices() -> [AudioDevice]? { ownedAggregateDevices()?.filter { guard let channels = $0.layoutChannels(direction: .recording) else { return false } return channels > 0 } } /// All the subdevices of this aggregate device that support output /// /// - Returns: An array of `AudioDevice` objects. func ownedAggregateOutputDevices() -> [AudioDevice]? { ownedAggregateDevices()?.filter { guard let channels = $0.layoutChannels(direction: .playback) else { return false } return channels > 0 } } // MARK: - Create and Destroy Aggregate Devices /// This routine creates a new Aggregate AudioDevice /// /// - Parameter masterDeviceUID: An audio device unique identifier. This will also be the clock source. /// - Parameter secondDeviceUID: An audio device unique identifier /// /// - Returns *(optional)* An aggregate `AudioDevice` if one can be created. static func createAggregateDevice(masterDeviceUID: String, secondDeviceUID: String?, named name: String, uid: String) -> AudioDevice? { var deviceList: [[String: Any]] = [ [kAudioSubDeviceUIDKey: masterDeviceUID] ] // make sure same device isn't added twice if let secondDeviceUID = secondDeviceUID, secondDeviceUID != masterDeviceUID { deviceList.append([kAudioSubDeviceUIDKey: secondDeviceUID]) } let desc: [String: Any] = [ kAudioAggregateDeviceNameKey: name, kAudioAggregateDeviceUIDKey: uid, kAudioAggregateDeviceSubDeviceListKey: deviceList, kAudioAggregateDeviceMasterSubDeviceKey: masterDeviceUID ] var deviceID: AudioDeviceID = 0 let error = AudioHardwareCreateAggregateDevice(desc as CFDictionary, &deviceID) guard error == noErr else { os_log("Failed creating aggregate device with error: %d.", log: .default, type: .debug, error) return nil } return AudioDevice.lookup(by: deviceID) } /// Destroy the given AudioAggregateDevice. /// /// The actual destruction of the device is asynchronous and may take place after /// the call to this routine has returned. /// - Parameter id: The AudioObjectID of the AudioAggregateDevice to destroy. /// - Returns An OSStatus indicating success or failure. static func removeAggregateDevice(id deviceID: AudioObjectID) -> OSStatus { AudioHardwareDestroyAggregateDevice(deviceID) } }
mit
46827b36bfbfaabb22dbfa01bff45762
37.414141
107
0.635814
5.153117
false
false
false
false
chris-al-brown/alchemy-csa
Sources/Alphabet.swift
1
8508
// ----------------------------------------------------------------------------- // Copyright (c) 2016, Christopher A. Brown (chris-al-brown) // // 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. // // AlchemyCSA // Alphabet.swift // 06/29/2016 // ----------------------------------------------------------------------------- import Foundation /// ... public protocol Alphabet: Hashable { /// ... static var allValues: Set<Self> { get } /// ... init?(_ value: String) } /// ... public enum DNA: Alphabet { /// ... case adenine /// ... case cytosine /// ... case guanine /// ... case thymine /// ... public static let allValues: Set<DNA> = [ .adenine, .cytosine, .guanine, .thymine ] /// ... public init?(_ value: String) { switch value.lowercased() { case "a", "adenine": self = .adenine case "c", "cytosine": self = .cytosine case "g", "guanine": self = .guanine case "t", "thymine": self = .thymine default: return nil } } } /// ... extension DNA: CustomStringConvertible { /// ... public var description: String { switch self { case .adenine: return "A" case .cytosine: return "C" case .guanine: return "G" case .thymine: return "T" } } } /// ... public enum Gapped<Wrapped: Alphabet>: Alphabet { /// ... case gap /// ... case wrapped(Wrapped) /// ... public static var allValues: Set<Gapped<Wrapped>> { return Set(Wrapped.allValues.map { return .wrapped($0) } + [.gap]) } /// ... public init?(_ value: String) { switch value { case "-", ".": self = .gap default: if let w = Wrapped(value) { self = .wrapped(w) } else { return nil } } } } /// ... extension Gapped: CustomStringConvertible { /// ... public var description: String { switch self { case .gap: return "-" case .wrapped(let w): return String(w) } } } /// ... extension Gapped: Hashable { /// ... public var hashValue: Int { switch self { case .gap: return Wrapped.allValues.count case .wrapped(let w): return w.hashValue } } } /// ... extension Gapped: Equatable {} public func ==<T>(lhs: Gapped<T>, rhs: Gapped<T>) -> Bool { switch (lhs, rhs) { case (.gap, .gap): return true case (.wrapped(let l), .wrapped(let r)): return l == r default: return false } } /// ... public enum Protein: Alphabet { /// ... case alanine /// ... case arginine /// ... case asparagine /// ... case asparticAcid /// ... case cysteine /// ... case glutamicAcid /// ... case glutamine /// ... case glycine /// ... case histidine /// ... case isoleucine /// ... case leucine /// ... case lysine /// ... case methionine /// ... case phenylalanine /// ... case proline /// ... case serine /// ... case threonine /// ... case tryptophan /// ... case tyrosine /// ... case valine /// ... public static let allValues: Set<Protein> = [ .alanine, .arginine, .asparagine, .asparticAcid, .cysteine, .glutamicAcid, .glutamine, .glycine, .histidine, .isoleucine, .leucine, .lysine, .methionine, .phenylalanine, .proline, .serine, .threonine, .tryptophan, .tyrosine, .valine ] /// ... public init?(_ value: String) { switch value.lowercased() { case "a", "ala", "alanine": self = .alanine case "r", "arg", "arginine": self = .arginine case "n", "asn", "asparagine": self = .asparagine case "d", "asp", "aspartic acid": self = .asparticAcid case "c", "cys", "cysteine": self = .cysteine case "e", "glu", "glutamic acid": self = .glutamicAcid case "q", "gln", "glutamine": self = .glutamine case "g", "gly", "glycine": self = .glycine case "h", "his", "histidine": self = .histidine case "i", "ile", "isoleucine": self = .isoleucine case "l", "leu", "leucine": self = .leucine case "k", "lys", "lysine": self = .lysine case "m", "met", "methionine": self = .methionine case "f", "phe", "phenylalanine": self = .phenylalanine case "p", "pro", "proline": self = .proline case "s", "ser", "serine": self = .serine case "t", "thr", "threonine": self = .threonine case "w", "trp", "tryptophan": self = .tryptophan case "y", "tyr", "tyrosine": self = .tyrosine case "v", "val", "valine": self = .valine default: return nil } } } /// ... extension Protein: CustomStringConvertible { /// ... public var description: String { switch self { case .alanine: return "A" case arginine: return "R" case asparagine: return "N" case asparticAcid: return "D" case cysteine: return "C" case glutamicAcid: return "E" case glutamine: return "Q" case glycine: return "G" case histidine: return "H" case isoleucine: return "I" case leucine: return "L" case lysine: return "K" case methionine: return "M" case phenylalanine: return "F" case proline: return "P" case serine: return "S" case threonine: return "T" case tryptophan: return "W" case tyrosine: return "Y" case valine: return "V" } } } /// ... public enum RNA: Alphabet { /// ... case adenine /// ... case cytosine /// ... case guanine /// ... case uracil /// ... public static let allValues: Set<RNA> = [ .adenine, .cytosine, .guanine, .uracil ] /// ... public init?(_ value: String) { switch value.lowercased() { case "a", "adenine": self = .adenine case "c", "cytosine": self = .cytosine case "g", "guanine": self = .guanine case "u", "uracil": self = .uracil default: return nil } } } /// ... extension RNA: CustomStringConvertible { /// ... public var description: String { switch self { case .adenine: return "A" case .cytosine: return "C" case .guanine: return "G" case .uracil: return "U" } } }
mit
49711e21ceec8780ef9eb214cfff1766
20.593909
80
0.47567
4.222333
false
false
false
false
mindbody/Conduit
Sources/Conduit/Networking/Serialization/MultipartFormRequestSerializer.swift
1
10360
// // MultipartFormRequestSerializer.swift // Conduit // // Created by John Hammerlund on 8/8/16. // Copyright © 2017 MINDBODY. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit #elseif canImport(WatchKit) import WatchKit #elseif canImport(AppKit) import AppKit #endif /// An HTTPRequestSerializer used for constructing multipart/form-data requests /// - Important: For safety and readability, this class does not currently utilize I/O streams, /// and it therefore will cause memory pressure for massive uploads. If the need arises, /// the serializer implementation can be switched to utilize buffers. /// - Note: This serializer does not currently support mixed boundaries. Support for all other /// content types can be progressively added as needed. public final class MultipartFormRequestSerializer: HTTPRequestSerializer { static private let CRLF = "\r\n" private var formData: [FormPart] = [] lazy var contentBoundary: String = { let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let lettersLength = UInt32(letters.count) let randomCharacters = (0..<12).map { _ -> String in let offset = Int(arc4random_uniform(lettersLength)) let characters = letters[letters.index(letters.startIndex, offsetBy: offset)] return String(characters) } return randomCharacters.joined() }() private lazy var inlineContentBoundary: String = { return "--\(contentBoundary)" }() private lazy var finalContentBoundary: String = { return "--\(contentBoundary)--" }() public override init() {} /// Appends the form part to the request body /// - Parameters /// - formPart: The part to add to the form public func append(formPart: FormPart) { formData.append(formPart) } public override func serialize(request: URLRequest, bodyParameters: Any?) throws -> URLRequest { let request = try super.serialize(request: request, bodyParameters: bodyParameters) var mutableRequest = request if mutableRequest.value(forHTTPHeaderField: "Content-Type") == nil { mutableRequest.setValue("multipart/form-data; boundary=\(contentBoundary)", forHTTPHeaderField: "Content-Type") } let httpBody = try makeHTTPBody() mutableRequest.setValue(String(httpBody.count), forHTTPHeaderField: "Content-Length") mutableRequest.httpBody = httpBody return mutableRequest } private func encodedDataFrom(string: String) -> Data? { return string.data(using: .utf8) } private func defaultHeadersFor(formPart: FormPart) -> [String: String] { var dispositionParts = ["form-data"] if let formName = formPart.name { dispositionParts.append("name=\"\(formName)\"") } if let filename = formPart.filename { dispositionParts.append("filename=\"\(filename)\"") } let contentDisposition = dispositionParts.joined(separator: "; ") var headers = [ "Content-Disposition": contentDisposition ] if let contentType = formPart.contentType { headers["Content-Type"] = contentType } return headers } private func inlineContentPartDataFrom(formPart: FormPart) throws -> Data { var mutableData = Data() guard let boundaryData = encodedDataFrom(string: inlineContentBoundary), let crlfData = encodedDataFrom(string: MultipartFormRequestSerializer.CRLF) else { throw RequestSerializerError.serializationFailure } mutableData.append(boundaryData) mutableData.append(crlfData) var headers = defaultHeadersFor(formPart: formPart) for (key, value) in formPart.additionalHTTPHeaderFields { headers[key] = value } for header in headers { let headerStr = "\(header.0): \(header.1)\(MultipartFormRequestSerializer.CRLF)" guard let headerData = encodedDataFrom(string: headerStr) else { throw RequestSerializerError.serializationFailure } mutableData.append(headerData) } guard let contentData = formPart.contentData() else { throw RequestSerializerError.serializationFailure } mutableData.append(crlfData) mutableData.append(contentData) mutableData.append(crlfData) return mutableData } private func makeHTTPBody() throws -> Data { var mutableBody = Data() for formData in formData { try mutableBody.append(inlineContentPartDataFrom(formPart: formData)) } let boundaryLine = "\(finalContentBoundary)\(MultipartFormRequestSerializer.CRLF)" guard let finalBoundaryData = encodedDataFrom(string: boundaryLine) else { throw RequestSerializerError.serializationFailure } mutableBody.append(finalBoundaryData) return mutableBody } } /// Represents a part of a multipart form with associated content and content information public struct FormPart { /// The name of the form part public let name: String? /// The filename of the associated content data, if the data is binary public let filename: String? /// The form part content public let content: Content /// Additional header fields to apply to the form part (beyond Content-Disposition and Content-Type) public var additionalHTTPHeaderFields: [String: String] = [:] /// Specifies a custom (or nonexistent) Content-Type for the part headers. Defaults to the /// content's MIME type, or application/octet-stream if there is no MIME type. public var contentType: String? /// Creates a new FormPart with the provided name, filename, and content public init(name: String? = nil, filename: String? = nil, content: Content) { self.name = name self.filename = filename self.content = content self.contentType = content.mimeType() } func contentData() -> Data? { switch content { case let .image(image, type): return dataFrom(image: image, type: type) case let .video(videoData, _): return videoData case let .pdf(data): return data case let .binary(data): return data case let .text(text): return text.data(using: .utf8) } } #if canImport(AppKit) private func dataFrom(image: NSImage, type: ImageFormat) -> Data? { if let imageRepresentation = image.representations[0] as? NSBitmapImageRep { if case .jpeg(let compressionQuality) = type { let properties = [NSBitmapImageRep.PropertyKey.compressionFactor: compressionQuality] return imageRepresentation.representation(using: .jpeg, properties: properties) } return imageRepresentation.representation(using: .png, properties: [:]) } return nil } #elseif canImport(UIKit) private func dataFrom(image: UIImage, type: ImageFormat) -> Data? { if case .jpeg(let compressionQuality) = type { return image.jpegData(compressionQuality: compressionQuality) } else { return image.pngData() } } #endif /// The image format used to compress the image data public enum ImageFormat { /// JPEG representation with an associated compression quality, /// where 0.0 represents the lowest quality and 1.0 represents the highest quality case jpeg(compressionQuality: CGFloat) /// PNG representation case png } /// The multimedia container format used to describe video data public enum VideoFormat { /// Quicktime representation case mov /// MPEG-4 representation case mp4 /// Adobe Flash Video representation case flv /// Apple HLS format representaiton case m3u8 /// Microsoft interleave representation case avi /// Windows Media representation case wmv } /// A structure containing form part content information public enum Content { /// Reasoning for SwiftLint exception (false-positive): https://github.com/realm/SwiftLint/issues/2782 // swiftlint:disable duplicate_enum_cases #if canImport(AppKit) /// An image with an associated compression format case image(NSImage, ImageFormat) #elseif canImport(UIKit) /// An image with an associated compression format case image(UIImage, ImageFormat) #endif // swiftlint:enable duplicate_enum_cases /// A video with an associated media container format case video(Data, VideoFormat) /// PDF Data case pdf(Data) /// Arbitrary binary data case binary(Data) /// A plaintext value case text(String) func mimeType() -> String { switch self { case .image(_, let imageType): return imageMimeType(imageType: imageType) case .video(_, let videoType): return videoMimeType(videoType: videoType) case .pdf: return "application/pdf" case .binary: return "application/octet-stream" case .text: return "text/plain" } } private func imageMimeType(imageType: FormPart.ImageFormat) -> String { switch imageType { case .jpeg: return "image/jpeg" case .png: return "image/png" } } private func videoMimeType(videoType: FormPart.VideoFormat) -> String { switch videoType { case .avi: return "video/x-msvideo" case .flv: return "video/x-flv" case .m3u8: return "application/x-mpegURL" case .mov: return "video/quicktime" case .mp4: return "video/mp4" case .wmv: return "video/x-ms-wmv" } } } }
apache-2.0
d809d92e27b950a6b88e9e570e236875
32.095847
123
0.62786
5.166584
false
false
false
false
dasdom/GlobalADN
GlobalADN/Cells/PostCell.swift
1
3761
// // PostCell.swift // GlobalADN // // Created by dasdom on 21.06.14. // Copyright (c) 2014 Dominik Hauser. All rights reserved. // import UIKit class PostCell: UITableViewCell { private var imageLoadingQueue = NSOperationQueue() var usernameLabel: UILabel var postTextView: UITextView private var avatarImageView: UIImageView var avatarURL: NSURL? { didSet { avatarImageView.image = nil if avatarURL != nil { imageLoadingQueue.cancelAllOperations() avatarImageView.image = nil weak var weakSelf = self var imageLoadinOperation = NSBlockOperation(block: { var strongSelf = weakSelf let imageData = NSData(contentsOfURL: strongSelf!.avatarURL!) let image = UIImage(data: imageData) dispatch_async(dispatch_get_main_queue(), { strongSelf!.avatarImageView.image = image }) }) imageLoadingQueue.addOperation(imageLoadinOperation) } } } override init(style: UITableViewCellStyle, reuseIdentifier: String) { usernameLabel = { let label = UILabel() label.setTranslatesAutoresizingMaskIntoConstraints(false) label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline) return label }() postTextView = { let textView = UITextView() textView.setTranslatesAutoresizingMaskIntoConstraints(false) // textView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) textView.textContainerInset = UIEdgeInsetsMake(5, -5, 0, 0) // textView.backgroundColor = UIColor.yellowColor() // let exclusioinPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 60, height: 60)) // textView.textContainer.exclusionPaths = [exclusioinPath] // textView.backgroundColor = UIColor.clearColor() return textView }() avatarImageView = { let imageView = UIImageView() imageView.setTranslatesAutoresizingMaskIntoConstraints(false) return imageView }() super.init(style: style, reuseIdentifier: reuseIdentifier) // backgroundColor = UIColor.yellowColor() contentView.addSubview(usernameLabel) contentView.addSubview(postTextView) contentView.addSubview(avatarImageView) var viewsDictionary = ["usernameLabel" : usernameLabel, "avatarImageView" : avatarImageView, "postTextView" : postTextView] contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-5-[avatarImageView(50)]-5-[postTextView]-5-|", options: nil, metrics: nil, views: viewsDictionary)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-5-[avatarImageView(50)]-(>=5)-|", options: nil, metrics: nil, views: viewsDictionary)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-5-[usernameLabel][postTextView]-(>=5)-|", options: .AlignAllLeft, metrics: nil, views: viewsDictionary)) } required convenience init(coder aDecoder: NSCoder!) { self.init(style: .Default, reuseIdentifier: "PostCell") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func prepareForReuse() { avatarImageView.image = nil } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
57d38e4a5e7d630d3206afd9d9f24a2a
37.377551
191
0.638128
5.689864
false
false
false
false
alexhilton/cocoajourney
NotTomorrow/NotTomorrow/PomodoroViewController.swift
1
4982
// // PomodoroViewController.swift // NotTomorrow // // Created by Alex Hilton on 11/30/14. // Copyright (c) 2014 Alex Hilton. All rights reserved. // import UIKit import CoreData class PomodoroViewController: UIViewController { var taskItem: TaskEntity? @IBOutlet weak var buttonCancel: UIButton! @IBOutlet weak var buttonDone: UIButton! @IBOutlet weak var buttonPause: UIButton! @IBOutlet weak var labelCountDown: UILabel! @IBOutlet weak var labelType: UILabel! @IBOutlet weak var labelDescription: UILabel! @IBOutlet weak var labelPomodoroNumber: UILabel! var pomodoroClockTimer: PomodoroTimer? var lastPomodoroClock = 60 * 25 // 25 minutes var pausing: Bool? lazy var managedObjectContext: NSManagedObjectContext? = { let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate if let moc = appDelegate.managedObjectContext { return moc } else { return nil } }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. labelDescription.text = taskItem!.taskDescription // if task is already completed, disable all buttons and timers if taskItem!.isCompleted { buttonCancel.enabled = false buttonDone.enabled = false buttonPause.enabled = false labelType.text = "Rest time." } else { labelType.text = "Work time:" labelCountDown.text = "" } labelPomodoroNumber.text = "Pomodoro #\(taskItem!.consumed.integerValue + 1)" pausing = false } override func viewWillAppear(animated: Bool) { pomodoroClockTimer = PomodoroTimer(label: labelCountDown, initCount: lastPomodoroClock) { self.taskItem!.consumed = NSNumber(int: self.taskItem!.consumed.integerValue + 1) self.labelType.text = "Rest time." } pomodoroClockTimer!.start() } override func viewWillDisappear(animated: Bool) { var error: NSError? managedObjectContext?.save(&error) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancelClicked(sender: AnyObject) { pomodoroClockTimer!.cancel() navigationController?.popViewControllerAnimated(true) } @IBAction func taskDoneClicked(sender: AnyObject) { pomodoroClockTimer!.cancel() taskItem!.completed = true navigationController?.popViewControllerAnimated(true) } @IBAction func pauseClicked(sender: AnyObject) { if !pausing! { lastPomodoroClock = pomodoroClockTimer!.currentPomodoroClock! pomodoroClockTimer?.cancel() buttonPause.setTitle("Resume", forState: UIControlState.Normal) pausing = true } else { pomodoroClockTimer = PomodoroTimer(label: labelCountDown, initCount: lastPomodoroClock) { self.taskItem!.consumed = NSNumber(int: self.taskItem!.consumed.integerValue + 1) self.labelType.text = "Rest time." } pomodoroClockTimer?.start() buttonPause.setTitle("Pause", forState: UIControlState.Normal) pausing = false } } /* // 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. } */ class PomodoroTimer: NSThread { var label: UILabel? var acallback: ()-> Void var currentPomodoroClock: Int? init(label: UILabel, initCount: Int, callback: () -> Void) { self.label = label self.acallback = callback self.currentPomodoroClock = initCount super.init() name = "PomodoroTimer" } override func main() { while currentPomodoroClock > 0 { if cancelled { break } // sleep for 1 second NSThread.sleepForTimeInterval(1.0) if cancelled { break } let sec = String(format: "%02d", currentPomodoroClock! % 60) let min = String(format: "%02d", currentPomodoroClock! / 60) dispatch_async(dispatch_get_main_queue()) { self.label!.text = "\(min):\(sec)" } currentPomodoroClock!-- } if !cancelled { acallback() } } } }
apache-2.0
18d7a89752e439a2a8202b86e4bfe3aa
32.662162
106
0.598354
5.385946
false
false
false
false
YoungGary/Sina
Sina/Sina/Classes/Profile我/ProfileViewController.swift
1
2905
// // ProfileViewController.swift // Sina // // Created by YOUNG on 16/9/4. // Copyright © 2016年 Young. All rights reserved. // import UIKit class ProfileViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() visitorView.setupVisitorViewInfo("visitordiscover_image_profile", text: "登录后,你的微博,相册,个人资料,会显示在这里 展示给别人") } // 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
d164a64f566fbbf7b634bc1bcfb1e7c3
31.431818
157
0.6822
5.405303
false
false
false
false
silt-lang/silt
Sources/Crust/Parser.swift
1
38416
/// Parser.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Lithosphere extension Diagnostic.Message { static func unexpectedToken( _ token: TokenSyntax, expected: TokenKind? = nil) -> Diagnostic.Message { var msg: String switch token.tokenKind { case .leftBrace where token.isImplicit: msg = "unexpected opening scope" case .rightBrace where token.isImplicit: msg = "unexpected end of scope" case .semicolon where token.isImplicit: msg = "unexpected end of line" default: msg = "unexpected token '\(token.tokenKind.text)'" } if let kind = expected { msg += " (expected '\(kind.text)')" } return .init(.error, msg) } static let unexpectedEOF = Diagnostic.Message(.error, "unexpected end-of-file reached") static func expected(_ name: String) -> Diagnostic.Message { return Diagnostic.Message(.error, "expected \(name)") } static func declRequiresIndices( _ typeName: TokenSyntax) -> Diagnostic.Message { return .init(.error, """ declaration of '\(typeName.triviaFreeSourceText)' is \ missing type ascription """) } /// FIXME: Fix-It Candidate static let addBasicTypeIndex = Diagnostic.Message(.note, "add a type ascription; e.g. ': Type'") static let expectedTopLevelModule = Diagnostic.Message( .error, "missing required top level module") static let expectedNameInFuncDecl = Diagnostic.Message( .error, "expression may not be used as identifier in function name") static func unexpectedQualifiedName( _ syntax: QualifiedNameSyntax) -> Diagnostic.Message { let txt = syntax.triviaFreeSourceText return Diagnostic.Message( .error, "qualified name '\(txt)' is not allowed in this position") } static let unexpectedConstructor = Diagnostic.Message(.error, """ data constructors may only appear within the scope of a \ data declaration """) static let emptyDataDeclWithWhere = Diagnostic.Message(.error, """ data declaration with no constructors cannot have a \ 'where' clause """) static let indentToMakeConstructor = Diagnostic.Message(.note, """ indent this declaration to make it a constructor """) static let removeWhereClause = Diagnostic.Message(.note, """ remove 'where' to make an empty data declaration """) } public class Parser { public let engine: DiagnosticEngine let tokens: [TokenSyntax] public var index = 0 var offset: Int = 0 let converter: SourceLocationConverter public init(diagnosticEngine: DiagnosticEngine, tokens: [TokenSyntax], converter: SourceLocationConverter) { self.engine = diagnosticEngine self.tokens = tokens self.converter = converter } public var currentToken: TokenSyntax? { return index < tokens.count ? tokens[index] : nil } /// Looks backwards from where we are in the token stream for /// the first non-implicit token to which we can attach a diagnostic. func previousNonImplicitToken() -> TokenSyntax? { var i = 0 while let tok = peekToken(ahead: i) { defer { i -= 1 } if tok.isImplicit { continue } return tok } return nil } func expected(_ name: String) -> Diagnostic.Message { let highlightedToken = previousNonImplicitToken() return engine.diagnose(.expected(name), location: .location(self.currentLocation)) { if let tok = highlightedToken { $0.highlight(tok) } } } public func unexpectedToken( expected: TokenKind? = nil) -> Diagnostic.Message { // If we've "unexpected" an implicit token from Shining, highlight // instead the previous token because the diagnostic will say that we've // begun or ended the scope/line. let highlightedToken = previousNonImplicitToken() guard let token = currentToken else { return engine.diagnose(.unexpectedEOF, location: .location(self.currentLocation)) } let msg = Diagnostic.Message.unexpectedToken(token, expected: expected) return engine.diagnose(msg, location: .location(self.currentLocation)) { if let tok = highlightedToken { $0.highlight(tok) } } } public func consumeIf(_ kinds: TokenKind...) throws -> TokenSyntax? { guard let token = currentToken else { throw unexpectedToken(expected: kinds.first) } if kinds.contains(token.tokenKind) { advance() return token } return nil } public func consume(_ kinds: TokenKind...) throws -> TokenSyntax { guard let token = currentToken, kinds.contains(token.tokenKind) else { throw unexpectedToken(expected: kinds.first) } advance() return token } public func consumeUntil(_ kind: TokenKind) { while let token = currentToken, token.tokenKind != kind { advance() } } public func peek(ahead n: Int = 0) -> TokenKind { return peekToken(ahead: n)?.tokenKind ?? .eof } public func peekToken(ahead n: Int = 0) -> TokenSyntax? { guard index + n < tokens.count else { return nil } return tokens[index + n] } public func advance(_ n: Int = 1) { for i in 0..<n { guard let tok = peekToken(ahead: i), tok.isPresent else { break } offset += tok.byteSize } index += n } public var currentLocation: SourceLocation { return self.converter.location(for: AbsolutePosition(utf8Offset: self.offset)) } public func peekLocation(ahead n: Int = 0) -> SourceLocation { var off = self.offset for i in 0..<n { guard let tok = peekToken(ahead: i), tok.isPresent else { break } off += tok.byteSize } return self.converter.location(for: AbsolutePosition(utf8Offset: off)) } } extension Parser { public func parseTopLevelModule() -> ModuleDeclSyntax? { do { guard peek() == .moduleKeyword else { throw engine.diagnose(.expectedTopLevelModule, location: .location(self.peekLocation(ahead: 1))) } let module = try parseModule() _ = try consume(.eof) return module } catch { return nil } } } extension Parser { public func parseIdentifierToken() throws -> TokenSyntax { guard case .identifier(_) = peek() else { throw unexpectedToken() } let name = currentToken! advance() return name } public func parseQualifiedName() throws -> QualifiedNameSyntax { var pieces = [QualifiedNamePieceSyntax]() while true { guard case .identifier(_) = peek() else { continue } let id = try parseIdentifierToken() if case .period = peek() { let period = try consume(.period) pieces.append(SyntaxFactory.makeQualifiedNamePiece(name: id, trailingPeriod: period)) } else { pieces.append(SyntaxFactory.makeQualifiedNamePiece(name: id, trailingPeriod: nil)) break } } // No pieces, no qualified name. guard !pieces.isEmpty else { throw expected("name") } return SyntaxFactory.makeQualifiedNameSyntax(pieces) } /// Ensures all of the QualifiedNameSyntax nodes passed in are basic names, /// not actually fully qualified names. func ensureAllNamesSimple( _ names: [QualifiedNameSyntax], _ locs: [SourceLocation] ) -> [TokenSyntax] { return zip(names, locs).map { (qn, loc) -> TokenSyntax in let name = qn.first! if name.trailingPeriod != nil || qn.count != 1 { // Diagnose the qualified name and recover by using just the // first piece. engine.diagnose(.unexpectedQualifiedName(qn), location: .location(loc)) { $0.highlight(qn) } } return name.name } } func parseIdentifierList() throws -> IdentifierListSyntax { var names = [QualifiedNameSyntax]() var locs = [SourceLocation]() loop: while true { switch peek() { case .identifier(_), .underscore: // Parse qualified names, then verify they are all identifiers. locs.append(self.currentLocation) names.append(try parseQualifiedName()) default: break loop } } return SyntaxFactory.makeIdentifierListSyntax(ensureAllNamesSimple(names, locs)) } } extension Parser { func parseDeclList() throws -> DeclListSyntax { var pieces = [DeclSyntax]() while peek() != .rightBrace { guard peek() != .eof else { throw engine.diagnose(.unexpectedEOF) } // Recover from invalid declarations by ignoring them and parsing to the // next semicolon. let declLoc = self.peekLocation(ahead: 1) guard let decl = try? parseDecl() else { consumeUntil(.semicolon) _ = try consume(.semicolon) continue } // If this is a function declaration directly after an empty data // declaration with a `where` clause (which should have caused an error), // diagnose this as a possible constructor. if decl is FunctionDeclSyntax, let lastData = pieces.last as? DataDeclSyntax, lastData.constructorList.isEmpty { engine.diagnose(.unexpectedConstructor, location: .location(declLoc)) { $0.highlight(decl) $0.note(.indentToMakeConstructor, location: .location(declLoc)) } } pieces.append(decl) } return SyntaxFactory.makeDeclListSyntax(pieces) } func parseDecl() throws -> DeclSyntax { switch peek() { case .moduleKeyword: return try self.parseModule() case .dataKeyword: let declLoc = self.peekLocation(ahead: 1) let decl = try self.parseDataDecl() // If there's a regular data decl and an empty constructor list, // throw an error. if let dataDecl = decl as? DataDeclSyntax, dataDecl.constructorList.isEmpty { engine.diagnose(.emptyDataDeclWithWhere, location: .location(declLoc)) { $0.highlight(decl) $0.note(.removeWhereClause, location: .location(declLoc), highlights: [dataDecl.whereToken]) } } return decl case .recordKeyword: return try self.parseRecordDecl() case .openKeyword: return try self.parseOpenImportDecl() case .importKeyword: return try self.parseImportDecl() case .infixKeyword, .infixlKeyword, .infixrKeyword: return try self.parseInfixDecl() case _ where isStartOfBasicExpr(): return try self.parseFunctionDeclOrClause() default: advance() throw expected("declaration") } } func parseModule() throws -> ModuleDeclSyntax { let moduleKw = try consume(.moduleKeyword) let moduleId = try parseQualifiedName() let paramList = try parseTypedParameterList() let whereKw = try consume(.whereKeyword) let leftBrace = try consume(.leftBrace) let declList = try parseDeclList() let rightBrace = try consume(.rightBrace) let semi = try consume(.semicolon) return SyntaxFactory.makeModuleDecl( moduleToken: moduleKw, moduleIdentifier: moduleId, typedParameterList: paramList, whereToken: whereKw, leftBraceToken: leftBrace, declList: declList, rightBraceToken: rightBrace, trailingSemicolon: semi ) } func parseOpenImportDecl() throws -> OpenImportDeclSyntax { return SyntaxFactory.makeOpenImportDecl( openToken: try consume(.openKeyword), importToken: try consume(.importKeyword), importIdentifier: try parseQualifiedName(), trailingSemicolon: try consume(.semicolon) ) } func parseImportDecl() throws -> ImportDeclSyntax { return SyntaxFactory.makeImportDecl( importToken: try consume(.importKeyword), importIdentifier: try parseQualifiedName(), trailingSemicolon: try consume(.semicolon) ) } } extension Parser { func parseInfixDecl() throws -> FixityDeclSyntax { switch peek() { case .infixKeyword: return try self.parseNonFixDecl() case .infixlKeyword: return try self.parseLeftFixDecl() case .infixrKeyword: return try self.parseRightFixDecl() default: throw unexpectedToken() } } func parseNonFixDecl() throws -> NonFixDeclSyntax { let tok = try consume(.infixKeyword) let prec = try parseIdentifierToken() let ids = try parseIdentifierList() let semi = try consume(.semicolon) return SyntaxFactory.makeNonFixDecl( infixToken: tok, precedence: prec, names: ids, trailingSemicolon: semi ) } func parseLeftFixDecl() throws -> LeftFixDeclSyntax { let tok = try consume(.infixlKeyword) let prec = try parseIdentifierToken() let ids = try parseIdentifierList() let semi = try consume(.semicolon) return SyntaxFactory.makeLeftFixDecl( infixlToken: tok, precedence: prec, names: ids, trailingSemicolon: semi ) } func parseRightFixDecl() throws -> RightFixDeclSyntax { let tok = try consume(.infixrKeyword) let prec = try parseIdentifierToken() let ids = try parseIdentifierList() let semi = try consume(.semicolon) return SyntaxFactory.makeRightFixDecl( infixrToken: tok, precedence: prec, names: ids, trailingSemicolon: semi ) } } extension Parser { func parseRecordDecl() throws -> RecordDeclSyntax { let recordTok = try consume(.recordKeyword) let recName = try parseIdentifierToken() let paramList = try parseTypedParameterList() let indices = try parseTypeIndices(recName, self.currentLocation) let whereTok = try consume(.whereKeyword) let leftTok = try consume(.leftBrace) let elemList = try parseRecordElementList() let rightTok = try consume(.rightBrace) let trailingSemi = try consume(.semicolon) return SyntaxFactory.makeRecordDecl( recordToken: recordTok, recordName: recName, parameterList: paramList, typeIndices: indices, whereToken: whereTok, leftParenToken: leftTok, recordElementList: elemList, rightParenToken: rightTok, trailingSemicolon: trailingSemi ) } func parseRecordElementList() throws -> DeclListSyntax { var pieces = [DeclSyntax]() loop: while true { switch peek() { case .identifier(_): pieces.append(try parseFunctionDeclOrClause()) case .fieldKeyword: pieces.append(try parseFieldDecl()) case .constructorKeyword: pieces.append(try parseRecordConstructorDecl()) default: break loop } } return SyntaxFactory.makeDeclListSyntax(pieces) } func parseRecordElement() throws -> DeclSyntax { switch peek() { case .fieldKeyword: return try self.parseFieldDecl() case .identifier(_): return try self.parseFunctionDeclOrClause() case .constructorKeyword: return try parseRecordConstructorDecl() default: throw expected("field or function declaration") } } func parseFieldDecl() throws -> FieldDeclSyntax { let fieldTok = try consume(.fieldKeyword) let ascription = try parseAscription() let trailingSemi = try consume(.semicolon) return SyntaxFactory.makeFieldDecl( fieldToken: fieldTok, ascription: ascription, trailingSemicolon: trailingSemi ) } func parseRecordConstructorDecl() throws -> RecordConstructorDeclSyntax { let constrTok = try consume(.constructorKeyword) let constrName = try parseIdentifierToken() let trailingSemi = try consume(.semicolon) return SyntaxFactory.makeRecordConstructorDecl( constructorToken: constrTok, constructorName: constrName, trailingSemicolon: trailingSemi ) } } extension Parser { func isStartOfTypedParameter() -> Bool { guard self.index + 1 < self.tokens.endIndex else { return false } switch (peek(), peek(ahead: 1)) { case (.leftBrace, .identifier(_)): return true case (.leftParen, .identifier(_)): return true default: return false } } func parseTypedParameterList() throws -> TypedParameterListSyntax { var pieces = [TypedParameterSyntax]() while isStartOfTypedParameter() { pieces.append(try parseTypedParameter()) } return SyntaxFactory.makeTypedParameterListSyntax(pieces) } func parseTypedParameter() throws -> TypedParameterSyntax { switch peek() { case .leftParen: return try self.parseExplicitTypedParameter() case .leftBrace: return try self.parseImplicitTypedParameter() default: throw expected("typed parameter") } } func parseExplicitTypedParameter() throws -> ExplicitTypedParameterSyntax { let leftParen = try consume(.leftParen) let ascription = try parseAscription() let rightParen = try consume(.rightParen) return SyntaxFactory.makeExplicitTypedParameter( leftParenToken: leftParen, ascription: ascription, rightParenToken: rightParen) } func parseImplicitTypedParameter() throws -> ImplicitTypedParameterSyntax { let leftBrace = try consume(.leftBrace) let ascription = try parseAscription() let rightBrace = try consume(.rightBrace) return SyntaxFactory.makeImplicitTypedParameter( leftBraceToken: leftBrace, ascription: ascription, rightBraceToken: rightBrace) } func parseTypeIndices( _ parentName: TokenSyntax, _ loc: SourceLocation ) throws -> TypeIndicesSyntax { // If we see a semicolon or 'where' after the identifier, the // user likely forgot to provide indices for this data type. // Recover by inserting `: Type`. guard [.semicolon, .whereKeyword].contains(peek()) else { let colon = try consume(.colon) let expr = try parseExpr() return SyntaxFactory.makeTypeIndices(colonToken: colon, indexExpr: expr) } let indices = SyntaxFactory.makeTypeIndices( colonToken: SyntaxFactory.makeColon(), indexExpr: implicitNamedExpr(.typeKeyword)) engine.diagnose(.declRequiresIndices(parentName), location: .location(loc)) { $0.highlight(parentName) $0.note(.addBasicTypeIndex, location: .location(loc)) } return indices } func parseAscription() throws -> AscriptionSyntax { let boundNames = try parseIdentifierList() let colonToken = try consume(.colon) let expr = try parseExpr() return SyntaxFactory.makeAscription( boundNames: boundNames, colonToken: colonToken, typeExpr: expr) } } extension Parser { func implicitNamedExpr(_ name: TokenKind) -> NamedBasicExprSyntax { let tok = SyntaxFactory.makeToken(name, presence: .implicit) let piece = SyntaxFactory.makeQualifiedNamePiece(name: tok, trailingPeriod: nil) return SyntaxFactory.makeNamedBasicExpr( name: SyntaxFactory.makeQualifiedNameSyntax([piece])) } func parseDataDecl() throws -> DeclSyntax { let dataTok = try consume(.dataKeyword) let dataId = try parseIdentifierToken() let paramList = try parseTypedParameterList() let indices = try parseTypeIndices(dataId, self.currentLocation) if let whereTok = try consumeIf(.whereKeyword) { let leftBrace = try consume(.leftBrace) let constrList = try parseConstructorList() let rightBrace = try consume(.rightBrace) let semi = try consume(.semicolon) return SyntaxFactory.makeDataDecl( dataToken: dataTok, dataIdentifier: dataId, typedParameterList: paramList, typeIndices: indices, whereToken: whereTok, leftBraceToken: leftBrace, constructorList: constrList, rightBraceToken: rightBrace, trailingSemicolon: semi) } else { let semi = try consume(.semicolon) return SyntaxFactory.makeEmptyDataDecl( dataToken: dataTok, dataIdentifier: dataId, typedParameterList: paramList, typeIndices: indices, trailingSemicolon: semi) } } func parseConstructorList() throws -> ConstructorListSyntax { var pieces = [ConstructorDeclSyntax]() while peek() != .rightBrace { pieces.append(try parseConstructor()) } return SyntaxFactory.makeConstructorListSyntax(pieces) } func parseConstructor() throws -> ConstructorDeclSyntax { let ascription = try parseAscription() let semi = try consume(.semicolon) return SyntaxFactory.makeConstructorDecl( ascription: ascription, trailingSemicolon: semi) } } extension Parser { func parseFunctionDeclOrClause() throws -> DeclSyntax { let (exprs, exprLocs) = try parseBasicExprList() switch peek() { case .colon: return try self.finishParsingFunctionDecl(exprs, exprLocs) case .equals, .withKeyword: return try self.finishParsingFunctionClause(exprs) default: return try self.finishParsingAbsurdFunctionClause(exprs) } } func finishParsingFunctionDecl( _ exprs: BasicExprListSyntax, _ locs: [SourceLocation] ) throws -> FunctionDeclSyntax { let colonTok = try self.consume(.colon) let boundNames = SyntaxFactory .makeIdentifierListSyntax(try zip(exprs, locs).map { (expr, loc) in guard let namedExpr = expr as? NamedBasicExprSyntax else { throw engine.diagnose(.expectedNameInFuncDecl, location: .location(loc)) } guard let name = namedExpr.name.first, namedExpr.name.count == 1 else { throw engine.diagnose(.unexpectedQualifiedName(namedExpr.name), location: .location(loc)) } return name.name }) let typeExpr = try self.parseExpr() let ascription = SyntaxFactory.makeAscription( boundNames: boundNames, colonToken: colonTok, typeExpr: typeExpr ) return SyntaxFactory.makeFunctionDecl( ascription: ascription, trailingSemicolon: try consume(.semicolon)) } func finishParsingFunctionClause( _ exprs: BasicExprListSyntax) throws -> FunctionClauseDeclSyntax { if case .withKeyword = peek() { return SyntaxFactory.makeWithRuleFunctionClauseDecl( basicExprList: exprs, withToken: try consume(.withKeyword), withExpr: try parseExpr(), withPatternClause: try parseBasicExprList().0, equalsToken: try consume(.equals), rhsExpr: try parseExpr(), whereClause: try maybeParseWhereClause(), trailingSemicolon: try consume(.semicolon)) } assert(peek() == .equals) return SyntaxFactory.makeNormalFunctionClauseDecl( basicExprList: exprs, equalsToken: try consume(.equals), rhsExpr: try parseExpr(), whereClause: try maybeParseWhereClause(), trailingSemicolon: try consume(.semicolon)) } func finishParsingAbsurdFunctionClause( _ exprs: BasicExprListSyntax) throws -> AbsurdFunctionClauseDeclSyntax { return SyntaxFactory.makeAbsurdFunctionClauseDecl( basicExprList: exprs, trailingSemicolon: try consume(.semicolon) ) } func maybeParseWhereClause() throws -> FunctionWhereClauseDeclSyntax? { guard case .whereKeyword = peek() else { return nil } return SyntaxFactory.makeFunctionWhereClauseDecl( whereToken: try consume(.whereKeyword), leftBraceToken: try consume(.leftBrace), declList: try parseDeclList(), rightBraceToken: try consume(.rightBrace) ) } } extension Parser { func isStartOfExpr() -> Bool { if isStartOfBasicExpr() { return true } switch peek() { case .backSlash, .forallSymbol, .forallKeyword, .letKeyword: return true default: return false } } func isStartOfBasicExpr(parseGIR: Bool = false) -> Bool { if parseGIR && peekToken()!.leadingTrivia.containsNewline { return false } switch peek() { case .underscore, .typeKeyword, .leftParen, .recordKeyword, .identifier(_): return true case .leftBrace where !parseGIR: return true default: return false } } // Breaks the ambiguity in parsing the beginning of a typed parameter // // (a b c ... : <expr>) // // and the beginning of an application expression // // (a b c ...) func parseParenthesizedExpr() throws -> BasicExprSyntax { let leftParen = try consume(.leftParen) if case .rightParen = peek() { let rightParen = try consume(.rightParen) return SyntaxFactory.makeAbsurdExpr(leftParenToken: leftParen, rightParenToken: rightParen) } // If we've hit a non-identifier token, start parsing a parenthesized // expression. guard case .identifier(_) = peek() else { let expr = try parseExpr() let rightParen = try consume(.rightParen) return SyntaxFactory.makeParenthesizedExpr( leftParenToken: leftParen, expr: expr, rightParenToken: rightParen ) } // Gather all the subexpressions. var exprs = [BasicExprSyntax]() var exprLocs = [SourceLocation]() while isStartOfBasicExpr() { exprLocs.append(self.currentLocation) exprs.append(try parseBasicExpr()) } // If we've not hit the matching closing paren, we must be parsing a typed // parameter group // // (a b c ... : <expr>) {d e f ... : <expr>} ... if case .colon = peek() { return try self.finishParsingTypedParameterGroupExpr(leftParen, exprs, exprLocs) } // Else consume the closing paren. let rightParen = try consume(.rightParen) // If there's only one named expression like '(a)', return it. guard exprs.count >= 1 else { return SyntaxFactory.makeParenthesizedExpr( leftParenToken: leftParen, expr: exprs[0], rightParenToken: rightParen ) } // Else form an application expression. let appExprs = SyntaxFactory.makeBasicExprListSyntax(exprs) let app = SyntaxFactory.makeApplicationExpr(exprs: appExprs) return SyntaxFactory.makeParenthesizedExpr( leftParenToken: leftParen, expr: app, rightParenToken: rightParen ) } func parseExpr() throws -> ExprSyntax { switch peek() { case .backSlash: return try self.parseLambdaExpr() case .forallSymbol, .forallKeyword: return try self.parseQuantifiedExpr() case .letKeyword: return try self.parseLetExpr() default: // If we're looking at another basic expr, then we're trying to parse // either an application or an -> expression. Either way, parse the // remaining list of expressions and construct a BasicExprList with the // first expression at the beginning. var exprs = [BasicExprSyntax]() while isStartOfBasicExpr() || peek() == .arrow { // If we see an arrow at the start, then consume it and move on. if case .arrow = peek() { let arrow = try consume(.arrow) let name = SyntaxFactory.makeQualifiedNameSyntax([ SyntaxFactory.makeQualifiedNamePiece(name: arrow, trailingPeriod: nil) ]) exprs.append(SyntaxFactory.makeNamedBasicExpr(name: name)) } else { exprs.append(contentsOf: try parseBasicExprs().0) } } if exprs.isEmpty { throw expected("expression") } // If there's only one expression in this "application", then just return // it without constructing an application. guard exprs.count > 1 else { return exprs[0] } return SyntaxFactory.makeApplicationExpr( exprs: SyntaxFactory.makeBasicExprListSyntax(exprs)) } } func parseTypedParameterGroupExpr() throws -> TypedParameterGroupExprSyntax { let parameters = try parseTypedParameterList() guard !parameters.isEmpty else { throw expected("type ascription") } return SyntaxFactory.makeTypedParameterGroupExpr( parameters: parameters ) } func finishParsingTypedParameterGroupExpr( _ leftParen: TokenSyntax, _ exprs: [ExprSyntax], _ locs: [SourceLocation] ) throws -> TypedParameterGroupExprSyntax { let colonTok = try consume(.colon) // Ensure all expressions are simple names let names = try zip(exprs, locs).map { (expr, loc) -> QualifiedNameSyntax in guard let namedExpr = expr as? NamedBasicExprSyntax else { throw engine.diagnose(.expected("identifier"), location: .location(loc)) { $0.highlight(expr) } } return namedExpr.name } let tokens = ensureAllNamesSimple(names, locs) let identList = SyntaxFactory.makeIdentifierListSyntax(tokens) let typeExpr = try self.parseExpr() let ascription = SyntaxFactory.makeAscription(boundNames: identList, colonToken: colonTok, typeExpr: typeExpr) let rightParen = try consume(.rightParen) let firstParam = SyntaxFactory.makeExplicitTypedParameter( leftParenToken: leftParen, ascription: ascription, rightParenToken: rightParen) let parameters = try parseTypedParameterList().prepending(firstParam) guard !parameters.isEmpty else { throw expected("type ascription") } return SyntaxFactory.makeTypedParameterGroupExpr(parameters: parameters) } func parseLambdaExpr() throws -> LambdaExprSyntax { let slashTok = try consume(.backSlash) let bindingList = try parseBindingList() let arrowTok = try consume(.arrow) let bodyExpr = try parseExpr() return SyntaxFactory.makeLambdaExpr( slashToken: slashTok, bindingList: bindingList, arrowToken: arrowTok, bodyExpr: bodyExpr ) } func parseQuantifiedExpr() throws -> QuantifiedExprSyntax { let forallTok = try consume(.forallSymbol, .forallKeyword) let bindingList = try parseTypedParameterList() let arrow = try consume(.arrow) let outputExpr = try parseExpr() return SyntaxFactory.makeQuantifiedExpr( forallToken: forallTok, bindingList: bindingList, arrowToken: arrow, outputExpr: outputExpr ) } func parseLetExpr() throws -> LetExprSyntax { let letTok = try consume(.letKeyword) let leftBrace = try consume(.leftBrace) let declList = try parseDeclList() let rightBrace = try consume(.rightBrace) let inTok = try consume(.inKeyword) let outputExpr = try parseExpr() return SyntaxFactory.makeLetExpr( letToken: letTok, leftBraceToken: leftBrace, declList: declList, rightBraceToken: rightBrace, inToken: inTok, outputExpr: outputExpr) } func parseBasicExprs( diagType: String = "expression", parseGIR: Bool = false) throws -> ([BasicExprSyntax], [SourceLocation]) { var pieces = [BasicExprSyntax]() var locs = [SourceLocation]() while isStartOfBasicExpr(parseGIR: parseGIR) { if parseGIR && peekToken()!.leadingTrivia.containsNewline { return (pieces, locs) } locs.append(self.currentLocation) pieces.append(try parseBasicExpr(parseGIR: parseGIR)) } guard !pieces.isEmpty else { throw expected(diagType) } return (pieces, locs) } func parseBasicExprList() throws -> (BasicExprListSyntax, [SourceLocation]) { let (exprs, locs) = try parseBasicExprs(diagType: "list of expressions") return (SyntaxFactory.makeBasicExprListSyntax(exprs), locs) } public func parseBasicExpr(parseGIR: Bool = false) throws -> BasicExprSyntax { switch peek() { case .underscore: return try self.parseUnderscoreExpr() case .typeKeyword: return try self.parseTypeBasicExpr() case .leftParen: return try self.parseParenthesizedExpr() case .leftBrace where !parseGIR: return try self.parseTypedParameterGroupExpr() case .recordKeyword: return try self.parseRecordExpr() case .identifier(_): return try self.parseNamedBasicExpr() default: throw expected("expression") } } func parseRecordExpr() throws -> RecordExprSyntax { let recordTok = try consume(.recordKeyword) let parameterExpr = isStartOfBasicExpr() ? try parseBasicExpr() : nil let leftBrace = try consume(.leftBrace) let fieldAssigns = try parseRecordFieldAssignmentList() let rightBrace = try consume(.rightBrace) return SyntaxFactory.makeRecordExpr( recordToken: recordTok, parameterExpr: parameterExpr, leftBraceToken: leftBrace, fieldAssignments: fieldAssigns, rightBraceToken: rightBrace ) } func parseRecordFieldAssignmentList() throws -> RecordFieldAssignmentListSyntax { var pieces = [RecordFieldAssignmentSyntax]() while case .identifier(_) = peek() { pieces.append(try parseRecordFieldAssignment()) } return SyntaxFactory.makeRecordFieldAssignmentListSyntax(pieces) } func parseRecordFieldAssignment() throws -> RecordFieldAssignmentSyntax { let fieldName = try parseIdentifierToken() let equalsTok = try consume(.equals) let fieldInit = try parseExpr() let trailingSemi = try consume(.semicolon) return SyntaxFactory.makeRecordFieldAssignment( fieldName: fieldName, equalsToken: equalsTok, fieldInitExpr: fieldInit, trailingSemicolon: trailingSemi ) } func parseNamedBasicExpr() throws -> NamedBasicExprSyntax { let name = try parseQualifiedName() return SyntaxFactory.makeNamedBasicExpr(name: name) } func parseUnderscoreExpr() throws -> UnderscoreExprSyntax { let underscore = try consume(.underscore) return SyntaxFactory.makeUnderscoreExpr(underscoreToken: underscore) } func parseTypeBasicExpr() throws -> TypeBasicExprSyntax { let typeTok = try consume(.typeKeyword) return SyntaxFactory.makeTypeBasicExpr(typeToken: typeTok) } func parseBindingList() throws -> BindingListSyntax { var pieces = [BindingSyntax]() while true { if isStartOfTypedParameter() { pieces.append(try parseTypedBinding()) } else if case .underscore = peek() { pieces.append(try parseAnonymousBinding()) } else if case .identifier(_) = peek(), peek() != .arrow { pieces.append(try parseNamedBinding()) } else { break } } guard !pieces.isEmpty else { throw expected("binding list") } return SyntaxFactory.makeBindingListSyntax(pieces) } func parseNamedBinding() throws -> NamedBindingSyntax { let name = try parseQualifiedName() return SyntaxFactory.makeNamedBinding(name: name) } func parseTypedBinding() throws -> TypedBindingSyntax { let parameter = try parseTypedParameter() return SyntaxFactory.makeTypedBinding(parameter: parameter) } func parseAnonymousBinding() throws -> AnonymousBindingSyntax { let underscore = try consume(.underscore) return SyntaxFactory.makeAnonymousBinding(underscoreToken: underscore) } } extension Parser { func isStartOfGIRTypedParameter() -> Bool { guard self.index + 1 < self.tokens.endIndex else { return false } switch (peek(), peek(ahead: 1)) { case (.leftParen, .identifier(_)): return true default: return false } } func parseGIRTypedParameterList() throws -> TypedParameterListSyntax { var pieces = [TypedParameterSyntax]() while isStartOfGIRTypedParameter() { pieces.append(try parseGIRTypedParameter()) } return SyntaxFactory.makeTypedParameterListSyntax(pieces) } func parseGIRTypedParameter() throws -> TypedParameterSyntax { switch peek() { case .leftParen: return try self.parseExplicitTypedParameter() default: throw expected("typed parameter") } } func parseGIRQuantifiedExpr() throws -> QuantifiedExprSyntax { let forallTok = try consume(.forallSymbol, .forallKeyword) let bindingList = try parseGIRTypedParameterList() let arrow = try consume(.arrow) let outputExpr = try parseExpr() return SyntaxFactory.makeQuantifiedExpr( forallToken: forallTok, bindingList: bindingList, arrowToken: arrow, outputExpr: outputExpr ) } public func parseGIRTypeExpr() throws -> ExprSyntax { switch peek() { case .backSlash: return try self.parseLambdaExpr() case .forallSymbol, .forallKeyword: return try self.parseGIRQuantifiedExpr() default: // If we're looking at another basic expr, then we're trying to parse // either an application or an -> expression. Either way, parse the // remaining list of expressions and construct a BasicExprList with the // first expression at the beginning. var exprs = [BasicExprSyntax]() while isStartOfBasicExpr(parseGIR: true) || peek() == .arrow { // If we see an arrow at the start, then consume it and move on. if case .arrow = peek() { let arrow = try consume(.arrow) let name = SyntaxFactory.makeQualifiedNameSyntax([ SyntaxFactory.makeQualifiedNamePiece(name: arrow, trailingPeriod: nil), ]) exprs.append(SyntaxFactory.makeNamedBasicExpr(name: name)) } else { exprs.append(contentsOf: try parseBasicExprs(parseGIR: true).0) } } if exprs.isEmpty { throw expected("expression") } // If there's only one expression in this "application", then just return // it without constructing an application. guard exprs.count > 1 else { return exprs[0] } return SyntaxFactory.makeApplicationExpr( exprs: SyntaxFactory.makeBasicExprListSyntax(exprs)) } } }
mit
27d224285a5aefa028f44ba5955df221
31.255248
80
0.660714
4.951153
false
false
false
false
xedin/swift
test/IDE/print_types.swift
17
5971
// This file should not have any syntax or type checker errors. // RUN: %target-typecheck-verify-swift // RUN: %target-swift-ide-test -print-types -source-filename %s -fully-qualified-types=false | %FileCheck %s -strict-whitespace // RUN: %target-swift-ide-test -print-types -source-filename %s -fully-qualified-types=true | %FileCheck %s -check-prefix=FULL -strict-whitespace typealias MyInt = Int // CHECK: TypeAliasDecl '''MyInt''' MyInt.Type{{$}} // FULL: TypeAliasDecl '''MyInt''' swift_ide_test.MyInt.Type{{$}} func testVariableTypes(_ param: Int, param2: inout Double) { // CHECK: FuncDecl '''testVariableTypes''' (Int, inout Double) -> (){{$}} // FULL: FuncDecl '''testVariableTypes''' (Swift.Int, inout Swift.Double) -> (){{$}} var a1 = 42 // CHECK: VarDecl '''a1''' Int{{$}} // CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int{{$}} // FULL: VarDecl '''a1''' Swift.Int{{$}} // FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Swift.Int{{$}} a1 = 17; _ = a1 var a2 : Int = 42 // CHECK: VarDecl '''a2''' Int{{$}} // CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int{{$}} // FULL: VarDecl '''a2''' Swift.Int{{$}} // FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Swift.Int{{$}} a2 = 17; _ = a2 var a3 = Int16(42) // CHECK: VarDecl '''a3''' Int16{{$}} // CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int16{{$}} // FULL: VarDecl '''a3''' Swift.Int16{{$}} // FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Swift.Int16{{$}} a3 = 17; _ = a3 var a4 = Int32(42) // CHECK: VarDecl '''a4''' Int32{{$}} // CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int32{{$}} // FULL: VarDecl '''a4''' Swift.Int32{{$}} // FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Swift.Int32{{$}} a4 = 17; _ = a4 var a5 : Int64 = 42 // CHECK: VarDecl '''a5''' Int64{{$}} // CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int64{{$}} // FULL: VarDecl '''a5''' Swift.Int64{{$}} // FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Swift.Int64{{$}} a5 = 17; _ = a5 var typealias1 : MyInt = 42 // CHECK: VarDecl '''typealias1''' MyInt{{$}} // CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int{{$}} // FULL: VarDecl '''typealias1''' swift_ide_test.MyInt{{$}} // FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Swift.Int{{$}} _ = typealias1 ; typealias1 = 1 var optional1 = Optional<Int>.none // CHECK: VarDecl '''optional1''' Int?{{$}} // FULL: VarDecl '''optional1''' Swift.Int?{{$}} _ = optional1 ; optional1 = nil var optional2 = Optional<[Int]>.none _ = optional2 ; optional2 = nil // CHECK: VarDecl '''optional2''' [Int]?{{$}} // FULL: VarDecl '''optional2''' [Swift.Int]?{{$}} } func testFuncType1() {} // CHECK: FuncDecl '''testFuncType1''' () -> (){{$}} // FULL: FuncDecl '''testFuncType1''' () -> (){{$}} func testFuncType2() -> () {} // CHECK: FuncDecl '''testFuncType2''' () -> (){{$}} // FULL: FuncDecl '''testFuncType2''' () -> (){{$}} func testFuncType3() -> Void {} // CHECK: FuncDecl '''testFuncType3''' () -> Void{{$}} // FULL: FuncDecl '''testFuncType3''' () -> Swift.Void{{$}} func testFuncType4() -> MyInt {} // CHECK: FuncDecl '''testFuncType4''' () -> MyInt{{$}} // FULL: FuncDecl '''testFuncType4''' () -> swift_ide_test.MyInt{{$}} func testFuncType5() -> (Int) {} // CHECK: FuncDecl '''testFuncType5''' () -> (Int){{$}} // FULL: FuncDecl '''testFuncType5''' () -> (Swift.Int){{$}} func testFuncType6() -> (Int, Int) {} // CHECK: FuncDecl '''testFuncType6''' () -> (Int, Int){{$}} // FULL: FuncDecl '''testFuncType6''' () -> (Swift.Int, Swift.Int){{$}} func testFuncType7(_ a: Int, withFloat b: Float) {} // CHECK: FuncDecl '''testFuncType7''' (Int, Float) -> (){{$}} // FULL: FuncDecl '''testFuncType7''' (Swift.Int, Swift.Float) -> (){{$}} func testVariadicFuncType(_ a: Int, b: Float...) {} // CHECK: FuncDecl '''testVariadicFuncType''' (Int, Float...) -> (){{$}} // FULL: FuncDecl '''testVariadicFuncType''' (Swift.Int, Swift.Float...) -> (){{$}} func testCurriedFuncType1(_ a: Int) -> (_ b: Float) -> () {} // CHECK: FuncDecl '''testCurriedFuncType1''' (Int) -> (Float) -> (){{$}} // FULL: FuncDecl '''testCurriedFuncType1''' (Swift.Int) -> (Swift.Float) -> (){{$}} protocol FooProtocol {} protocol BarProtocol {} protocol QuxProtocol { associatedtype Qux } struct GenericStruct<A, B : FooProtocol> {} func testInGenericFunc1<A, B : FooProtocol, C : FooProtocol & BarProtocol>(_ a: A, b: B, c: C) { // CHECK: FuncDecl '''testInGenericFunc1''' <A, B, C where B : FooProtocol, C : BarProtocol, C : FooProtocol> (A, b: B, c: C) -> (){{$}} // FULL: FuncDecl '''testInGenericFunc1''' <A, B, C where B : swift_ide_test.FooProtocol, C : swift_ide_test.BarProtocol, C : swift_ide_test.FooProtocol> (A, b: B, c: C) -> (){{$}} var a1 = a _ = a1; a1 = a // CHECK: VarDecl '''a1''' A{{$}} // FULL: VarDecl '''a1''' A{{$}} var b1 = b _ = b1; b1 = b // CHECK: VarDecl '''b1''' B{{$}} // FULL: VarDecl '''b1''' B{{$}} var gs1 = GenericStruct<A, B>() _ = gs1; gs1 = GenericStruct<A, B>() // CHECK: VarDecl '''gs1''' GenericStruct<A, B>{{$}} // CHECK: CallExpr:[[@LINE-2]] '''GenericStruct<A, B>()''' GenericStruct<A, B>{{$}} // CHECK: ConstructorRefCallExpr:[[@LINE-3]] '''GenericStruct<A, B>''' () -> GenericStruct<A, B> // FULL: VarDecl '''gs1''' swift_ide_test.GenericStruct<A, B>{{$}} // FULL: CallExpr:[[@LINE-6]] '''GenericStruct<A, B>()''' swift_ide_test.GenericStruct<A, B>{{$}} // FULL: ConstructorRefCallExpr:[[@LINE-7]] '''GenericStruct<A, B>''' () -> swift_ide_test.GenericStruct<A, B> } func testInGenericFunc2<T : QuxProtocol, U : QuxProtocol>(_: T, _: U) where T.Qux == U.Qux {} // CHECK: FuncDecl '''testInGenericFunc2''' <T, U where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux> (T, U) -> (){{$}} // FULL: FuncDecl '''testInGenericFunc2''' <T, U where T : swift_ide_test.QuxProtocol, U : swift_ide_test.QuxProtocol, T.Qux == U.Qux> (T, U) -> (){{$}}
apache-2.0
e958897d3a0ef49ee3816b14c02130c1
41.65
181
0.573941
3.441499
false
true
false
false
apple/swift-syntax
Sources/SwiftParser/LexerDiagnosticMessages.swift
1
2853
//===--- LexerDiagnosticMessages.swift ------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftDiagnostics @_spi(RawSyntax) import SwiftSyntax fileprivate let diagnosticDomain: String = "SwiftLexer" /// A error diagnostic whose ID is determined by the diagnostic's type. public protocol LexerError: DiagnosticMessage { var diagnosticID: MessageID { get } } public extension LexerError { static var diagnosticID: MessageID { return MessageID(domain: diagnosticDomain, id: "\(self)") } var diagnosticID: MessageID { return Self.diagnosticID } var severity: DiagnosticSeverity { return .error } } // MARK: - Errors (please sort alphabetically) /// Please order the cases in this enum alphabetically by case name. public enum StaticLexerError: String, DiagnosticMessage { case expectedBinaryExponentInHexFloatLiteral = "hexadecimal floating point literal must end with an exponent" case expectedDigitInFloatLiteral = "expected a digit in floating point exponent" public var message: String { self.rawValue } public var diagnosticID: MessageID { MessageID(domain: diagnosticDomain, id: "\(type(of: self)).\(self)") } public var severity: DiagnosticSeverity { .error } } public struct InvalidFloatingPointExponentDigit: LexerError { public enum Kind { case digit(Unicode.Scalar) case character(Unicode.Scalar) } public let kind: Self.Kind public var message: String { switch self.kind { case .digit(let digit): return "'\(digit)' is not a valid digit in floating point exponent" case .character(let char): return "'\(char)' is not a valid first character in floating point exponent" } } } public struct InvalidDigitInIntegerLiteral: LexerError { public enum Kind { case binary(Unicode.Scalar) case octal(Unicode.Scalar) case decimal(Unicode.Scalar) case hex(Unicode.Scalar) } public let kind: Self.Kind public var message: String { switch self.kind { case .binary(let digit): return "'\(digit)' is not a valid binary digit (0 or 1) in integer literal" case .octal(let digit): return "'\(digit)' is not a valid octal digit (0-7) in integer literal" case .decimal(let digit): return "'\(digit)' is not a valid digit in integer literal" case .hex(let digit): return "'\(digit)' is not a valid hexadecimal digit (0-9, A-F) in integer literal" } } }
apache-2.0
7185f8ac6e9901da055473bbb7c90f69
30.01087
111
0.683491
4.416409
false
false
false
false
lightsprint09/socket.io-client-swift
Source/SocketIO/Parse/SocketParsable.swift
1
5979
// // SocketParsable.swift // Socket.IO-Client-Swift // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation protocol SocketParsable { func parseBinaryData(_ data: Data) func parseSocketMessage(_ message: String) } enum SocketParsableError : Error { case invalidDataArray case invalidPacket case invalidPacketType } extension SocketParsable where Self: SocketIOClientSpec { private func isCorrectNamespace(_ nsp: String) -> Bool { return nsp == self.nsp } private func handleConnect(_ packetNamespace: String) { if packetNamespace == "/" && nsp != "/" { joinNamespace(nsp) } else { didConnect(toNamespace: packetNamespace) } } private func handlePacket(_ pack: SocketPacket) { switch pack.type { case .event where isCorrectNamespace(pack.nsp): handleEvent(pack.event, data: pack.args, isInternalMessage: false, withAck: pack.id) case .ack where isCorrectNamespace(pack.nsp): handleAck(pack.id, data: pack.data) case .binaryEvent where isCorrectNamespace(pack.nsp): waitingPackets.append(pack) case .binaryAck where isCorrectNamespace(pack.nsp): waitingPackets.append(pack) case .connect: handleConnect(pack.nsp) case .disconnect: didDisconnect(reason: "Got Disconnect") case .error: handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id) default: DefaultSocketLogger.Logger.log("Got invalid packet: \(pack.description)", type: "SocketParser") } } /// Parses a messsage from the engine, returning a complete SocketPacket or throwing. func parseString(_ message: String) throws -> SocketPacket { var reader = SocketStringReader(message: message) guard let type = Int(reader.read(count: 1)).flatMap({ SocketPacket.PacketType(rawValue: $0) }) else { throw SocketParsableError.invalidPacketType } if !reader.hasNext { return SocketPacket(type: type, nsp: "/") } var namespace = "/" var placeholders = -1 if type == .binaryEvent || type == .binaryAck { if let holders = Int(reader.readUntilOccurence(of: "-")) { placeholders = holders } else { throw SocketParsableError.invalidPacket } } if reader.currentCharacter == "/" { namespace = reader.readUntilOccurence(of: ",") } if !reader.hasNext { return SocketPacket(type: type, nsp: namespace, placeholders: placeholders) } var idString = "" if type == .error { reader.advance(by: -1) } else { while reader.hasNext { if let int = Int(reader.read(count: 1)) { idString += String(int) } else { reader.advance(by: -2) break } } } var dataArray = String(message.utf16[message.utf16.index(reader.currentIndex, offsetBy: 1)..<message.utf16.endIndex])! if type == .error && !dataArray.hasPrefix("[") && !dataArray.hasSuffix("]") { dataArray = "[" + dataArray + "]" } let data = try parseData(dataArray) return SocketPacket(type: type, data: data, id: Int(idString) ?? -1, nsp: namespace, placeholders: placeholders) } // Parses data for events private func parseData(_ data: String) throws -> [Any] { do { return try data.toArray() } catch { throw SocketParsableError.invalidDataArray } } // Parses messages recieved func parseSocketMessage(_ message: String) { guard !message.isEmpty else { return } DefaultSocketLogger.Logger.log("Parsing \(message)", type: "SocketParser") do { let packet = try parseString(message) DefaultSocketLogger.Logger.log("Decoded packet as: \(packet.description)", type: "SocketParser") handlePacket(packet) } catch { DefaultSocketLogger.Logger.error("\(error): \(message)", type: "SocketParser") } } func parseBinaryData(_ data: Data) { guard !waitingPackets.isEmpty else { DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser") return } // Should execute event? guard waitingPackets[waitingPackets.count - 1].addData(data) else { return } let packet = waitingPackets.removeLast() if packet.type != .binaryAck { handleEvent(packet.event, data: packet.args, isInternalMessage: false, withAck: packet.id) } else { handleAck(packet.id, data: packet.args) } } }
apache-2.0
6dcc41b46a9ac41cde3a3bfec0e6e0fb
34.170588
126
0.620672
4.779376
false
false
false
false
ReactiveKit/Bond
Sources/Bond/UIKit/UIPickerView+DataSource.swift
1
6520
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(iOS) import UIKit import ReactiveKit extension SignalProtocol where Element: SectionedDataSourceChangesetConvertible, Error == Never { /// Binds the signal of data source elements to the given picker view. /// /// - parameters: /// - pickerView: A picker view that should display the data from the data source. /// - createTitle: A closure that configures the title for a given picker view row with the given data source at the given index path. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the picker view is deallocated. @discardableResult public func bind(to pickerView: UIPickerView, createTitle: @escaping (Element.Changeset.Collection, Int, Int, UIPickerView) -> String?) -> Disposable { let binder = PickerViewBinderDataSource<Element.Changeset>(createTitle) return bind(to: pickerView, using: binder) } /// Binds the signal of data source elements to the given table view. /// /// - parameters: /// - pickerView: A picker view that should display the data from the data source. /// - binder: A `PickerViewBinderDataSource` or its subclass that will manage the binding. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the picker view is deallocated. @discardableResult public func bind(to pickerView: UIPickerView, using binderDataSource: PickerViewBinderDataSource<Element.Changeset>) -> Disposable { binderDataSource.pickerView = pickerView return bind(to: pickerView) { (_, changeset) in binderDataSource.changeset = changeset.asSectionedDataSourceChangeset } } } extension SignalProtocol where Element: SectionedDataSourceChangesetConvertible, Element.Changeset.Collection: QueryableSectionedDataSourceProtocol, Error == Never { /// Binds the signal of data source elements to the given picker view. /// /// - parameters: /// - pickerView: A picker view that should display the data from the data source. /// - returns: A disposable object that can terminate the binding. Safe to ignore - the binding will be automatically terminated when the picker view is deallocated. @discardableResult public func bind(to pickerView: UIPickerView) -> Disposable { let createTitle: (Element.Changeset.Collection, Int, Int, UIPickerView) -> String? = { (dataSource, row, component, pickerView) in let indexPath = IndexPath(row: row, section: component) let item = dataSource.item(at: indexPath) return String(describing: item) } return bind(to: pickerView, using: PickerViewBinderDataSource<Element.Changeset>(createTitle)) } } private var PickerViewBinderDataSourceAssociationKey = "PickerViewBinderDataSource" public class PickerViewBinderDataSource<Changeset: SectionedDataSourceChangeset>: NSObject, UIPickerViewDataSource, UIPickerViewDelegate { public var createTitle: ((Changeset.Collection, Int, Int, UIPickerView) -> String?)? public var changeset: Changeset? = nil { didSet { pickerView?.reloadAllComponents() } } open weak var pickerView: UIPickerView? = nil { didSet { guard let pickerView = pickerView else { return } associateWithPickerView(pickerView) } } public override init() { self.createTitle = nil } /// - parameter createTitle: A closure that configures the title for a given picker view row with the given data source at the given index path. public init(_ createTitle: @escaping (Changeset.Collection, Int, Int, UIPickerView) -> String?) { self.createTitle = createTitle } public func numberOfComponents(in pickerView: UIPickerView) -> Int { return changeset?.collection.numberOfSections ?? 0 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return changeset?.collection.numberOfItems(inSection: component) ?? 0 } open func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { guard let changeset = changeset else { fatalError() } if let createTitle = createTitle { return createTitle(changeset.collection, row, component, pickerView) } else { fatalError("Subclass of PickerViewBinderDataSource should override and implement pickerView(_:titleForRow:forComponent) method if they do not initialize `createTitle` closure.") } } private func associateWithPickerView(_ pickerView: UIPickerView) { objc_setAssociatedObject(pickerView, &PickerViewBinderDataSourceAssociationKey, self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if pickerView.reactive.hasProtocolProxy(for: UIPickerViewDataSource.self) { pickerView.reactive.dataSource.forwardTo = self } else { pickerView.dataSource = self } if pickerView.reactive.hasProtocolProxy(for: UIPickerViewDelegate.self) { pickerView.reactive.delegate.forwardTo = self } else { pickerView.delegate = self } } } #endif
mit
5e5cf60f7d671b3d6cceac9b330cf9c0
44.915493
189
0.711196
5.162312
false
false
false
false
urdnot-ios/ShepardAppearanceConverter
ShepardAppearanceConverter/ShepardAppearanceConverter/Library/IBIncluded/IBIncludedWrapperViewController.swift
1
8037
// // 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) -> Void /** 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). */ optional func prepareBeforeIBIncludedSegue(segue: UIStoryboardSegue, sender: AnyObject?) /** Check the destination view controller type and share data if it is what you want. */ optional var prepareAfterIBIncludedSegue: PrepareAfterIBIncludedSegueType { get } } //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]() public typealias prepareAfterSegueType = (UIViewController) -> Void 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) } // share post-segue closures for later execution: // skip any navigation/tab controllers let destinationController = activeViewController(segue.destinationViewController) if destinationController == nil { return } 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 { if 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) } // but we don't care what we run our saved prepareAfterIBIncludedSegue closures on: for closure in prepareAfterSegueClosures { closure(viewController) } } /** 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
bd59e51fa7273d2602b46ae2aaefa3db
47.415663
235
0.693542
6.230233
false
false
false
false
HipHipArr/PocketCheck
Cheapify 2.0/ReceiptManager.swift
1
7073
// // ReceiptManager.swift // Cheapify 2.0 // // // Copyright (c) 2015 Hip Hip Array[]. All rights reserved. // import UIKit import Foundation import CoreData var entryMgr: ReceiptManager = ReceiptManager() class Entry: NSObject/*, NSCoding */{ var event = "Name" var category = "Description" var price = "0.00" var tax = "0.00" var tip = "0.00" var date = "Not assigned" init(event: String, category: String, price: String, tax: String, tip: String, date: String){ self.event = event self.category = category self.price = price self.tax = tax self.tip = tip self.date = date } /*func encodeWithCoder(encoder: NSCoder) { encoder.encodeObject(event, forKey: "event") encoder.encodeObject(category, forKey: "category") encoder.encodeObject(price, forKey: "price") encoder.encodeObject(tax, forKey: "tax") encoder.encodeObject(tip, forKey: "tip") encoder.encodeObject(date, forKey: "date") } required init(coder aDecoder: NSCoder) { if let event = aDecoder.decodeObjectForKey("event") as? String{ self.event = event } if let category = aDecoder.decodeObjectForKey("category") as? String{ self.category = category } if let price = aDecoder.decodeObjectForKey("price") as? String{ self.price = price } if let tax = aDecoder.decodeObjectForKey("tax") as? String{ self.tax = tax } if let tip = aDecoder.decodeObjectForKey("tip") as? String{ self.tip = tip } if let date = aDecoder.decodeObjectForKey("date") as? String{ self.date = date } }*/ } class Info: NSObject{ var total = 0.00 var tFood = 0.00 var tTran = 0.00 var tTrav = 0.00 var tEnte = 0.00 var tOthe = 0.00 var tPers = 0.00 var tBusi = 0.00 var budget = 100.00 init(total: Double, tFood: Double, tTran: Double, tTrav: Double, tEnte: Double, tOthe: Double, tPers: Double, tBusi: Double, budget: Double){ self.total = total self.tFood = tFood self.tTran = tTran self.tTrav = tTrav self.tEnte = tEnte self.tOthe = tOthe self.tPers = tPers self.tBusi = tBusi self.budget = budget } } class ReceiptManager: NSObject/*, NSCoding */{ var entries = [NSManagedObject]() var jan = [String]() var feb = [String]() var mar = [String]() var apr = [String]() var may = [String]() var jun = [String]() var jul = [String]() var aug = [String]() var sep = [String]() var oct = [String]() var nov = [String]() var dec = [String]() var tempArr = [NSManagedObject]() var categoryname: String! var moneyinfo = [NSManagedObject]() var total = 0.00 var tFood = 0.00 var tTran = 0.00 var tTrav = 0.00 var tEnte = 0.00 var tOthe = 0.00 var tPers = 0.00 var tBusi = 0.00 var budget = 100.00 /*func encodeWithCoder(encoder: NSCoder) { // encoder.encodeObject(entries, forKey: "entries") encoder.encodeInteger(entries.count, forKey: "count") for index in 0 ..< entries.count { encoder.encodeObject( entries[index] ) } /*encoder.encodeInteger(someInts.count, forKey: "count2") for index in 0 ..< someInts.count { encoder.encodeObject( someInts[index] ) }*/ encoder.encodeObject(total, forKey: "total") encoder.encodeObject(tFood, forKey: "tFood") encoder.encodeObject(tTran, forKey: "tTran") encoder.encodeObject(tTrav, forKey: "tTrav") encoder.encodeObject(tEnte, forKey: "tEnte") encoder.encodeObject(tOthe, forKey: "tOthe") encoder.encodeObject(tPers, forKey: "tPers") encoder.encodeObject(tBusi, forKey: "tBusi") encoder.encodeObject(budget, forKey: "budget") } required init(coder aDecoder: NSCoder) { let nbCounter = aDecoder.decodeIntegerForKey("countKey") for index in 0 ..< nbCounter { if var entry = aDecoder.decodeObject() as? Entry{ entries.append(entry) } } /*let nbCounter2 = aDecoder.decodeIntegerForKey("countKey2") for index in 0 ..< nbCounter2 { if var string = aDecoder.decodeObject() as? String{ someInts.append(string) } }*/ if let total = aDecoder.decodeObjectForKey("total") as? Double{ self.total = total } if let tFood = aDecoder.decodeObjectForKey("tFood") as? Double{ self.tFood = tFood } if let tTran = aDecoder.decodeObjectForKey("tTran") as? Double{ self.tTran = tTran } if let tTrav = aDecoder.decodeObjectForKey("tTrav") as? Double{ self.tTrav = tTrav } if let tEnte = aDecoder.decodeObjectForKey("tEnte") as? Double{ self.tEnte = tEnte } if let tOthe = aDecoder.decodeObjectForKey("tOthe") as? Double{ self.tOthe = tOthe } if let tPers = aDecoder.decodeObjectForKey("tPers") as? Double{ self.tPers = tPers } if let tBusi = aDecoder.decodeObjectForKey("tBusi") as? Double{ self.tBusi = tBusi } if let budget = aDecoder.decodeObjectForKey("budget") as? Double{ self.budget = budget } } override init() { } func addEntry(event: String, category: String, price: String, tax: String, tip: String, date: String){ entries.append(Entry(event: event, category: category, price: price, tax: tax, tip: tip, date: date)) }*/ func saveName(){ //1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! //2 let entity = NSEntityDescription.entityForName("Info", inManagedObjectContext: managedContext) let info = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext) //3 info.setValue(total, forKey: "total") info.setValue(tFood, forKey: "tFood") info.setValue(tTran, forKey: "tTran") info.setValue(tTrav, forKey: "tTrav") info.setValue(tEnte, forKey: "tEnte") info.setValue(tOthe, forKey: "tOthe") info.setValue(tPers, forKey: "tPers") info.setValue(tBusi, forKey: "tBusi") info.setValue(budget, forKey: "budget") //4 var error: NSError? if !managedContext.save(&error) { println("Could not save \(error), \(error?.userInfo)") } //5 moneyinfo.append(info) } }
mit
c984c8821b9db5ae593144cc99bbba3b
28.718487
145
0.568217
4.434483
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAccountPicker/Tests/AccountPickerViewTests.swift
1
4480
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainNamespace import Combine import ComposableArchitecture @testable import FeatureAccountPickerUI import SnapshotTesting import SwiftUI import UIComponentsKit import XCTest class AccountPickerViewTests: XCTestCase { let allIdentifier = UUID() let btcWalletIdentifier = UUID() let btcTradingWalletIdentifier = UUID() let ethWalletIdentifier = UUID() let bchWalletIdentifier = UUID() let bchTradingWalletIdentifier = UUID() lazy var fiatBalances: [AnyHashable: String] = [ allIdentifier: "$2,302.39", btcWalletIdentifier: "$2,302.39", btcTradingWalletIdentifier: "$10,093.13", ethWalletIdentifier: "$807.21", bchWalletIdentifier: "$807.21", bchTradingWalletIdentifier: "$40.30" ] lazy var currencyCodes: [AnyHashable: String] = [ allIdentifier: "USD" ] lazy var cryptoBalances: [AnyHashable: String] = [ btcWalletIdentifier: "0.21204887 BTC", btcTradingWalletIdentifier: "1.38294910 BTC", ethWalletIdentifier: "0.17039384 ETH", bchWalletIdentifier: "0.00388845 BCH", bchTradingWalletIdentifier: "0.00004829 BCH" ] lazy var accountPickerRowList: [AccountPickerRow] = [ .accountGroup( AccountPickerRow.AccountGroup( id: allIdentifier, title: "All Wallets", description: "Total Balance" ) ), .button( AccountPickerRow.Button( id: UUID(), text: "See Balance" ) ), .singleAccount( AccountPickerRow.SingleAccount( id: btcWalletIdentifier, title: "BTC Wallet", description: "Bitcoin" ) ), .singleAccount( AccountPickerRow.SingleAccount( id: btcTradingWalletIdentifier, title: "BTC Trading Wallet", description: "Bitcoin" ) ), .singleAccount( AccountPickerRow.SingleAccount( id: ethWalletIdentifier, title: "ETH Wallet", description: "Ethereum" ) ), .singleAccount( AccountPickerRow.SingleAccount( id: bchWalletIdentifier, title: "BCH Wallet", description: "Bitcoin Cash" ) ), .singleAccount( AccountPickerRow.SingleAccount( id: bchTradingWalletIdentifier, title: "BCH Trading Wallet", description: "Bitcoin Cash" ) ) ] let header = HeaderStyle.normal( title: "Send Crypto Now", subtitle: "Choose a Wallet to send cypto from.", image: ImageAsset.iconSend.image, tableTitle: "Select a Wallet", searchable: false ) override func setUp() { super.setUp() isRecording = false } func testView() { let view = AccountPickerView( store: Store( initialState: AccountPickerState( rows: .loaded(next: .success(Rows(content: accountPickerRowList))), header: .init(headerStyle: header, searchText: nil), fiatBalances: fiatBalances, cryptoBalances: cryptoBalances, currencyCodes: currencyCodes ), reducer: accountPickerReducer, environment: AccountPickerEnvironment( rowSelected: { _ in }, uxSelected: { _ in }, backButtonTapped: {}, closeButtonTapped: {}, search: { _ in }, sections: { .just([]).eraseToAnyPublisher() }, updateSingleAccounts: { _ in .just([:]) }, updateAccountGroups: { _ in .just([:]) }, header: { [unowned self] in .just(header).eraseToAnyPublisher() } ) ), badgeView: { _ in EmptyView() }, iconView: { _ in EmptyView() }, multiBadgeView: { _ in EmptyView() }, withdrawalLocksView: { EmptyView() } ) .app(App.preview) assertSnapshot(matching: view, as: .image(layout: .device(config: .iPhone8))) } }
lgpl-3.0
0b7ada400581250ea39daa7156fc230f
31.456522
87
0.540522
5.389892
false
false
false
false
chrisjmendez/swift-exercises
GUI/TipView/TipView/EasyTipView.swift
1
18506
// // EasyTipView.swift // // Copyright (c) 2015 Teodor Patraş // // 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 public protocol EasyTipViewDelegate : class { func easyTipViewDidDismiss(tipView : EasyTipView) } public class EasyTipView: UIView { // MARK:- Nested types - public enum ArrowPosition { case Top case Bottom } public struct Preferences { public struct Drawing { public var cornerRadius = CGFloat(5) public var arrowHeight = CGFloat(5) public var arrowWidth = CGFloat(10) public var foregroundColor = UIColor.whiteColor() public var backgroundColor = UIColor.redColor() public var arrowPosition = ArrowPosition.Bottom public var textAlignment = NSTextAlignment.Center public var borderWidth = CGFloat(0) public var borderColor = UIColor.clearColor() public var font = UIFont.systemFontOfSize(15) } public struct Positioning { public var bubbleHInset = CGFloat(10) public var bubbleVInset = CGFloat(1) public var textHInset = CGFloat(10) public var textVInset = CGFloat(10) public var maxWidth = CGFloat(200) } public var drawing = Drawing() public var positioning = Positioning() public var hasBorder : Bool { return self.drawing.borderWidth > 0 && self.drawing.borderColor != UIColor.clearColor() } public init() {} } // MARK:- Variables - override public var backgroundColor : UIColor? { didSet { guard let color = backgroundColor where color != UIColor.clearColor() else {return} self.preferences.drawing.backgroundColor = color backgroundColor = UIColor.clearColor() } } override public var description : String { let type = _stdlib_getDemangledTypeName(self).componentsSeparatedByString(".").last! return "<< \(type) with text : '\(self.text)' >>" } private weak var presentingView : UIView? private var arrowTip = CGPointZero private var preferences : Preferences weak var delegate : EasyTipViewDelegate? private let text : NSString // MARK: - Lazy variables - private lazy var textSize : CGSize = { [unowned self] in var attributes : [String : AnyObject] = [NSFontAttributeName : self.preferences.drawing.font] var textSize = self.text.boundingRectWithSize(CGSizeMake(self.preferences.positioning.maxWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil).size textSize.width = ceil(textSize.width) textSize.height = ceil(textSize.height) if textSize.width < self.preferences.drawing.arrowWidth { textSize.width = self.preferences.drawing.arrowWidth } return textSize }() private lazy var contentSize : CGSize = { [unowned self] in var contentSize = CGSizeMake(self.textSize.width + self.preferences.positioning.textHInset * 2 + self.preferences.positioning.bubbleHInset * 2, self.textSize.height + self.preferences.positioning.textVInset * 2 + self.preferences.positioning.bubbleVInset * 2 + self.preferences.drawing.arrowHeight) return contentSize }() // MARK: - Static variables - public static var globalPreferences = Preferences() // MARK:- Initializer - public init (text : NSString, preferences: Preferences = EasyTipView.globalPreferences, delegate : EasyTipViewDelegate? = nil){ self.text = text self.preferences = preferences self.delegate = delegate super.init(frame : CGRectZero) self.backgroundColor = UIColor.clearColor() NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleRotation", name: UIDeviceOrientationDidChangeNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } /** NSCoding not supported. Use init(text, preferences, delegate) instead! */ required public init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported. Use init(text, preferences, delegate) instead!") } // MARK: - Rotation support - func handleRotation () { guard let sview = self.superview where self.presentingView != nil else { return } UIView.animateWithDuration(0.3, animations: { () -> Void in self.arrangeInSuperview(sview) self.setNeedsDisplay() }) } // MARK:- Class functions - public class func showAnimated(animated : Bool = true, forView view : UIView, withinSuperview superview : UIView? = nil, text : NSString, preferences: Preferences = EasyTipView.globalPreferences, delegate : EasyTipViewDelegate? = nil){ let ev = EasyTipView(text: text, preferences : preferences, delegate : delegate) ev.showForView(view, withinSuperview: superview, animated: animated) } public class func showAnimated(animated : Bool = true, forItem item : UIBarButtonItem, withinSuperview superview : UIView? = nil, text : NSString, preferences: Preferences = EasyTipView.globalPreferences, delegate : EasyTipViewDelegate? = nil){ if let view = item.customView { self.showAnimated(animated, forView: view, withinSuperview: superview, text: text, preferences: preferences, delegate: delegate) }else{ if let view = item.valueForKey("view") as? UIView { self.showAnimated(animated, forView: view, withinSuperview: superview, text: text, preferences: preferences, delegate: delegate) } } } // MARK:- Instance methods - public func showForItem(item : UIBarButtonItem, withinSuperView sview : UIView? = nil, animated : Bool = true) { if let view = item.customView { self.showForView(view, withinSuperview: sview, animated : animated) }else{ if let view = item.valueForKey("view") as? UIView { self.showForView(view, withinSuperview: sview, animated: animated) } } } public func showForView(view : UIView, withinSuperview sview : UIView? = nil, animated : Bool = true) { if let v = sview { assert(view.hasSuperview(v), "The supplied superview <\(v)> is not a direct nor an indirect superview of the supplied reference view <\(view)>. The superview passed to this method should be a direct or an indirect superview of the reference view. To display the tooltip on the window, pass nil as the superview parameter.") } let superview = sview ?? UIApplication.sharedApplication().windows.last! self.presentingView = view self.arrangeInSuperview(superview) self.transform = CGAffineTransformMakeScale(0, 0) let tap = UITapGestureRecognizer(target: self, action: "handleTap") self.addGestureRecognizer(tap) superview.addSubview(self) if animated { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.transform = CGAffineTransformIdentity }, completion: nil) }else{ self.transform = CGAffineTransformIdentity } } private func arrangeInSuperview(superview : UIView) { let position = self.preferences.drawing.arrowPosition let refViewOrigin = self.presentingView!.originWithinDistantSuperView(superview) let refViewSize = self.presentingView!.frame.size let refViewCenter = CGPointMake(refViewOrigin.x + refViewSize.width / 2, refViewOrigin.y + refViewSize.height / 2) let xOrigin = refViewCenter.x - self.contentSize.width / 2 let yOrigin = position == .Bottom ? refViewOrigin.y - self.contentSize.height : refViewOrigin.y + refViewSize.height var frame = CGRectMake(xOrigin, yOrigin, self.contentSize.width, self.contentSize.height) if frame.origin.x < 0 { frame.origin.x = 0 } else if CGRectGetMaxX(frame) > CGRectGetWidth(superview.frame){ frame.origin.x = superview.frame.width - CGRectGetWidth(frame) } if position == .Top { if CGRectGetMaxY(frame) > CGRectGetHeight(superview.frame){ self.preferences.drawing.arrowPosition = .Bottom frame.origin.y = refViewOrigin.y - self.contentSize.height } }else{ if CGRectGetMinY(frame) < 0 { self.preferences.drawing.arrowPosition = .Top frame.origin.y = refViewOrigin.y + refViewSize.height } } var arrowTipXOrigin : CGFloat if CGRectGetWidth(frame) < refViewSize.width { arrowTipXOrigin = self.contentSize.width / 2 } else { arrowTipXOrigin = abs(frame.origin.x - refViewOrigin.x) + refViewSize.width / 2 } self.arrowTip = CGPointMake(arrowTipXOrigin, self.preferences.drawing.arrowPosition == .Top ? self.preferences.positioning.bubbleVInset : self.contentSize.height - self.preferences.positioning.bubbleVInset) self.frame = frame } public func dismissWithCompletion(completion : ((finished : Bool) -> Void)?){ UIView.animateWithDuration(0.2, animations: { () -> Void in self.transform = CGAffineTransformMakeScale(0.3, 0.3) self.alpha = 0 }) { (finished) -> Void in completion?(finished: finished) self.removeFromSuperview() } } // MARK:- Callbacks - public func handleTap () { self.dismissWithCompletion { (finished) -> Void in self.delegate?.easyTipViewDidDismiss(self) } } // MARK:- Drawing - private func drawBubble(bubbleFrame : CGRect, arrowPosition : ArrowPosition, context : CGContext) { let arrowWidth = self.preferences.drawing.arrowWidth let arrowHeight = self.preferences.drawing.arrowHeight let cornerRadius = self.preferences.drawing.cornerRadius let contourPath = CGPathCreateMutable() CGPathMoveToPoint(contourPath, nil, self.arrowTip.x, self.arrowTip.y) CGPathAddLineToPoint(contourPath, nil, self.arrowTip.x - arrowWidth / 2, self.arrowTip.y + (arrowPosition == .Bottom ? -1 : 1) * arrowHeight) var method = self.drawBubbleTopShape if arrowPosition == .Bottom { method = self.drawBubbleBottomShape } method(bubbleFrame, cornerRadius : cornerRadius, path : contourPath) CGPathAddLineToPoint(contourPath, nil, self.arrowTip.x + arrowWidth / 2, self.arrowTip.y + (arrowPosition == .Bottom ? -1 : 1) * arrowHeight) CGPathCloseSubpath(contourPath) CGContextAddPath(context, contourPath) CGContextClip(context) self.paintBubble(context) if self.preferences.hasBorder { self.drawBorder(contourPath, context: context) } } private func drawBubbleBottomShape(frame : CGRect, cornerRadius : CGFloat, path : CGMutablePath) { CGPathAddArcToPoint(path, nil, frame.x, frame.y + frame.height, frame.x, frame.y, cornerRadius) CGPathAddArcToPoint(path, nil, frame.x, frame.y, frame.x + frame.width, frame.y, cornerRadius) CGPathAddArcToPoint(path, nil, frame.x + frame.width, frame.y, frame.x + frame.width, frame.y + frame.height, cornerRadius) CGPathAddArcToPoint(path, nil, frame.x + frame.width, frame.y + frame.height, frame.x, frame.y + frame.height, cornerRadius) } private func drawBubbleTopShape(frame : CGRect, cornerRadius : CGFloat, path : CGMutablePath) { CGPathAddArcToPoint(path, nil, frame.x, frame.y, frame.x, frame.y + frame.height, cornerRadius) CGPathAddArcToPoint(path, nil, frame.x, frame.y + frame.height, frame.x + frame.width, frame.y + frame.height, cornerRadius) CGPathAddArcToPoint(path, nil, frame.x + frame.width, frame.y + frame.height, frame.x + frame.width, frame.y, cornerRadius) CGPathAddArcToPoint(path, nil, frame.x + frame.width, frame.y, frame.x, frame.y, cornerRadius) } private func paintBubble(context: CGContext) { CGContextSetFillColorWithColor(context, self.preferences.drawing.backgroundColor.CGColor) CGContextFillRect(context, self.bounds) } private func drawBorder(borderPath: CGPath, context : CGContext) { CGContextAddPath(context, borderPath) CGContextSetStrokeColorWithColor(context, self.preferences.drawing.borderColor.CGColor) CGContextSetLineWidth(context, self.preferences.drawing.borderWidth) CGContextStrokePath(context) } private func drawText(bubbleFrame : CGRect, context : CGContext) { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = self.preferences.drawing.textAlignment paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping let textRect = CGRectMake(bubbleFrame.origin.x + (bubbleFrame.size.width - self.textSize.width) / 2, bubbleFrame.origin.y + (bubbleFrame.size.height - self.textSize.height) / 2, textSize.width, textSize.height) self.text.drawInRect(textRect, withAttributes: [NSFontAttributeName : self.preferences.drawing.font, NSForegroundColorAttributeName : self.preferences.drawing.foregroundColor, NSParagraphStyleAttributeName : paragraphStyle]) } override public func drawRect(rect: CGRect) { let arrowPosition = self.preferences.drawing.arrowPosition let bubbleWidth = self.contentSize.width - 2 * self.preferences.positioning.bubbleHInset let bubbleHeight = self.contentSize.height - 2 * self.preferences.positioning.bubbleVInset - self.preferences.drawing.arrowHeight let bubbleXOrigin = self.preferences.positioning.bubbleHInset let bubbleYOrigin = arrowPosition == .Bottom ? self.preferences.positioning.bubbleVInset : self.preferences.positioning.bubbleVInset + self.preferences.drawing.arrowHeight let bubbleFrame = CGRectMake(bubbleXOrigin, bubbleYOrigin, bubbleWidth, bubbleHeight) let context = UIGraphicsGetCurrentContext()! CGContextSaveGState (context) self.drawBubble(bubbleFrame, arrowPosition: self.preferences.drawing.arrowPosition, context: context) self.drawText(bubbleFrame, context: context) CGContextRestoreGState(context) } } // MARK:- CGRect extension - private extension CGRect { var x : CGFloat { return self.origin.x } var y : CGFloat { return self.origin.y } var width : CGFloat { return self.size.width } var height : CGFloat { return self.size.height } } // MARK:- UIView extension - private extension UIView { func originWithinDistantSuperView (superview : UIView?) -> CGPoint { if self.superview != nil { return viewOriginInSuperview(self.superview!, subviewOrigin: self.frame.origin, refSuperview : superview) }else{ return self.frame.origin } } func hasSuperview (superview : UIView) -> Bool{ return viewHasSuperview(self, superview: superview) } private func viewHasSuperview (view : UIView, superview : UIView) -> Bool { if let sview = view.superview { if sview === superview { return true }else{ return viewHasSuperview(sview, superview: superview) } }else{ return false } } private func viewOriginInSuperview(sview : UIView, subviewOrigin sorigin: CGPoint, refSuperview : UIView?) -> CGPoint { if let superview = sview.superview { if let ref = refSuperview { if sview === ref { return sorigin }else{ return viewOriginInSuperview(superview, subviewOrigin: CGPointMake(sview.frame.origin.x + sorigin.x, sview.frame.origin.y + sorigin.y), refSuperview: ref) } }else{ return viewOriginInSuperview(superview, subviewOrigin: CGPointMake(sview.frame.origin.x + sorigin.x, sview.frame.origin.y + sorigin.y), refSuperview: nil) } }else{ return CGPointMake(sview.frame.origin.x + sorigin.x, sview.frame.origin.y + sorigin.y) } } }
mit
f190e4753a0564eb7fd841917b6916c7
40.493274
335
0.63853
5.203881
false
false
false
false
kclowes/HackingWithSwift
Project5/Project5/MasterViewController.swift
1
4922
// // MasterViewController.swift // Project5 // // Created by Keri Clowes on 3/23/16. // Copyright © 2016 Keri Clowes. All rights reserved. // import UIKit import GameKit class MasterViewController: UITableViewController { var objects = [String]() var allWords = [String]() override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "promptForAnswer") if let startWordsPath = NSBundle.mainBundle().pathForResource("start", ofType: "txt") { if let startWords = try? String(contentsOfFile: startWordsPath, usedEncoding: nil) { allWords = startWords.componentsSeparatedByString("\n") } } else { allWords = ["silkworm"] } startGame() } func promptForAnswer() { let ac = UIAlertController(title: "Enter Answer", message: nil, preferredStyle: .Alert) ac.addTextFieldWithConfigurationHandler(nil) let submitAction = UIAlertAction(title: "Submit", style: .Default) { [unowned self, ac] _ in let answer = ac.textFields![0] self.submitAnswer(answer.text!) } ac.addAction(submitAction) presentViewController(ac, animated: true, completion: nil) } func submitAnswer(answer: String) { let lowerAnswer = answer.lowercaseString let errorTitle: String let errorMessage: String if wordIsNotTheStartingWord(lowerAnswer) { if wordIsLongerThanThreeChars(lowerAnswer) { if wordIsPossible(lowerAnswer) { if wordIsOriginal(lowerAnswer) { if wordIsReal(lowerAnswer) { objects.insert(answer, atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) return } else { errorTitle = "Word Not Recognized" errorMessage = "You can't just make them up, you know!" displayError(errorTitle, errorMessage: errorMessage) } } else { errorTitle = "Duplicate" errorMessage = "You already used that one!" displayError(errorTitle, errorMessage: errorMessage) } } else { errorTitle = "Word Not Possible" errorMessage = "You can't spell that word from '\(title!.lowercaseString)'!" displayError(errorTitle, errorMessage: errorMessage) } } else { errorTitle = "Word Too Short" errorMessage = "Your word needs to be at least 3 characters!" displayError(errorTitle, errorMessage: errorMessage) } } else { errorTitle = "Word Is the Original" errorMessage = "Your word needs to be something other than the original!" displayError(errorTitle, errorMessage: errorMessage) } } func wordIsNotTheStartingWord(answer: String) -> Bool { return answer != title!.lowercaseString } func wordIsLongerThanThreeChars(answer: String) -> Bool { return answer.characters.count > 2 } func displayError(errorTitle: String, errorMessage: String) { let ac = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } func wordIsPossible(answer: String) -> Bool { var tempWord = title!.lowercaseString for letter in answer.characters { if let pos = tempWord.rangeOfString(String(letter)) { tempWord.removeAtIndex(pos.startIndex) } else { return false } } return true } func wordIsOriginal(answer: String) -> Bool { return !objects.contains(answer) } func wordIsReal(answer: String) -> Bool { let checker = UITextChecker() let range = NSMakeRange(0, answer.characters.count) let misspelledRange = checker.rangeOfMisspelledWordInString(answer, range: range, startingAt: 0, wrap: false, language: "en") return misspelledRange.location == NSNotFound } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] cell.textLabel!.text = object return cell } func startGame() { allWords = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(allWords) as! [String] title = allWords[0] objects.removeAll(keepCapacity: true) tableView.reloadData() } }
mit
731f7b90a6e66790742d8dd07b627e48
31.163399
129
0.677911
4.759188
false
false
false
false
stripe/stripe-ios
StripeIdentity/StripeIdentity/Source/IdentityVerificationSheet.swift
1
11696
// // IdentityVerificationSheet.swift // StripeIdentity // // Created by Mel Ludowise on 3/3/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // @_spi(STP) import StripeCore import UIKit /// A drop-in class that presents a sheet for a user to verify their identity. /// This class is in beta; see https://stripe.com/docs/identity for access final public class IdentityVerificationSheet { /// The result of an attempt to finish an identity verification flow @frozen public enum VerificationFlowResult { /// User completed the verification flow case flowCompleted /// User canceled out of the flow or declined to give consent case flowCanceled /// Failed with error case flowFailed(error: Error) } /// Configuration for an IdentityVerificationSheet public struct Configuration { /// An image of your customer-facing business logo. /// /// - Note: The recommended image size is 32 x 32 points. The image will be /// displayed in both light and dark modes, if the app supports it. Use a /// dynamic UIImage to support different images in light vs dark mode. public var brandLogo: UIImage /// Initializes a Configuration. /// - Parameters: /// - brandLogo: An image of your customer-facing business logo. /// The recommended image size is 32 x 32 points. The image will be /// displayed in both light and dark modes, if the app supports it. public init( brandLogo: UIImage ) { self.brandLogo = brandLogo } } /// The client secret of the Stripe VerificationSession object. /// See https://stripe.com/docs/api/identity/verification_sessions public let verificationSessionClientSecret: String // TODO(mludowise|IDPROD-2542): Make non-optional when native component // experience is ready for release. // This is required to be non-null for native experience. let verificationSheetController: VerificationSheetControllerProtocol? /// Initializes a web-based `IdentityVerificationSheet`. /// /// - Parameters: /// - verificationSessionClientSecret: The [client secret](https://stripe.com/docs/api/identity/verification_sessions) of a Stripe VerificationSession object. @available(iOS 14.3, *) public convenience init( verificationSessionClientSecret: String ) { self.init( verificationSessionClientSecret: verificationSessionClientSecret, verificationSheetController: nil, analyticsClient: STPAnalyticsClient.sharedClient ) } /// Initializes an `IdentityVerificationSheet` from native iOS components. /// /// - Note: This initializer and creating an ephemeral key for a /// VerificationSession is available on an invite only basis. Please contact /// [[email protected]](mailto:[email protected]) to learn /// more. /// /// - Parameters: /// - verificationSessionId: The id of a Stripe [VerificationSession](https://stripe.com/docs/api/identity/verification_sessions) object. /// - ephemeralKeySecret: A short-lived token that allows the SDK to access a [VerificationSession](https://stripe.com/docs/api/identity/verification_sessions) object. /// - configuration: Configuration for the `IdentityVerificationSheet` including your brand logo. @available(iOSApplicationExtension, unavailable) @available(macCatalystApplicationExtension, unavailable) public convenience init( verificationSessionId: String, ephemeralKeySecret: String, configuration: Configuration ) { self.init( verificationSessionClientSecret: "", verificationSheetController: VerificationSheetController( apiClient: IdentityAPIClientImpl( verificationSessionId: verificationSessionId, ephemeralKeySecret: ephemeralKeySecret ), flowController: VerificationSheetFlowController( brandLogo: configuration.brandLogo ), mlModelLoader: IdentityMLModelLoader(), analyticsClient: IdentityAnalyticsClient( verificationSessionId: verificationSessionId ) ), analyticsClient: STPAnalyticsClient.sharedClient ) } init( verificationSessionClientSecret: String, verificationSheetController: VerificationSheetControllerProtocol?, analyticsClient: STPAnalyticsClientProtocol ) { self.verificationSessionClientSecret = verificationSessionClientSecret self.clientSecret = VerificationClientSecret(string: verificationSessionClientSecret) self.verificationSheetController = verificationSheetController self.analyticsClient = analyticsClient analyticsClient.addClass(toProductUsageIfNecessary: IdentityVerificationSheet.self) verificationSheetController?.delegate = self } /// Presents a sheet for a customer to verify their identity. /// - Parameters: /// - presentingViewController: The view controller to present the identity verification sheet. /// - completion: Called with the result of the verification session after the identity verification sheet is dismissed. @available(iOSApplicationExtension, unavailable) public func present( from presentingViewController: UIViewController, completion: @escaping (VerificationFlowResult) -> Void ) { verificationSheetController?.analyticsClient.startTrackingTimeToScreen(from: nil) // Overwrite completion closure to retain self until called let completion: (VerificationFlowResult) -> Void = { result in let verificationSessionId = self.clientSecret?.verificationSessionId ?? self.verificationSheetController?.apiClient.verificationSessionId if let verificationSheetController = self.verificationSheetController { verificationSheetController.analyticsClient.logSheetClosedFailedOrCanceled( result: result, sheetController: verificationSheetController ) } else { self.analyticsClient.log( analytic: VerificationSheetCompletionAnalytic.make( verificationSessionId: verificationSessionId, sessionResult: result ), apiClient: .shared ) } completion(result) self.completion = nil } self.completion = completion // Guard against basic user error guard presentingViewController.presentedViewController == nil else { assertionFailure("presentingViewController is already presenting a view controller") let error = IdentityVerificationSheetError.unknown( debugDescription: "presentingViewController is already presenting a view controller" ) completion(.flowFailed(error: error)) return } // Navigation Controller to present let navigationController: UINavigationController // VS id used to log analytics let verificationSessionId: String if let verificationSheetController = verificationSheetController { // Use native UI verificationSessionId = verificationSheetController.apiClient.verificationSessionId navigationController = verificationSheetController.flowController.navigationController verificationSheetController.loadAndUpdateUI() verificationSheetController.analyticsClient.logSheetPresented() } else if #available(iOS 14.3, *) { // Validate client secret guard let clientSecret = clientSecret else { completion(.flowFailed(error: IdentityVerificationSheetError.invalidClientSecret)) return } verificationSessionId = clientSecret.verificationSessionId navigationController = VerificationFlowWebViewController.makeInNavigationController( clientSecret: clientSecret, delegate: self ) analyticsClient.log( analytic: VerificationSheetPresentedAnalytic( verificationSessionId: verificationSessionId ), apiClient: .shared ) } else { assertionFailure( "IdentityVerificationSheet can only be instantiated using a client secret on iOS 14.3 or higher" ) completion( .flowFailed( error: IdentityVerificationSheetError.unknown( debugDescription: "IdentityVerificationSheet can only be instantiated using a client secret on iOS 14.3 or higher" ) ) ) return } presentingViewController.present(navigationController, animated: true) } // MARK: - Private /// Analytics client to use for logging analytics /// TODO(mludowise|IDPROD-2542): Delete when deprecating web experience private let analyticsClient: STPAnalyticsClientProtocol /// Completion block called when the sheet is closed or fails to open private var completion: ((VerificationFlowResult) -> Void)? /// Parsed client secret string private let clientSecret: VerificationClientSecret? // MARK: - Simulator Mocking #if targetEnvironment(simulator) /// When running on the simulator, mocks the camera output for document scanning with these images public static var simulatorDocumentCameraImages: [UIImage] = [] /// When running on the simulator, mocks the camera output for selfie scanning with these images public static var simulatorSelfieCameraImages: [UIImage] = [] #endif // MARK: - API Mocking /// The version of the VerificationPage API used for all API requests. /// Modifying this value will use experimental features that are not guaranteed /// to be production-ready or prevent API requests from being decoded. @_spi(STP) public var verificationPageAPIVersion: Int { get { return verificationSheetController?.apiClient.apiVersion ?? IdentityAPIClientImpl.productionApiVersion } set { verificationSheetController?.apiClient.apiVersion = newValue } } } // MARK: - VerificationFlowWebViewControllerDelegate @available(iOS 14.3, *) @available(iOSApplicationExtension, unavailable) extension IdentityVerificationSheet: VerificationFlowWebViewControllerDelegate { func verificationFlowWebViewController( _ viewController: VerificationFlowWebViewController, didFinish result: VerificationFlowResult ) { completion?(result) } } // MARK: - VerificationSheetControllerDelegate extension IdentityVerificationSheet: VerificationSheetControllerDelegate { func verificationSheetController( _ controller: VerificationSheetControllerProtocol, didFinish result: VerificationFlowResult ) { completion?(result) } } // MARK: - STPAnalyticsProtocol /// :nodoc: @_spi(STP) extension IdentityVerificationSheet: STPAnalyticsProtocol { @_spi(STP) public static var stp_analyticsIdentifier = "IdentityVerificationSheet" }
mit
0f9b07212c360154016fbad2ed6a42a1
40.035088
173
0.670286
6.26406
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Model/RealmModel/ClothingSizeConvert/MenShirtsSizeConvertInfo.swift
1
1571
// // MenShirtsSizeConvertInfo.swift // selluv-ios // // Created by 조백근 on 2016. 12. 8.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // import RealmSwift class MenShirtsSizeConvertInfo: Object { dynamic var std = "" dynamic var kr = "" dynamic var eu = "" dynamic var us = "" dynamic var other = "" public func setupIndexes() { self.std.indexTag = 0 self.kr.indexTag = 1 self.eu.indexTag = 2 self.us.indexTag = 3 self.other.indexTag = 4 } public static func displayNamesByTag() -> [String] { return [SIZE_KR, SIZE_EU, SIZE_US_UK, SIZE_IT] } public static func propertyName(displayName: String) -> String { if displayName == SIZE_KR { return "kr"} else if displayName == SIZE_EU { return "eu"} else if displayName == SIZE_US_UK { return "us"} else if displayName == SIZE_IT { return "other"} return "" } public static func propertyIndex(displayName: String) -> String { if displayName == SIZE_KR { return "0"} else if displayName == SIZE_EU { return "1"} else if displayName == SIZE_US_UK { return "2"} else if displayName == SIZE_IT { return "3"} return "99" } public func sizeValues() -> [String] { return [(self.kr.copy() as! String), (self.eu.copy() as! String), (self.us.copy() as! String), (self.other.copy() as! String)] } override static func primaryKey() -> String? { return "std" } }
mit
29106e41571e9e767eddfbae0f984976
27.4
134
0.574264
3.866337
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/ArticleSurveyTimerController.swift
1
6162
import Foundation protocol ArticleSurveyTimerControllerDelegate: AnyObject { var isInValidSurveyCampaignAndArticleList: Bool { get } var shouldAttemptToShowArticleAsLivingDoc: Bool { get } var shouldShowArticleAsLivingDoc: Bool { get } var userHasSeenSurveyPrompt: Bool { get } var displayDelay: TimeInterval? { get } var livingDocSurveyLinkState: ArticleAsLivingDocSurveyLinkState { get } } // Manages the timer used to display survey announcements on articles final class ArticleSurveyTimerController { private var isInExperimentAndAllowedArticleList: Bool { guard let delegate = delegate else { return false } return delegate.shouldAttemptToShowArticleAsLivingDoc && delegate.isInValidSurveyCampaignAndArticleList } private var isInControlAndAllowedArticleList: Bool { guard let delegate = delegate else { return false } return !delegate.shouldAttemptToShowArticleAsLivingDoc && delegate.isInValidSurveyCampaignAndArticleList } // MARK: - Public Properties var timerFireBlock: (() -> Void)? // MARK: - Private Properties private weak var delegate: ArticleSurveyTimerControllerDelegate? private var timer: Timer? private var timeIntervalRemainingWhenPaused: TimeInterval? private var shouldPauseOnBackground = false private var shouldResumeOnForeground: Bool { return shouldPauseOnBackground } private var didScrollPastLivingDocContentInsertAndStartedTimer: Bool = false // MARK: - Lifecycle init(delegate: ArticleSurveyTimerControllerDelegate) { self.delegate = delegate } // MARK: - Public func articleContentDidLoad() { guard let delegate = delegate, !delegate.userHasSeenSurveyPrompt, isInControlAndAllowedArticleList else { return } startTimer() } func livingDocViewWillAppear(withState state: ArticleViewController.ViewState) { guard let delegate = delegate, state == .loaded, !delegate.userHasSeenSurveyPrompt, timer == nil, isInExperimentAndAllowedArticleList else { return } startTimer() } func livingDocViewWillPush(withState state: ArticleViewController.ViewState) { viewWillDisappear(withState: state) } func viewWillAppear(withState state: ArticleViewController.ViewState) { guard let delegate = delegate, state == .loaded, !delegate.userHasSeenSurveyPrompt, ((isInExperimentAndAllowedArticleList && didScrollPastLivingDocContentInsertAndStartedTimer) || isInControlAndAllowedArticleList) else { return } startTimer() } func userDidScrollPastLivingDocArticleContentInsert(withState state: ArticleViewController.ViewState) { guard let delegate = delegate, state == .loaded, !delegate.userHasSeenSurveyPrompt, isInExperimentAndAllowedArticleList else { return } didScrollPastLivingDocContentInsertAndStartedTimer = true startTimer() } func extendTimer() { guard let delegate = delegate, !delegate.userHasSeenSurveyPrompt, isInExperimentAndAllowedArticleList else { return } pauseTimer() let newTimeInterval = (timeIntervalRemainingWhenPaused ?? 0) + 5 startTimer(withTimeInterval: newTimeInterval) } func viewWillDisappear(withState state: ArticleViewController.ViewState) { // Do not listen for background/foreground notifications to pause and resume survey if this article is not on screen anymore guard let delegate = delegate, state == .loaded, !delegate.userHasSeenSurveyPrompt, (isInControlAndAllowedArticleList || isInExperimentAndAllowedArticleList) else { return } shouldPauseOnBackground = false stopTimer() } func willResignActive(withState state: ArticleViewController.ViewState) { if state == .loaded, shouldPauseOnBackground { pauseTimer() } } func didBecomeActive(withState state: ArticleViewController.ViewState) { if state == .loaded, shouldResumeOnForeground { resumeTimer() } } // MARK: - Timer State Management private func startTimer(withTimeInterval customTimeInterval: TimeInterval? = nil) { guard let displayDelay = delegate?.displayDelay else { return } shouldPauseOnBackground = true let timeInterval = customTimeInterval ?? displayDelay timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false, block: { [weak self] timer in guard let self = self else { return } self.timerFireBlock?() self.stopTimer() self.shouldPauseOnBackground = false }) } private func stopTimer() { timer?.invalidate() timer = nil } private func pauseTimer() { guard timer != nil, shouldPauseOnBackground else { return } timeIntervalRemainingWhenPaused = calculateRemainingTimerTimeInterval() stopTimer() } private func resumeTimer() { guard timer == nil, shouldResumeOnForeground else { return } startTimer(withTimeInterval: timeIntervalRemainingWhenPaused) } /// Calculate remaining TimeInterval (if any) until survey timer fire date private func calculateRemainingTimerTimeInterval() -> TimeInterval? { guard let timer = timer else { return nil } let remainingTime = timer.fireDate.timeIntervalSince(Date()) return remainingTime < 0 ? nil : remainingTime } }
mit
1b9283cca70b4c4a5772865a53222601
29.35468
150
0.63778
6.385492
false
false
false
false
ashfurrow/FunctionalReactiveAwesome
Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/AsObservable.swift
2
1228
// // AsObservable.swift // Rx // // Created by Krunoslav Zaher on 2/27/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class AsObservableSink_<O: ObserverType> : Sink<O>, ObserverType { typealias Element = O.Element override init(observer: O, cancel: Disposable) { super.init(observer: observer, cancel: cancel) } func on(event: Event<Element>) { trySend(observer, event) switch event { case .Error: fallthrough case .Completed: self.dispose() default: break } } } class AsObservable<Element> : Producer<Element> { let source: Observable<Element> init(source: Observable<Element>) { self.source = source } func omega() -> Observable<Element> { return self } func eval() -> Observable<Element> { return source } override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = AsObservableSink_(observer: observer, cancel: cancel) setSink(sink) return source.subscribe(sink) } }
mit
7fc80bd93380b1a37f2036ef6b0aae42
22.634615
145
0.60342
4.308772
false
false
false
false
velvetroom/columbus
Source/View/SettingsMemory/VSettingsMemoryListCell+Factory.swift
1
4837
import UIKit extension VSettingsMemoryListCell { //MARK: internal func factoryViews() { let locationsColour:UIColor = UIColor(white:0, alpha:0.5) let labelOrigin:UILabel = UILabel() labelOrigin.translatesAutoresizingMaskIntoConstraints = false labelOrigin.backgroundColor = UIColor.clear labelOrigin.isUserInteractionEnabled = false labelOrigin.font = UIFont.regular(size:VSettingsMemoryListCell.Constants.locationsFontSize) labelOrigin.textColor = locationsColour self.labelOrigin = labelOrigin let labelDestination:UILabel = UILabel() labelDestination.translatesAutoresizingMaskIntoConstraints = false labelDestination.backgroundColor = UIColor.clear labelDestination.isUserInteractionEnabled = false labelDestination.font = UIFont.regular(size:VSettingsMemoryListCell.Constants.locationsFontSize) labelDestination.textColor = locationsColour self.labelDestination = labelDestination let labelSize:UILabel = UILabel() labelSize.translatesAutoresizingMaskIntoConstraints = false labelSize.backgroundColor = UIColor.clear labelSize.isUserInteractionEnabled = false labelSize.font = UIFont.regular(size:VSettingsMemoryListCell.Constants.fontSize) labelSize.textAlignment = NSTextAlignment.right labelSize.textColor = UIColor(white:0, alpha:0.4) self.labelSize = labelSize let buttonDelete:UIButton = UIButton() buttonDelete.translatesAutoresizingMaskIntoConstraints = false buttonDelete.setTitleColor( UIColor.colourFail, for:UIControlState.normal) buttonDelete.setTitleColor( UIColor.colourBackgroundGray, for:UIControlState.highlighted) buttonDelete.setTitle( String.localizedView(key:"VSettingsMemoryListCell_buttonDelete"), for:UIControlState.normal) buttonDelete.titleLabel!.font = UIFont.medium(size:VSettingsMemoryListCell.Constants.fontSize) buttonDelete.addTarget( self, action:#selector(selectorDelete(sender:)), for:UIControlEvents.touchUpInside) let icon:UIImageView = UIImageView() icon.isUserInteractionEnabled = false icon.translatesAutoresizingMaskIntoConstraints = false icon.clipsToBounds = true icon.contentMode = UIViewContentMode.center icon.image = #imageLiteral(resourceName: "assetPlansRoute") addSubview(icon) addSubview(labelOrigin) addSubview(labelDestination) addSubview(labelSize) addSubview(buttonDelete) NSLayoutConstraint.equalsVertical( view:icon, toView:self) NSLayoutConstraint.leftToLeft( view:icon, toView:self) NSLayoutConstraint.width( view:icon, constant:VSettingsMemoryListCell.Constants.iconWidth) NSLayoutConstraint.topToTop( view:labelOrigin, toView:self) NSLayoutConstraint.height( view:labelOrigin, constant:VSettingsMemoryListCell.Constants.locationsHeight) NSLayoutConstraint.leftToRight( view:labelOrigin, toView:icon) NSLayoutConstraint.rightToLeft( view:labelOrigin, toView:labelSize, constant:VSettingsMemoryListCell.Constants.sizeLeft) NSLayoutConstraint.bottomToBottom( view:labelDestination, toView:self) NSLayoutConstraint.height( view:labelDestination, constant:VSettingsMemoryListCell.Constants.locationsHeight) NSLayoutConstraint.leftToRight( view:labelDestination, toView:icon) NSLayoutConstraint.rightToLeft( view:labelDestination, toView:labelSize, constant:VSettingsMemoryListCell.Constants.sizeLeft) NSLayoutConstraint.equalsVertical( view:labelSize, toView:self) NSLayoutConstraint.rightToLeft( view:labelSize, toView:buttonDelete, constant:VSettingsMemoryListCell.Constants.sizeRight) NSLayoutConstraint.widthGreaterOrEqual( view:labelSize, constant:VSettingsMemoryListCell.Constants.sizeMinWidth) NSLayoutConstraint.equalsVertical( view:buttonDelete, toView:self) NSLayoutConstraint.rightToRight( view:buttonDelete, toView:self) NSLayoutConstraint.width( view:buttonDelete, constant:VSettingsMemoryListCell.Constants.deleteWidth) } }
mit
553441e10fddb80ff2f0499749d25748
37.696
104
0.662394
6.536486
false
false
false
false
qvacua/vimr
NvimView/Sources/NvimView/UiBridge.swift
1
10885
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Commons import Foundation import MessagePack import NvimServerTypes import os import RxPack import RxSwift final class UiBridge { weak var consumer: NvimView? init(uuid: UUID, config: NvimView.Config) { self.uuid = uuid self.usesCustomTabBar = config.usesCustomTabBar self.usesInteractiveZsh = config.useInteractiveZsh self.nvimArgs = config.nvimArgs ?? [] self.cwd = config.cwd if let envDict = config.envDict { self.envDict = envDict self.log.debug("Using ENVs from vimr: \(envDict)") } else { let selfEnv = ProcessInfo.processInfo.environment let shellUrl = URL(fileURLWithPath: selfEnv["SHELL"] ?? "/bin/bash") self.log.debug("Using SHELL: \(shellUrl)") let interactiveMode = shellUrl.lastPathComponent == "zsh" && !config .useInteractiveZsh ? false : true self.envDict = ProcessUtils.envVars(of: shellUrl, usingInteractiveMode: interactiveMode) self.log.debug("Using ENVs from login shell: \(self.envDict)") } self.scheduler = SerialDispatchQueueScheduler( queue: self.queue, internalSerialQueueName: String(reflecting: UiBridge.self) ) self.server.stream .subscribe(onNext: { [weak self] message in self?.handleMessage(msgId: message.msgid, data: message.data) }, onError: { [weak self] error in self?.log.error("There was an error on the local message port server: \(error)") self?.consumer?.ipcBecameInvalid(error) }) .disposed(by: self.disposeBag) } func runLocalServerAndNvim(width: Int, height: Int) -> Completable { self.initialWidth = width self.initialHeight = height return self.server .run(as: self.localServerName) .andThen(Completable.create { completable in self.runLocalServerAndNvimCompletable = completable self.launchNvimUsingLoginShellEnv() // This will be completed in .nvimReady branch of handleMessage() return Disposables.create() }) .timeout(.seconds(timeout), scheduler: self.scheduler) } func deleteCharacters(_ count: Int, andInputEscapedString string: String) -> Completable { guard let strData = string.data(using: .utf8) else { return .empty() } var data = Data(capacity: MemoryLayout<Int>.size + strData.count) var c = count withUnsafeBytes(of: &c) { data.append(contentsOf: $0) } data.append(strData) return self.sendMessage(msgId: .deleteInput, data: data) } func resize(width: Int, height: Int) -> Completable { self.sendMessage(msgId: .resize, data: [width, height].data()) } func notifyReadinessForRpcEvents() -> Completable { self.sendMessage(msgId: .readyForRpcEvents, data: nil) } func focusGained(_ gained: Bool) -> Completable { self.sendMessage(msgId: .focusGained, data: [gained].data()) } func scroll(horizontal: Int, vertical: Int, at position: Position) -> Completable { self.sendMessage( msgId: .scroll, data: [horizontal, vertical, position.row, position.column].data() ) } func quit() -> Completable { self.quit { self.nvimServerProc?.waitUntilExit() self.log.info("NvimServer \(self.uuid) exited successfully.") } } func forceQuit() -> Completable { self.log.fault("Force-exiting NvimServer \(self.uuid).") return self.quit { self.forceExitNvimServer() self.log.fault("NvimServer \(self.uuid) was forcefully exited.") } } func debug() -> Completable { self.sendMessage(msgId: .debug1, data: nil) } private func handleMessage(msgId: Int32, data: Data?) { guard let msg = NvimServerMsgId(rawValue: Int(msgId)) else { return } switch msg { case .serverReady: self .establishNvimConnection() .subscribe(onError: { [weak self] error in self?.consumer?.ipcBecameInvalid(error) }) .disposed(by: self.disposeBag) case .nvimReady: self.runLocalServerAndNvimCompletable?(.completed) self.runLocalServerAndNvimCompletable = nil let isInitErrorPresent = MessagePackUtils .value(from: data, conversion: { $0.boolValue }) ?? false if isInitErrorPresent { self.consumer?.initVimError() } case .resize: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.resize(v) case .clear: self.consumer?.clear() case .setMenu: self.consumer?.updateMenu() case .busyStart: self.consumer?.busyStart() case .busyStop: self.consumer?.busyStop() case .modeChange: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.modeChange(v) case .modeInfoSet: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.modeInfoSet(v) case .bell: self.consumer?.bell() case .visualBell: self.consumer?.visualBell() case .flush: guard let d = data, let v = (try? unpackAll(d)) else { return } self.consumer?.flush(v) case .setTitle: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.setTitle(with: v) case .stop: self.consumer?.stop() case .dirtyStatusChanged: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.setDirty(with: v) case .cwdChanged: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.cwdChanged(v) case .defaultColorsChanged: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.defaultColorsChanged(v) case .colorSchemeChanged: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.colorSchemeChanged(v) case .optionSet: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.optionSet(v) case .autoCommandEvent: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.autoCommandEvent(v) case .event: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.event(v) case .debug1: break case .highlightAttrs: guard let v = MessagePackUtils.value(from: data) else { return } self.consumer?.setAttr(with: v) case .rpcEventSubscribed: self.consumer?.rpcEventSubscribed() case .fatalError: self.consumer?.bridgeHasFatalError(MessagePackUtils.value(from: data)) @unknown default: self.log.error("Unkonwn msg type from NvimServer") } } private func closePorts() -> Completable { self.client .stop() .andThen(self.server.stop()) } private func quit(using body: @escaping () -> Void) -> Completable { self .closePorts() .andThen(Completable.create { completable in body() completable(.completed) return Disposables.create() }) } private func establishNvimConnection() -> Completable { self.client .connect(to: self.remoteServerName) .andThen( self .sendMessage(msgId: .agentReady, data: [self.initialWidth, self.initialHeight].data()) ) } private func sendMessage(msgId: NvimBridgeMsgId, data: Data?) -> Completable { self.client .send(msgid: Int32(msgId.rawValue), data: data, expectsReply: false) .asCompletable() } private func forceExitNvimServer() { self.nvimServerProc?.interrupt() self.nvimServerProc?.terminate() } private func launchNvimUsingLoginShellEnv() { let listenAddress = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("vimr_\(self.uuid).sock") var env = self.envDict env["VIMRUNTIME"] = Bundle.module.url(forResource: "runtime", withExtension: nil)!.path env["NVIM_LISTEN_ADDRESS"] = listenAddress.path self.log.debug("Socket: \(listenAddress.path)") let usesCustomTabBarArg = self.usesCustomTabBar ? "1" : "0" let outPipe = Pipe() let errorPipe = Pipe() let process = Process() process.environment = env process.standardError = errorPipe process.standardOutput = outPipe process.currentDirectoryPath = self.cwd.path // We know that NvimServer is there. process.launchPath = Bundle.module.url(forResource: "NvimServer", withExtension: nil)!.path process .arguments = [self.localServerName, self.remoteServerName, usesCustomTabBarArg] + ["--headless"] + self.nvimArgs self.log.debug( "Launching NvimServer with args: \(String(describing: process.arguments))" ) process.launch() self.nvimServerProc = process } // FIXME: GH-832 private func launchNvimUsingLoginShell() { let nvimCmd = [ // We know that NvimServer is there. Bundle.module.url(forResource: "NvimServer", withExtension: nil)!.path, self.localServerName, self.remoteServerName, self.usesCustomTabBar ? "1" : "0", "--headless", ] + self.nvimArgs let listenAddress = FileManager.default.temporaryDirectory .appendingPathComponent("vimr_\(self.uuid).sock") let nvimEnv = [ // We know that runtime is there. "VIMRUNTIME": Bundle.module.url(forResource: "runtime", withExtension: nil)!.path, "NVIM_LISTEN_ADDRESS": listenAddress.path, ] self.nvimServerProc = ProcessUtils.execProcessViaLoginShell( cmd: nvimCmd.map { "'\($0)'" }.joined(separator: " "), cwd: self.cwd, envs: nvimEnv, interactive: self.interactive(for: ProcessUtils.loginShell()), qos: .userInteractive ) } private func interactive(for shell: URL) -> Bool { if shell.lastPathComponent == "zsh" { return self.usesInteractiveZsh } return true } private let log = OSLog(subsystem: Defs.loggerSubsystem, category: Defs.LoggerCategory.bridge) private let uuid: UUID private let usesCustomTabBar: Bool private let usesInteractiveZsh: Bool private let cwd: URL private let nvimArgs: [String] private let envDict: [String: String] private let server = RxMessagePortServer(queueQos: .userInteractive) private let client = RxMessagePortClient(queueQos: .userInteractive) private var nvimServerProc: Process? private var initialWidth = 40 private var initialHeight = 20 private var runLocalServerAndNvimCompletable: Completable.CompletableObserver? private let scheduler: SerialDispatchQueueScheduler private let queue = DispatchQueue( label: String(reflecting: UiBridge.self), qos: .userInitiated, target: .global(qos: .userInitiated) ) private let disposeBag = DisposeBag() private var localServerName: String { "com.qvacua.NvimView.\(self.uuid)" } private var remoteServerName: String { "com.qvacua.NvimView.NvimServer.\(self.uuid)" } } private let timeout = 5
mit
a1619825ba559720a42accc607e5d885
29.405028
96
0.675792
4.145088
false
false
false
false
everald/JetPack
Sources/UI/ScrollViewController.swift
1
20370
import UIKit @objc(JetPack_ScrollViewController) open class ScrollViewController: ViewController { public typealias ScrollCompletion = (_ cancelled: Bool) -> Void fileprivate lazy var childContainer = View() fileprivate lazy var delegateProxy: DelegateProxy = DelegateProxy(scrollViewController: self) fileprivate var ignoresScrollViewDidScroll = 0 fileprivate var isSettingPrimaryViewControllerInternally = false fileprivate var lastLayoutedScrollViewInsets = UIEdgeInsets.zero fileprivate var lastLayoutedScrollViewInsetsForChildren = UIEdgeInsets.zero fileprivate var lastLayoutedScrollViewSizeForChildren = CGSize.zero fileprivate var lastLayoutedSizeForChildren = CGSize.zero fileprivate var lastLayoutedSize = CGSize.zero fileprivate var reusableChildView: ChildView? fileprivate var scrollCompletion: ScrollCompletion? fileprivate var viewControllersNotYetMovedToParentViewController = [UIViewController]() public fileprivate(set) final var isInScrollingAnimation = false public override init() { super.init() } public required init?(coder: NSCoder) { super.init(coder: coder) automaticallyAdjustsScrollViewInsets = false } fileprivate func childViewForIndex(_ index: Int) -> ChildView? { guard isViewLoaded else { return nil } for subview in childContainer.subviews { guard let childView = subview as? ChildView, childView.index == index else { continue } return childView } return nil } fileprivate func childViewForViewController(_ viewController: UIViewController) -> ChildView? { guard isViewLoaded else { return nil } for subview in childContainer.subviews { guard let childView = subview as? ChildView, childView.viewController === viewController else { continue } return childView } return nil } fileprivate func createScrollView() -> UIScrollView { let child = SpecialScrollView() child.bounces = false child.canCancelContentTouches = true child.delaysContentTouches = true child.delegate = self.delegateProxy child.isPagingEnabled = true child.scrollsToTop = false child.showsHorizontalScrollIndicator = false child.showsVerticalScrollIndicator = false return child } open var currentIndex: CGFloat { let scrollViewWidth = scrollView.bounds.width if isViewLoaded && scrollViewWidth > 0 { return scrollView.contentOffset.left / scrollViewWidth } else if let primaryViewController = primaryViewController, let index = viewControllers.indexOfIdentical(primaryViewController) { return CGFloat(index) } else { return 0 } } open func didEndDecelerating() { // override in subclasses } open func didEndDragging(willDecelerate: Bool) { // override in subclasses } open func didScroll() { // override in subclasses } fileprivate var isInTransition: Bool { return appearState == .willAppear || appearState == .willDisappear || isInScrollingAnimation || scrollView.isTracking || scrollView.isDecelerating } fileprivate func layoutChildContainer() { ignoresScrollViewDidScroll += 1 defer { ignoresScrollViewDidScroll -= 1 } let scrollViewFrame = CGRect(size: view.bounds.size).insetBy(scrollViewInsets) let contentSize = CGSize(width: CGFloat(viewControllers.count) * scrollViewFrame.width, height: scrollViewFrame.height) let contentOffset = scrollView.contentOffset scrollView.frame = scrollViewFrame childContainer.frame = CGRect(size: contentSize) scrollView.contentSize = contentSize scrollView.contentOffset = contentOffset } fileprivate func layoutChildView(_ childView: ChildView) { guard childView.index >= 0 else { return } let containerSize = scrollView.bounds.size var childViewFrame = CGRect() childViewFrame.left = CGFloat(childView.index) * containerSize.width childViewFrame.size = containerSize childView.frame = childViewFrame } fileprivate func layoutChildrenForcingLayoutUpdate(_ forcesLayoutUpdate: Bool) { ignoresScrollViewDidScroll += 1 defer { ignoresScrollViewDidScroll -= 1 } let viewControllers = self.viewControllers let viewSize = view.bounds.size let scrollViewInsets = self.scrollViewInsets var scrollViewSize = self.scrollView.bounds.size var contentOffset: CGPoint let layoutsExistingChildren: Bool let previousScrollViewSize = lastLayoutedScrollViewSizeForChildren if forcesLayoutUpdate || scrollViewSize != previousScrollViewSize || scrollViewInsets != lastLayoutedScrollViewInsetsForChildren || viewSize != lastLayoutedSizeForChildren { lastLayoutedScrollViewInsetsForChildren = scrollViewInsets lastLayoutedSizeForChildren = viewSize layoutChildContainer() scrollViewSize = self.scrollView.bounds.size lastLayoutedScrollViewSizeForChildren = scrollViewSize contentOffset = scrollView.contentOffset var newContentOffset = contentOffset if viewControllers.count > 1 { var closestChildIndex: Int? var closestChildOffset = CGFloat(0) var closestDistanceToHorizontalCenter = CGFloat.greatestFiniteMagnitude if !previousScrollViewSize.isEmpty { let previousHorizontalCenter = contentOffset.left + (previousScrollViewSize.width / 2) for subview in childContainer.subviews { guard let childView = subview as? ChildView, childView.index >= 0 else { continue } let childViewFrame = childView.frame let distanceToHorizontalCenter = min((previousHorizontalCenter - childViewFrame.left).absolute, (previousHorizontalCenter - childViewFrame.right).absolute) guard distanceToHorizontalCenter < closestDistanceToHorizontalCenter else { continue } closestChildIndex = childView.index closestChildOffset = (childViewFrame.left - contentOffset.left) / previousScrollViewSize.width closestDistanceToHorizontalCenter = distanceToHorizontalCenter } } if let closestChildIndex = closestChildIndex { newContentOffset = CGPoint(left: (CGFloat(closestChildIndex) - closestChildOffset) * scrollViewSize.width, top: 0) } else if let primaryViewController = primaryViewController, let index = viewControllers.indexOfIdentical(primaryViewController) { newContentOffset = CGPoint(left: (CGFloat(index) * scrollViewSize.width), top: 0) } } newContentOffset = newContentOffset.coerced(atLeast: scrollView.minimumContentOffset, atMost: scrollView.maximumContentOffset) if newContentOffset != contentOffset { scrollView.contentOffset = newContentOffset contentOffset = newContentOffset } layoutsExistingChildren = true } else { contentOffset = scrollView.contentOffset layoutsExistingChildren = false } let visibleIndexes: CountableRange<Int> if viewControllers.isEmpty || scrollViewSize.isEmpty { visibleIndexes = 0 ..< 0 } else { let floatingIndex = contentOffset.left / scrollViewSize.width visibleIndexes = Int(floatingIndex.rounded(.down)).coerced(in: 0 ... (viewControllers.count - 1)) ..< (Int(floatingIndex.rounded(.up)).coerced(in: 0 ... (viewControllers.count - 1)) + 1) } for subview in childContainer.subviews { guard let childView = subview as? ChildView, !visibleIndexes.contains(childView.index) else { continue } updateChildView(childView, withPreferredAppearState: .willDisappear, animated: false) childView.removeFromSuperview() updateChildView(childView, withPreferredAppearState: .didDisappear, animated: false) childView.index = -1 childView.viewController = nil reusableChildView = childView } for index in visibleIndexes { if let childView = childViewForIndex(index) { if layoutsExistingChildren { layoutChildView(childView) } } else { let viewController = viewControllers[index] let childView = reusableChildView ?? ChildView() childView.index = index childView.viewController = viewController reusableChildView = nil layoutChildView(childView) updateChildView(childView, withPreferredAppearState: .willAppear, animated: false) childContainer.addSubview(childView) updateChildView(childView, withPreferredAppearState: .didAppear, animated: false) } } } open var primaryViewController: UIViewController? { didSet { if isSettingPrimaryViewControllerInternally { return } guard let primaryViewController = primaryViewController else { fatalError("Cannot set primaryViewController to nil") } scrollToViewController(primaryViewController, animated: false) } } open func scrollToViewController(_ viewController: UIViewController, animated: Bool = true, completion: ScrollCompletion? = nil) { guard let index = viewControllers.indexOfIdentical(viewController) else { fatalError("Cannot scroll to view controller \(viewController) which is not a child view controller") } if viewController != primaryViewController { isSettingPrimaryViewControllerInternally = true primaryViewController = viewController isSettingPrimaryViewControllerInternally = false } if isViewLoaded { let previousScrollCompletion = self.scrollCompletion scrollCompletion = completion scrollView.setContentOffset(CGPoint(left: CGFloat(index) * scrollView.bounds.width, top: 0), animated: animated) previousScrollCompletion?(true) } } public fileprivate(set) final lazy var scrollView: UIScrollView = self.createScrollView() public var scrollViewInsets = UIEdgeInsets.zero { didSet { guard scrollViewInsets != oldValue else { return } if isViewLoaded { view.setNeedsLayout() } } } open override var shouldAutomaticallyForwardAppearanceMethods : Bool { return false } fileprivate func updateAppearStateForAllChildrenAnimated(_ animated: Bool) { for subview in childContainer.subviews { guard let childView = subview as? ChildView else { continue } updateChildView(childView, withPreferredAppearState: appearState, animated: animated) } } fileprivate func updateChildView(_ childView: ChildView, withPreferredAppearState preferredAppearState: AppearState, animated: Bool) { guard let viewController = childView.viewController else { return } var targetAppearState = min(preferredAppearState, appearState) if isInTransition && targetAppearState != .didDisappear { switch childView.appearState { case .didDisappear: targetAppearState = .willAppear case .willAppear: return case .didAppear: targetAppearState = .willDisappear case .willDisappear: return } } childView.updateAppearState(targetAppearState, animated: animated) if targetAppearState == .didAppear, let index = viewControllersNotYetMovedToParentViewController.indexOfIdentical(viewController) { viewControllersNotYetMovedToParentViewController.remove(at: index) onMainQueue { // perform one cycle later since the child may not yet have completed the transitions in this cycle if viewController.containmentState == .willMoveToParent { viewController.didMove(toParent: self) } } } } fileprivate func updatePrimaryViewController() { guard isViewLoaded else { return } var mostVisibleViewController: UIViewController? var mostVisibleWidth = CGFloat.leastNormalMagnitude let scrollViewFrame = scrollView.frame for subview in childContainer.subviews { guard let childView = subview as? ChildView else { continue } let childFrameInView = childView.convert(childView.bounds, to: view) let intersection = childFrameInView.intersection(scrollViewFrame) guard !intersection.isNull else { continue } if intersection.width > mostVisibleWidth { mostVisibleViewController = childView.viewController mostVisibleWidth = intersection.width } } guard mostVisibleViewController != primaryViewController else { return } isSettingPrimaryViewControllerInternally = true primaryViewController = mostVisibleViewController isSettingPrimaryViewControllerInternally = false } open var viewControllers = [UIViewController]() { didSet { guard viewControllers != oldValue else { return } ignoresScrollViewDidScroll += 1 defer { ignoresScrollViewDidScroll -= 1 } var removedViewControllers = [UIViewController]() for viewController in oldValue where viewController.parent === self && !viewControllers.containsIdentical(viewController) { viewController.willMove(toParent: nil) childViewForViewController(viewController)?.index = -1 removedViewControllers.append(viewController) viewControllersNotYetMovedToParentViewController.removeFirstIdentical(viewController) } for index in 0 ..< viewControllers.count { let viewController = viewControllers[index] if viewController.parent !== self { addChild(viewController) viewControllersNotYetMovedToParentViewController.append(viewController) } else { childViewForViewController(viewController)?.index = index } } if isViewLoaded { layoutChildrenForcingLayoutUpdate(true) updatePrimaryViewController() } else { if let primaryViewController = primaryViewController, viewControllers.containsIdentical(primaryViewController) { // primaryViewController still valid } else { primaryViewController = viewControllers.first } } for viewController in removedViewControllers { viewController.removeFromParent() } } } open override func viewDidLayoutSubviewsWithAnimation(_ animation: Animation?) { super.viewDidLayoutSubviewsWithAnimation(animation) let bounds = view.bounds let scrollViewInsets = self.scrollViewInsets guard bounds.size != lastLayoutedSize || scrollViewInsets != lastLayoutedScrollViewInsets else { return } lastLayoutedSize = bounds.size lastLayoutedScrollViewInsets = scrollViewInsets layoutChildrenForcingLayoutUpdate(false) updatePrimaryViewController() } open override func viewDidLoad() { super.viewDidLoad() scrollView.addSubview(childContainer) view.addSubview(scrollView) } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateAppearStateForAllChildrenAnimated(animated) } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) updateAppearStateForAllChildrenAnimated(animated) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateAppearStateForAllChildrenAnimated(animated) } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) updateAppearStateForAllChildrenAnimated(animated) } open func willBeginDragging() { // override in subclasses } } private final class DelegateProxy: NSObject { fileprivate unowned let scrollViewController: ScrollViewController fileprivate init(scrollViewController: ScrollViewController) { self.scrollViewController = scrollViewController } } extension DelegateProxy: UIScrollViewDelegate { @objc fileprivate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let scrollViewController = self.scrollViewController scrollViewController.updateAppearStateForAllChildrenAnimated(true) scrollViewController.didEndDecelerating() } @objc fileprivate func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { let scrollViewController = self.scrollViewController scrollViewController.isInScrollingAnimation = false scrollViewController.updateAppearStateForAllChildrenAnimated(true) scrollViewController.updatePrimaryViewController() let scrollCompletion = scrollViewController.scrollCompletion scrollViewController.scrollCompletion = nil // TODO not called when scrolling was not necessary scrollCompletion?(false) } @objc fileprivate func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let scrollViewController = self.scrollViewController scrollViewController.isInScrollingAnimation = false if decelerate { scrollViewController.didEndDragging(willDecelerate: true) } else { onMainQueue { // loop one cycle because UIScrollView did not yet update .tracking scrollViewController.updateAppearStateForAllChildrenAnimated(true) scrollViewController.updatePrimaryViewController() scrollViewController.didEndDragging(willDecelerate: false) } } } @objc fileprivate func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollViewController = self.scrollViewController guard scrollViewController.ignoresScrollViewDidScroll == 0 else { return } scrollViewController.layoutChildrenForcingLayoutUpdate(false) if scrollView.isTracking || scrollView.isDecelerating { scrollViewController.updatePrimaryViewController() } scrollViewController.didScroll() } @objc fileprivate func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { let scrollViewController = self.scrollViewController scrollViewController.isInScrollingAnimation = false let scrollCompletion = scrollViewController.scrollCompletion scrollViewController.scrollCompletion = nil scrollViewController.updateAppearStateForAllChildrenAnimated(true) scrollCompletion?(true) scrollViewController.willBeginDragging() } @objc fileprivate func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { scrollViewController.isInScrollingAnimation = false } } private final class ChildView: View { fileprivate var appearState = ViewController.AppearState.didDisappear fileprivate var index = -1 fileprivate override func layoutSubviews() { super.layoutSubviews() guard let viewControllerView = viewController?.view else { return } let bounds = self.bounds viewControllerView.bounds = CGRect(size: bounds.size) viewControllerView.center = bounds.center } fileprivate func updateAppearState(_ appearState: ViewController.AppearState, animated: Bool) { let oldAppearState = self.appearState guard appearState != oldAppearState else { return } self.appearState = appearState guard let viewController = self.viewController else { return } switch appearState { case .didDisappear: switch oldAppearState { case .didDisappear: break case .willAppear, .didAppear: viewController.beginAppearanceTransition(false, animated: animated) fallthrough case .willDisappear: viewController.view.removeFromSuperview() viewController.endAppearanceTransition() } case .willAppear: switch oldAppearState { case .didAppear, .willAppear: break case .willDisappear, .didDisappear: viewController.beginAppearanceTransition(true, animated: animated) addSubview(viewController.view) if window != nil { layoutIfNeeded() } } case .willDisappear: switch oldAppearState { case .didDisappear, .willDisappear: break case .willAppear, .didAppear: viewController.beginAppearanceTransition(false, animated: animated) } case .didAppear: assert(window != nil) switch oldAppearState { case .didAppear: break case .didDisappear, .willDisappear: viewController.beginAppearanceTransition(true, animated: animated) addSubview(viewController.view) fallthrough case .willAppear: layoutIfNeeded() viewController.endAppearanceTransition() } } } fileprivate var viewController: UIViewController? { didSet { precondition((viewController != nil) != (oldValue != nil)) } } } private class SpecialScrollView: ScrollView { fileprivate override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) { let willBeginAnimation = animated && contentOffset != self.contentOffset super.setContentOffset(contentOffset, animated: animated) if willBeginAnimation, let delegate = delegate as? DelegateProxy { delegate.scrollViewController.isInScrollingAnimation = true } } } private func min(_ a: ViewController.AppearState, _ b: ViewController.AppearState) -> ViewController.AppearState { switch a { case .didAppear: return b case .willAppear: switch b { case .didAppear: return a default: return b } case .willDisappear: switch b { case .didAppear, .willAppear: return a default: return b } case .didDisappear: return a } }
mit
57a23d2f3367454b451aafbba3172d92
25.697248
161
0.767256
4.932203
false
false
false
false
hffmnn/Swiftz
Swiftz/NonEmptyList.swift
1
3444
// // NonEmptyList.swift // swiftz // // Created by Maxwell Swadling on 10/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // /// A list that may not ever be empty. /// /// Traditionally partial operations on regular lists are total with non-empty lilsts. public struct NonEmptyList<A> { public let head : Box<A> public let tail : List<A> public init(_ a : A, _ t : List<A>) { head = Box(a) tail = t } public init?(_ list : List<A>) { switch list.match() { case .Nil: return nil case let .Cons(h, t): self.init(h, t) } } public func toList() -> List<A> { return List(head.value, tail) } } public func head<A>() -> Lens<NonEmptyList<A>, NonEmptyList<A>, A, A> { return Lens { nel in IxStore(nel.head.value) { NonEmptyList($0, nel.tail) } } } public func tail<A>() -> Lens<NonEmptyList<A>, NonEmptyList<A>, List<A>, List<A>> { return Lens { nel in IxStore(nel.tail) { NonEmptyList(nel.head.value, $0) } } } public func ==<A : Equatable>(lhs : NonEmptyList<A>, rhs : NonEmptyList<A>) -> Bool { return (lhs.head.value == rhs.head.value && lhs.tail == rhs.tail) } extension NonEmptyList : ArrayLiteralConvertible { typealias Element = A public init(arrayLiteral s: Element...) { var xs : [A] = [] var g = s.generate() let h: A? = g.next() while let x : A = g.next() { xs.append(x) } var l = List<A>() for x in xs.reverse() { l = List(x, l) } self = NonEmptyList(h!, l) } } public final class NonEmptyListGenerator<A> : K1<A>, GeneratorType { var head: A? var l: List<A>? public func next() -> A? { if let h = head { head = nil return h } else { var r = l?.head() l = self.l?.tail() return r } } public init(_ l : NonEmptyList<A>) { head = l.head.value self.l = l.tail } } extension NonEmptyList : SequenceType { public func generate() -> NonEmptyListGenerator<A> { return NonEmptyListGenerator(self) } } extension NonEmptyList : Printable { public var description : String { var x = ", ".join(self.fmap({ "\($0)" })) return "[\(x)]" } } extension NonEmptyList : Functor { typealias B = Any typealias FB = NonEmptyList<B> public func fmap<B>(f : (A -> B)) -> NonEmptyList<B> { return NonEmptyList<B>(f(self.head.value), self.tail.fmap(f)) } } extension NonEmptyList : Pointed { public static func pure(x : A) -> NonEmptyList<A> { return NonEmptyList(x, List()) } } extension NonEmptyList : Applicative { typealias FA = NonEmptyList<A> typealias FAB = NonEmptyList<A -> B> public func ap<B>(f : NonEmptyList<A -> B>) -> NonEmptyList<B> { return f.bind({ f in self.bind({ x in NonEmptyList<B>.pure(f(x)) }) }) } } extension NonEmptyList : Monad { public func bind<B>(f : A -> NonEmptyList<B>) -> NonEmptyList<B> { let nh = f(self.head.value) return NonEmptyList<B>(nh.head.value, nh.tail + self.tail.bind { t in f(t).toList() }) } } extension NonEmptyList : Copointed { public func extract() -> A { return self.head.value } } extension NonEmptyList : Comonad { typealias FFA = NonEmptyList<NonEmptyList<A>> public func duplicate() -> NonEmptyList<NonEmptyList<A>> { switch NonEmptyList(self.tail) { case .None: return NonEmptyList<NonEmptyList<A>>(self, []) case let .Some(x): return NonEmptyList<NonEmptyList<A>>(self, x.duplicate().toList()) } } public func extend<B>(fab : NonEmptyList<A> -> B) -> NonEmptyList<B> { return self.duplicate().fmap(fab) } }
bsd-3-clause
3e0cdc62ef35f390855ba4f6fc5d1748
22.114094
88
0.640244
2.984402
false
false
false
false
apple/swift
stdlib/public/core/FloatingPoint.swift
4
79230
//===--- FloatingPoint.swift ----------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A floating-point numeric type. /// /// Floating-point types are used to represent fractional numbers, like 5.5, /// 100.0, or 3.14159274. Each floating-point type has its own possible range /// and precision. The floating-point types in the standard library are /// `Float`, `Double`, and `Float80` where available. /// /// Create new instances of floating-point types using integer or /// floating-point literals. For example: /// /// let temperature = 33.2 /// let recordHigh = 37.5 /// /// The `FloatingPoint` protocol declares common arithmetic operations, so you /// can write functions and algorithms that work on any floating-point type. /// The following example declares a function that calculates the length of /// the hypotenuse of a right triangle given its two perpendicular sides. /// Because the `hypotenuse(_:_:)` function uses a generic parameter /// constrained to the `FloatingPoint` protocol, you can call it using any /// floating-point type. /// /// func hypotenuse<T: FloatingPoint>(_ a: T, _ b: T) -> T { /// return (a * a + b * b).squareRoot() /// } /// /// let (dx, dy) = (3.0, 4.0) /// let distance = hypotenuse(dx, dy) /// // distance == 5.0 /// /// Floating-point values are represented as a *sign* and a *magnitude*, where /// the magnitude is calculated using the type's *radix* and the instance's /// *significand* and *exponent*. This magnitude calculation takes the /// following form for a floating-point value `x` of type `F`, where `**` is /// exponentiation: /// /// x.significand * (F.radix ** x.exponent) /// /// Here's an example of the number -8.5 represented as an instance of the /// `Double` type, which defines a radix of 2. /// /// let y = -8.5 /// // y.sign == .minus /// // y.significand == 1.0625 /// // y.exponent == 3 /// /// let magnitude = 1.0625 * Double(2 ** 3) /// // magnitude == 8.5 /// /// Types that conform to the `FloatingPoint` protocol provide most basic /// (clause 5) operations of the [IEEE 754 specification][spec]. The base, /// precision, and exponent range are not fixed in any way by this protocol, /// but it enforces the basic requirements of any IEEE 754 floating-point /// type. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// Additional Considerations /// ========================= /// /// In addition to representing specific numbers, floating-point types also /// have special values for working with overflow and nonnumeric results of /// calculation. /// /// Infinity /// -------- /// /// Any value whose magnitude is so great that it would round to a value /// outside the range of representable numbers is rounded to *infinity*. For a /// type `F`, positive and negative infinity are represented as `F.infinity` /// and `-F.infinity`, respectively. Positive infinity compares greater than /// every finite value and negative infinity, while negative infinity compares /// less than every finite value and positive infinity. Infinite values with /// the same sign are equal to each other. /// /// let values: [Double] = [10.0, 25.0, -10.0, .infinity, -.infinity] /// print(values.sorted()) /// // Prints "[-inf, -10.0, 10.0, 25.0, inf]" /// /// Operations with infinite values follow real arithmetic as much as possible: /// Adding or subtracting a finite value, or multiplying or dividing infinity /// by a nonzero finite value, results in infinity. /// /// NaN ("not a number") /// -------------------- /// /// Floating-point types represent values that are neither finite numbers nor /// infinity as NaN, an abbreviation for "not a number." Comparing a NaN with /// any value, including another NaN, results in `false`. /// /// let myNaN = Double.nan /// print(myNaN > 0) /// // Prints "false" /// print(myNaN < 0) /// // Prints "false" /// print(myNaN == .nan) /// // Prints "false" /// /// Because testing whether one NaN is equal to another NaN results in `false`, /// use the `isNaN` property to test whether a value is NaN. /// /// print(myNaN.isNaN) /// // Prints "true" /// /// NaN propagates through many arithmetic operations. When you are operating /// on many values, this behavior is valuable because operations on NaN simply /// forward the value and don't cause runtime errors. The following example /// shows how NaN values operate in different contexts. /// /// Imagine you have a set of temperature data for which you need to report /// some general statistics: the total number of observations, the number of /// valid observations, and the average temperature. First, a set of /// observations in Celsius is parsed from strings to `Double` values: /// /// let temperatureData = ["21.5", "19.25", "27", "no data", "28.25", "no data", "23"] /// let tempsCelsius = temperatureData.map { Double($0) ?? .nan } /// print(tempsCelsius) /// // Prints "[21.5, 19.25, 27, nan, 28.25, nan, 23.0]" /// /// /// Note that some elements in the `temperatureData ` array are not valid /// numbers. When these invalid strings are parsed by the `Double` failable /// initializer, the example uses the nil-coalescing operator (`??`) to /// provide NaN as a fallback value. /// /// Next, the observations in Celsius are converted to Fahrenheit: /// /// let tempsFahrenheit = tempsCelsius.map { $0 * 1.8 + 32 } /// print(tempsFahrenheit) /// // Prints "[70.7, 66.65, 80.6, nan, 82.85, nan, 73.4]" /// /// The NaN values in the `tempsCelsius` array are propagated through the /// conversion and remain NaN in `tempsFahrenheit`. /// /// Because calculating the average of the observations involves combining /// every value of the `tempsFahrenheit` array, any NaN values cause the /// result to also be NaN, as seen in this example: /// /// let badAverage = tempsFahrenheit.reduce(0.0, +) / Double(tempsFahrenheit.count) /// // badAverage.isNaN == true /// /// Instead, when you need an operation to have a specific numeric result, /// filter out any NaN values using the `isNaN` property. /// /// let validTemps = tempsFahrenheit.filter { !$0.isNaN } /// let average = validTemps.reduce(0.0, +) / Double(validTemps.count) /// /// Finally, report the average temperature and observation counts: /// /// print("Average: \(average)°F in \(validTemps.count) " + /// "out of \(tempsFahrenheit.count) observations.") /// // Prints "Average: 74.84°F in 5 out of 7 observations." public protocol FloatingPoint: SignedNumeric, Strideable, Hashable where Magnitude == Self { /// A type that can represent any written exponent. associatedtype Exponent: SignedInteger /// Creates a new value from the given sign, exponent, and significand. /// /// The following example uses this initializer to create a new `Double` /// instance. `Double` is a binary floating-point type that has a radix of /// `2`. /// /// let x = Double(sign: .plus, exponent: -2, significand: 1.5) /// // x == 0.375 /// /// This initializer is equivalent to the following calculation, where `**` /// is exponentiation, computed as if by a single, correctly rounded, /// floating-point operation: /// /// let sign: FloatingPointSign = .plus /// let exponent = -2 /// let significand = 1.5 /// let y = (sign == .minus ? -1 : 1) * significand * Double.radix ** exponent /// // y == 0.375 /// /// As with any basic operation, if this value is outside the representable /// range of the type, overflow or underflow occurs, and zero, a subnormal /// value, or infinity may result. In addition, there are two other edge /// cases: /// /// - If the value you pass to `significand` is zero or infinite, the result /// is zero or infinite, regardless of the value of `exponent`. /// - If the value you pass to `significand` is NaN, the result is NaN. /// /// For any floating-point value `x` of type `F`, the result of the following /// is equal to `x`, with the distinction that the result is canonicalized /// if `x` is in a noncanonical encoding: /// /// let x0 = F(sign: x.sign, exponent: x.exponent, significand: x.significand) /// /// This initializer implements the `scaleB` operation defined by the [IEEE /// 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - sign: The sign to use for the new value. /// - exponent: The new value's exponent. /// - significand: The new value's significand. init(sign: FloatingPointSign, exponent: Exponent, significand: Self) /// Creates a new floating-point value using the sign of one value and the /// magnitude of another. /// /// The following example uses this initializer to create a new `Double` /// instance with the sign of `a` and the magnitude of `b`: /// /// let a = -21.5 /// let b = 305.15 /// let c = Double(signOf: a, magnitudeOf: b) /// print(c) /// // Prints "-305.15" /// /// This initializer implements the IEEE 754 `copysign` operation. /// /// - Parameters: /// - signOf: A value from which to use the sign. The result of the /// initializer has the same sign as `signOf`. /// - magnitudeOf: A value from which to use the magnitude. The result of /// the initializer has the same magnitude as `magnitudeOf`. init(signOf: Self, magnitudeOf: Self) /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. init(_ value: Int) /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. init<Source: BinaryInteger>(_ value: Source) /// Creates a new value, if the given integer can be represented exactly. /// /// If the given integer cannot be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to convert to a floating-point value. init?<Source: BinaryInteger>(exactly value: Source) /// The radix, or base of exponentiation, for a floating-point type. /// /// The magnitude of a floating-point value `x` of type `F` can be calculated /// by using the following formula, where `**` is exponentiation: /// /// x.significand * (F.radix ** x.exponent) /// /// A conforming type may use any integer radix, but values other than 2 (for /// binary floating-point types) or 10 (for decimal floating-point types) /// are extraordinarily rare in practice. static var radix: Int { get } /// A quiet NaN ("not a number"). /// /// A NaN compares not equal, not greater than, and not less than every /// value, including itself. Passing a NaN to an operation generally results /// in NaN. /// /// let x = 1.21 /// // x > Double.nan == false /// // x < Double.nan == false /// // x == Double.nan == false /// /// Because a NaN always compares not equal to itself, to test whether a /// floating-point value is NaN, use its `isNaN` property instead of the /// equal-to operator (`==`). In the following example, `y` is NaN. /// /// let y = x + Double.nan /// print(y == Double.nan) /// // Prints "false" /// print(y.isNaN) /// // Prints "true" static var nan: Self { get } /// A signaling NaN ("not a number"). /// /// The default IEEE 754 behavior of operations involving a signaling NaN is /// to raise the Invalid flag in the floating-point environment and return a /// quiet NaN. /// /// Operations on types conforming to the `FloatingPoint` protocol should /// support this behavior, but they might also support other options. For /// example, it would be reasonable to implement alternative operations in /// which operating on a signaling NaN triggers a runtime error or results /// in a diagnostic for debugging purposes. Types that implement alternative /// behaviors for a signaling NaN must document the departure. /// /// Other than these signaling operations, a signaling NaN behaves in the /// same manner as a quiet NaN. static var signalingNaN: Self { get } /// Positive infinity. /// /// Infinity compares greater than all finite numbers and equal to other /// infinite values. /// /// let x = Double.greatestFiniteMagnitude /// let y = x * 2 /// // y == Double.infinity /// // y > x static var infinity: Self { get } /// The greatest finite number representable by this type. /// /// This value compares greater than or equal to all finite numbers, but less /// than `infinity`. /// /// This value corresponds to type-specific C macros such as `FLT_MAX` and /// `DBL_MAX`. The naming of those macros is slightly misleading, because /// `infinity` is greater than this value. static var greatestFiniteMagnitude: Self { get } /// The mathematical constant pi (π), approximately equal to 3.14159. /// /// When measuring an angle in radians, π is equivalent to a half-turn. /// /// This value is rounded toward zero to keep user computations with angles /// from inadvertently ending up in the wrong quadrant. A type that conforms /// to the `FloatingPoint` protocol provides the value for `pi` at its best /// possible precision. /// /// print(Double.pi) /// // Prints "3.14159265358979" static var pi: Self { get } // NOTE: Rationale for "ulp" instead of "epsilon": // We do not use that name because it is ambiguous at best and misleading // at worst: // // - Historically several definitions of "machine epsilon" have commonly // been used, which differ by up to a factor of two or so. By contrast // "ulp" is a term with a specific unambiguous definition. // // - Some languages have used "epsilon" to refer to wildly different values, // such as `leastNonzeroMagnitude`. // // - Inexperienced users often believe that "epsilon" should be used as a // tolerance for floating-point comparisons, because of the name. It is // nearly always the wrong value to use for this purpose. /// The unit in the last place of this value. /// /// This is the unit of the least significant digit in this value's /// significand. For most numbers `x`, this is the difference between `x` /// and the next greater (in magnitude) representable number. There are some /// edge cases to be aware of: /// /// - If `x` is not a finite number, then `x.ulp` is NaN. /// - If `x` is very small in magnitude, then `x.ulp` may be a subnormal /// number. If a type does not support subnormals, `x.ulp` may be rounded /// to zero. /// - `greatestFiniteMagnitude.ulp` is a finite number, even though the next /// greater representable value is `infinity`. /// /// See also the `ulpOfOne` static property. var ulp: Self { get } /// The unit in the last place of 1.0. /// /// The positive difference between 1.0 and the next greater representable /// number. `ulpOfOne` corresponds to the value represented by the C macros /// `FLT_EPSILON`, `DBL_EPSILON`, etc, and is sometimes called *epsilon* or /// *machine epsilon*. Swift deliberately avoids using the term "epsilon" /// because: /// /// - Historically "epsilon" has been used to refer to several different /// concepts in different languages, leading to confusion and bugs. /// /// - The name "epsilon" suggests that this quantity is a good tolerance to /// choose for approximate comparisons, but it is almost always unsuitable /// for that purpose. /// /// See also the `ulp` member property. static var ulpOfOne: Self { get } /// The least positive normal number. /// /// This value compares less than or equal to all positive normal numbers. /// There may be smaller positive numbers, but they are *subnormal*, meaning /// that they are represented with less precision than normal numbers. /// /// This value corresponds to type-specific C macros such as `FLT_MIN` and /// `DBL_MIN`. The naming of those macros is slightly misleading, because /// subnormals, zeros, and negative numbers are smaller than this value. static var leastNormalMagnitude: Self { get } /// The least positive number. /// /// This value compares less than or equal to all positive numbers, but /// greater than zero. If the type supports subnormal values, /// `leastNonzeroMagnitude` is smaller than `leastNormalMagnitude`; /// otherwise they are equal. static var leastNonzeroMagnitude: Self { get } /// The sign of the floating-point value. /// /// The `sign` property is `.minus` if the value's signbit is set, and /// `.plus` otherwise. For example: /// /// let x = -33.375 /// // x.sign == .minus /// /// Don't use this property to check whether a floating point value is /// negative. For a value `x`, the comparison `x.sign == .minus` is not /// necessarily the same as `x < 0`. In particular, `x.sign == .minus` if /// `x` is -0, and while `x < 0` is always `false` if `x` is NaN, `x.sign` /// could be either `.plus` or `.minus`. var sign: FloatingPointSign { get } /// The exponent of the floating-point value. /// /// The *exponent* of a floating-point value is the integer part of the /// logarithm of the value's magnitude. For a value `x` of a floating-point /// type `F`, the magnitude can be calculated as the following, where `**` /// is exponentiation: /// /// x.significand * (F.radix ** x.exponent) /// /// In the next example, `y` has a value of `21.5`, which is encoded as /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. /// /// let y: Double = 21.5 /// // y.significand == 1.34375 /// // y.exponent == 4 /// // Double.radix == 2 /// /// The `exponent` property has the following edge cases: /// /// - If `x` is zero, then `x.exponent` is `Int.min`. /// - If `x` is +/-infinity or NaN, then `x.exponent` is `Int.max` /// /// This property implements the `logB` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var exponent: Exponent { get } /// The significand of the floating-point value. /// /// The magnitude of a floating-point value `x` of type `F` can be calculated /// by using the following formula, where `**` is exponentiation: /// /// x.significand * (F.radix ** x.exponent) /// /// In the next example, `y` has a value of `21.5`, which is encoded as /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. /// /// let y: Double = 21.5 /// // y.significand == 1.34375 /// // y.exponent == 4 /// // Double.radix == 2 /// /// If a type's radix is 2, then for finite nonzero numbers, the significand /// is in the range `1.0 ..< 2.0`. For other values of `x`, `x.significand` /// is defined as follows: /// /// - If `x` is zero, then `x.significand` is 0.0. /// - If `x` is infinite, then `x.significand` is infinity. /// - If `x` is NaN, then `x.significand` is NaN. /// - Note: The significand is frequently also called the *mantissa*, but /// significand is the preferred terminology in the [IEEE 754 /// specification][spec], to allay confusion with the use of mantissa for /// the fractional part of a logarithm. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var significand: Self { get } /// Adds two values and produces their sum, rounded to a /// representable value. /// /// The addition operator (`+`) calculates the sum of its two arguments. For /// example: /// /// let x = 1.5 /// let y = x + 2.25 /// // y == 3.75 /// /// The `+` operator implements the addition operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +(lhs: Self, rhs: Self) -> Self /// Adds two values and stores the result in the left-hand-side variable, /// rounded to a representable value. /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +=(lhs: inout Self, rhs: Self) /// Calculates the additive inverse of a value. /// /// The unary minus operator (prefix `-`) calculates the negation of its /// operand. The result is always exact. /// /// let x = 21.5 /// let y = -x /// // y == -21.5 /// /// - Parameter operand: The value to negate. override static prefix func - (_ operand: Self) -> Self /// Replaces this value with its additive inverse. /// /// The result is always exact. This example uses the `negate()` method to /// negate the value of the variable `x`: /// /// var x = 21.5 /// x.negate() /// // x == -21.5 override mutating func negate() /// Subtracts one value from another and produces their difference, rounded /// to a representable value. /// /// The subtraction operator (`-`) calculates the difference of its two /// arguments. For example: /// /// let x = 7.5 /// let y = x - 2.25 /// // y == 5.25 /// /// The `-` operator implements the subtraction operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -(lhs: Self, rhs: Self) -> Self /// Subtracts the second value from the first and stores the difference in /// the left-hand-side variable, rounding to a representable value. /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -=(lhs: inout Self, rhs: Self) /// Multiplies two values and produces their product, rounding to a /// representable value. /// /// The multiplication operator (`*`) calculates the product of its two /// arguments. For example: /// /// let x = 7.5 /// let y = x * 2.25 /// // y == 16.875 /// /// The `*` operator implements the multiplication operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *(lhs: Self, rhs: Self) -> Self /// Multiplies two values and stores the result in the left-hand-side /// variable, rounding to a representable value. /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *=(lhs: inout Self, rhs: Self) /// Returns the quotient of dividing the first value by the second, rounded /// to a representable value. /// /// The division operator (`/`) calculates the quotient of the division if /// `rhs` is nonzero. If `rhs` is zero, the result of the division is /// infinity, with the sign of the result matching the sign of `lhs`. /// /// let x = 16.875 /// let y = x / 2.25 /// // y == 7.5 /// /// let z = x / 0 /// // z.isInfinite == true /// /// The `/` operator implements the division operation defined by the [IEEE /// 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. static func /(lhs: Self, rhs: Self) -> Self /// Divides the first value by the second and stores the quotient in the /// left-hand-side variable, rounding to a representable value. /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. static func /=(lhs: inout Self, rhs: Self) /// Returns the remainder of this value divided by the given value. /// /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is /// chosen to be even. Note that `q` is *not* `x / y` computed in /// floating-point arithmetic, and that `q` may not be representable in any /// available integer type. /// /// The following example calculates the remainder of dividing 8.625 by 0.75: /// /// let x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.toNearestOrEven) /// // q == 12.0 /// let r = x.remainder(dividingBy: 0.75) /// // r == -0.375 /// /// let x1 = 0.75 * q + r /// // x1 == 8.625 /// /// If this value and `other` are finite numbers, the remainder is in the /// closed range `-abs(other / 2)...abs(other / 2)`. The /// `remainder(dividingBy:)` method is always exact. This method implements /// the remainder operation defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to use when dividing this value. /// - Returns: The remainder of this value divided by `other`. func remainder(dividingBy other: Self) -> Self /// Replaces this value with the remainder of itself divided by the given /// value. /// /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is /// chosen to be even. Note that `q` is *not* `x / y` computed in /// floating-point arithmetic, and that `q` may not be representable in any /// available integer type. /// /// The following example calculates the remainder of dividing 8.625 by 0.75: /// /// var x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.toNearestOrEven) /// // q == 12.0 /// x.formRemainder(dividingBy: 0.75) /// // x == -0.375 /// /// let x1 = 0.75 * q + x /// // x1 == 8.625 /// /// If this value and `other` are finite numbers, the remainder is in the /// closed range `-abs(other / 2)...abs(other / 2)`. The /// `formRemainder(dividingBy:)` method is always exact. /// /// - Parameter other: The value to use when dividing this value. mutating func formRemainder(dividingBy other: Self) /// Returns the remainder of this value divided by the given value using /// truncating division. /// /// Performing truncating division with floating-point values results in a /// truncated integer quotient and a remainder. For values `x` and `y` and /// their truncated integer quotient `q`, the remainder `r` satisfies /// `x == y * q + r`. /// /// The following example calculates the truncating remainder of dividing /// 8.625 by 0.75: /// /// let x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.towardZero) /// // q == 11.0 /// let r = x.truncatingRemainder(dividingBy: 0.75) /// // r == 0.375 /// /// let x1 = 0.75 * q + r /// // x1 == 8.625 /// /// If this value and `other` are both finite numbers, the truncating /// remainder has the same sign as this value and is strictly smaller in /// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method /// is always exact. /// /// - Parameter other: The value to use when dividing this value. /// - Returns: The remainder of this value divided by `other` using /// truncating division. func truncatingRemainder(dividingBy other: Self) -> Self /// Replaces this value with the remainder of itself divided by the given /// value using truncating division. /// /// Performing truncating division with floating-point values results in a /// truncated integer quotient and a remainder. For values `x` and `y` and /// their truncated integer quotient `q`, the remainder `r` satisfies /// `x == y * q + r`. /// /// The following example calculates the truncating remainder of dividing /// 8.625 by 0.75: /// /// var x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.towardZero) /// // q == 11.0 /// x.formTruncatingRemainder(dividingBy: 0.75) /// // x == 0.375 /// /// let x1 = 0.75 * q + x /// // x1 == 8.625 /// /// If this value and `other` are both finite numbers, the truncating /// remainder has the same sign as this value and is strictly smaller in /// magnitude than `other`. The `formTruncatingRemainder(dividingBy:)` /// method is always exact. /// /// - Parameter other: The value to use when dividing this value. mutating func formTruncatingRemainder(dividingBy other: Self) /// Returns the square root of the value, rounded to a representable value. /// /// The following example declares a function that calculates the length of /// the hypotenuse of a right triangle given its two perpendicular sides. /// /// func hypotenuse(_ a: Double, _ b: Double) -> Double { /// return (a * a + b * b).squareRoot() /// } /// /// let (dx, dy) = (3.0, 4.0) /// let distance = hypotenuse(dx, dy) /// // distance == 5.0 /// /// - Returns: The square root of the value. func squareRoot() -> Self /// Replaces this value with its square root, rounded to a representable /// value. mutating func formSquareRoot() /// Returns the result of adding the product of the two given values to this /// value, computed without intermediate rounding. /// /// This method is equivalent to the C `fma` function and implements the /// `fusedMultiplyAdd` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: One of the values to multiply before adding to this value. /// - rhs: The other value to multiply. /// - Returns: The product of `lhs` and `rhs`, added to this value. func addingProduct(_ lhs: Self, _ rhs: Self) -> Self /// Adds the product of the two given values to this value in place, computed /// without intermediate rounding. /// /// - Parameters: /// - lhs: One of the values to multiply before adding to this value. /// - rhs: The other value to multiply. mutating func addProduct(_ lhs: Self, _ rhs: Self) /// Returns the lesser of the two given values. /// /// This method returns the minimum of two values, preserving order and /// eliminating NaN when possible. For two values `x` and `y`, the result of /// `minimum(x, y)` is `x` if `x <= y`, `y` if `y < x`, or whichever of `x` /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. /// /// Double.minimum(10.0, -25.0) /// // -25.0 /// Double.minimum(10.0, .nan) /// // 10.0 /// Double.minimum(.nan, -25.0) /// // -25.0 /// Double.minimum(.nan, .nan) /// // nan /// /// The `minimum` method implements the `minNum` operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: The minimum of `x` and `y`, or whichever is a number if the /// other is NaN. static func minimum(_ x: Self, _ y: Self) -> Self /// Returns the greater of the two given values. /// /// This method returns the maximum of two values, preserving order and /// eliminating NaN when possible. For two values `x` and `y`, the result of /// `maximum(x, y)` is `x` if `x > y`, `y` if `x <= y`, or whichever of `x` /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. /// /// Double.maximum(10.0, -25.0) /// // 10.0 /// Double.maximum(10.0, .nan) /// // 10.0 /// Double.maximum(.nan, -25.0) /// // -25.0 /// Double.maximum(.nan, .nan) /// // nan /// /// The `maximum` method implements the `maxNum` operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: The greater of `x` and `y`, or whichever is a number if the /// other is NaN. static func maximum(_ x: Self, _ y: Self) -> Self /// Returns the value with lesser magnitude. /// /// This method returns the value with lesser magnitude of the two given /// values, preserving order and eliminating NaN when possible. For two /// values `x` and `y`, the result of `minimumMagnitude(x, y)` is `x` if /// `x.magnitude <= y.magnitude`, `y` if `y.magnitude < x.magnitude`, or /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result /// is NaN. /// /// Double.minimumMagnitude(10.0, -25.0) /// // 10.0 /// Double.minimumMagnitude(10.0, .nan) /// // 10.0 /// Double.minimumMagnitude(.nan, -25.0) /// // -25.0 /// Double.minimumMagnitude(.nan, .nan) /// // nan /// /// The `minimumMagnitude` method implements the `minNumMag` operation /// defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: Whichever of `x` or `y` has lesser magnitude, or whichever is /// a number if the other is NaN. static func minimumMagnitude(_ x: Self, _ y: Self) -> Self /// Returns the value with greater magnitude. /// /// This method returns the value with greater magnitude of the two given /// values, preserving order and eliminating NaN when possible. For two /// values `x` and `y`, the result of `maximumMagnitude(x, y)` is `x` if /// `x.magnitude > y.magnitude`, `y` if `x.magnitude <= y.magnitude`, or /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result /// is NaN. /// /// Double.maximumMagnitude(10.0, -25.0) /// // -25.0 /// Double.maximumMagnitude(10.0, .nan) /// // 10.0 /// Double.maximumMagnitude(.nan, -25.0) /// // -25.0 /// Double.maximumMagnitude(.nan, .nan) /// // nan /// /// The `maximumMagnitude` method implements the `maxNumMag` operation /// defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: Whichever of `x` or `y` has greater magnitude, or whichever is /// a number if the other is NaN. static func maximumMagnitude(_ x: Self, _ y: Self) -> Self /// Returns this value rounded to an integral value using the specified /// rounding rule. /// /// The following example rounds a value using four different rounding rules: /// /// let x = 6.5 /// /// // Equivalent to the C 'round' function: /// print(x.rounded(.toNearestOrAwayFromZero)) /// // Prints "7.0" /// /// // Equivalent to the C 'trunc' function: /// print(x.rounded(.towardZero)) /// // Prints "6.0" /// /// // Equivalent to the C 'ceil' function: /// print(x.rounded(.up)) /// // Prints "7.0" /// /// // Equivalent to the C 'floor' function: /// print(x.rounded(.down)) /// // Prints "6.0" /// /// For more information about the available rounding rules, see the /// `FloatingPointRoundingRule` enumeration. To round a value using the /// default "schoolbook rounding", you can use the shorter `rounded()` /// method instead. /// /// print(x.rounded()) /// // Prints "7.0" /// /// - Parameter rule: The rounding rule to use. /// - Returns: The integral value found by rounding using `rule`. func rounded(_ rule: FloatingPointRoundingRule) -> Self /// Rounds the value to an integral value using the specified rounding rule. /// /// The following example rounds a value using four different rounding rules: /// /// // Equivalent to the C 'round' function: /// var w = 6.5 /// w.round(.toNearestOrAwayFromZero) /// // w == 7.0 /// /// // Equivalent to the C 'trunc' function: /// var x = 6.5 /// x.round(.towardZero) /// // x == 6.0 /// /// // Equivalent to the C 'ceil' function: /// var y = 6.5 /// y.round(.up) /// // y == 7.0 /// /// // Equivalent to the C 'floor' function: /// var z = 6.5 /// z.round(.down) /// // z == 6.0 /// /// For more information about the available rounding rules, see the /// `FloatingPointRoundingRule` enumeration. To round a value using the /// default "schoolbook rounding", you can use the shorter `round()` method /// instead. /// /// var w1 = 6.5 /// w1.round() /// // w1 == 7.0 /// /// - Parameter rule: The rounding rule to use. mutating func round(_ rule: FloatingPointRoundingRule) /// The least representable value that compares greater than this value. /// /// For any finite value `x`, `x.nextUp` is greater than `x`. For `nan` or /// `infinity`, `x.nextUp` is `x` itself. The following special cases also /// apply: /// /// - If `x` is `-infinity`, then `x.nextUp` is `-greatestFiniteMagnitude`. /// - If `x` is `-leastNonzeroMagnitude`, then `x.nextUp` is `-0.0`. /// - If `x` is zero, then `x.nextUp` is `leastNonzeroMagnitude`. /// - If `x` is `greatestFiniteMagnitude`, then `x.nextUp` is `infinity`. var nextUp: Self { get } /// The greatest representable value that compares less than this value. /// /// For any finite value `x`, `x.nextDown` is less than `x`. For `nan` or /// `-infinity`, `x.nextDown` is `x` itself. The following special cases /// also apply: /// /// - If `x` is `infinity`, then `x.nextDown` is `greatestFiniteMagnitude`. /// - If `x` is `leastNonzeroMagnitude`, then `x.nextDown` is `0.0`. /// - If `x` is zero, then `x.nextDown` is `-leastNonzeroMagnitude`. /// - If `x` is `-greatestFiniteMagnitude`, then `x.nextDown` is `-infinity`. var nextDown: Self { get } /// Returns a Boolean value indicating whether this instance is equal to the /// given value. /// /// This method serves as the basis for the equal-to operator (`==`) for /// floating-point values. When comparing two values with this method, `-0` /// is equal to `+0`. NaN is not equal to any value, including itself. For /// example: /// /// let x = 15.0 /// x.isEqual(to: 15.0) /// // true /// x.isEqual(to: .nan) /// // false /// Double.nan.isEqual(to: .nan) /// // false /// /// The `isEqual(to:)` method implements the equality predicate defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` has the same value as this instance; /// otherwise, `false`. If either this value or `other` is NaN, the result /// of this method is `false`. func isEqual(to other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than the /// given value. /// /// This method serves as the basis for the less-than operator (`<`) for /// floating-point values. Some special cases apply: /// /// - Because NaN compares not less than nor greater than any value, this /// method returns `false` when called on NaN or when NaN is passed as /// `other`. /// - `-infinity` compares less than all values except for itself and NaN. /// - Every value except for NaN and `+infinity` compares less than /// `+infinity`. /// /// let x = 15.0 /// x.isLess(than: 20.0) /// // true /// x.isLess(than: .nan) /// // false /// Double.nan.isLess(than: x) /// // false /// /// The `isLess(than:)` method implements the less-than predicate defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if this value is less than `other`; otherwise, `false`. /// If either this value or `other` is NaN, the result of this method is /// `false`. func isLess(than other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than or /// equal to the given value. /// /// This method serves as the basis for the less-than-or-equal-to operator /// (`<=`) for floating-point values. Some special cases apply: /// /// - Because NaN is incomparable with any value, this method returns `false` /// when called on NaN or when NaN is passed as `other`. /// - `-infinity` compares less than or equal to all values except NaN. /// - Every value except NaN compares less than or equal to `+infinity`. /// /// let x = 15.0 /// x.isLessThanOrEqualTo(20.0) /// // true /// x.isLessThanOrEqualTo(.nan) /// // false /// Double.nan.isLessThanOrEqualTo(x) /// // false /// /// The `isLessThanOrEqualTo(_:)` method implements the less-than-or-equal /// predicate defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` is greater than this value; otherwise, /// `false`. If either this value or `other` is NaN, the result of this /// method is `false`. func isLessThanOrEqualTo(_ other: Self) -> Bool /// Returns a Boolean value indicating whether this instance should precede /// or tie positions with the given value in an ascending sort. /// /// This relation is a refinement of the less-than-or-equal-to operator /// (`<=`) that provides a total order on all values of the type, including /// signed zeros and NaNs. /// /// The following example uses `isTotallyOrdered(belowOrEqualTo:)` to sort an /// array of floating-point values, including some that are NaN: /// /// var numbers = [2.5, 21.25, 3.0, .nan, -9.5] /// numbers.sort { !$1.isTotallyOrdered(belowOrEqualTo: $0) } /// print(numbers) /// // Prints "[-9.5, 2.5, 3.0, 21.25, nan]" /// /// The `isTotallyOrdered(belowOrEqualTo:)` method implements the total order /// relation as defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: A floating-point value to compare to this value. /// - Returns: `true` if this value is ordered below or the same as `other` /// in a total ordering of the floating-point type; otherwise, `false`. func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool /// A Boolean value indicating whether this instance is normal. /// /// A *normal* value is a finite number that uses the full precision /// available to values of a type. Zero is neither a normal nor a subnormal /// number. var isNormal: Bool { get } /// A Boolean value indicating whether this instance is finite. /// /// All values other than NaN and infinity are considered finite, whether /// normal or subnormal. For NaN, both `isFinite` and `isInfinite` are false. var isFinite: Bool { get } /// A Boolean value indicating whether the instance is equal to zero. /// /// The `isZero` property of a value `x` is `true` when `x` represents either /// `-0.0` or `+0.0`. `x.isZero` is equivalent to the following comparison: /// `x == 0.0`. /// /// let x = -0.0 /// x.isZero // true /// x == 0.0 // true var isZero: Bool { get } /// A Boolean value indicating whether the instance is subnormal. /// /// A *subnormal* value is a nonzero number that has a lesser magnitude than /// the smallest normal number. Subnormal values don't use the full /// precision available to values of a type. /// /// Zero is neither a normal nor a subnormal number. Subnormal numbers are /// often called *denormal* or *denormalized*---these are different names /// for the same concept. var isSubnormal: Bool { get } /// A Boolean value indicating whether the instance is infinite. /// /// For NaN, both `isFinite` and `isInfinite` are false. var isInfinite: Bool { get } /// A Boolean value indicating whether the instance is NaN ("not a number"). /// /// Because NaN is not equal to any value, including NaN, use this property /// instead of the equal-to operator (`==`) or not-equal-to operator (`!=`) /// to test whether a value is or is not NaN. For example: /// /// let x = 0.0 /// let y = x * .infinity /// // y is a NaN /// /// // Comparing with the equal-to operator never returns 'true' /// print(x == Double.nan) /// // Prints "false" /// print(y == Double.nan) /// // Prints "false" /// /// // Test with the 'isNaN' property instead /// print(x.isNaN) /// // Prints "false" /// print(y.isNaN) /// // Prints "true" /// /// This property is `true` for both quiet and signaling NaNs. var isNaN: Bool { get } /// A Boolean value indicating whether the instance is a signaling NaN. /// /// Signaling NaNs typically raise the Invalid flag when used in general /// computing operations. var isSignalingNaN: Bool { get } /// The classification of this value. /// /// A value's `floatingPointClass` property describes its "class" as /// described by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var floatingPointClass: FloatingPointClassification { get } /// A Boolean value indicating whether the instance's representation is in /// its canonical form. /// /// The [IEEE 754 specification][spec] defines a *canonical*, or preferred, /// encoding of a floating-point value. On platforms that fully support /// IEEE 754, every `Float` or `Double` value is canonical, but /// non-canonical values can exist on other platforms or for other types. /// Some examples: /// /// - On platforms that flush subnormal numbers to zero (such as armv7 /// with the default floating-point environment), Swift interprets /// subnormal `Float` and `Double` values as non-canonical zeros. /// (In Swift 5.1 and earlier, `isCanonical` is `true` for these /// values, which is the incorrect value.) /// /// - On i386 and x86_64, `Float80` has a number of non-canonical /// encodings. "Pseudo-NaNs", "pseudo-infinities", and "unnormals" are /// interpreted as non-canonical NaN encodings. "Pseudo-denormals" are /// interpreted as non-canonical encodings of subnormal values. /// /// - Decimal floating-point types admit a large number of non-canonical /// encodings. Consult the IEEE 754 standard for additional details. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var isCanonical: Bool { get } } /// The sign of a floating-point value. @frozen public enum FloatingPointSign: Int, Sendable { /// The sign for a positive value. case plus /// The sign for a negative value. case minus // Explicit declarations of otherwise-synthesized members to make them // @inlinable, promising that we will never change the implementation. @inlinable public init?(rawValue: Int) { switch rawValue { case 0: self = .plus case 1: self = .minus default: return nil } } @inlinable public var rawValue: Int { switch self { case .plus: return 0 case .minus: return 1 } } @_transparent @inlinable public static func ==(a: FloatingPointSign, b: FloatingPointSign) -> Bool { return a.rawValue == b.rawValue } @inlinable public var hashValue: Int { return rawValue.hashValue } @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } @inlinable public func _rawHashValue(seed: Int) -> Int { return rawValue._rawHashValue(seed: seed) } } /// The IEEE 754 floating-point classes. @frozen public enum FloatingPointClassification: Sendable { /// A signaling NaN ("not a number"). /// /// A signaling NaN sets the floating-point exception status when used in /// many floating-point operations. case signalingNaN /// A silent NaN ("not a number") value. case quietNaN /// A value equal to `-infinity`. case negativeInfinity /// A negative value that uses the full precision of the floating-point type. case negativeNormal /// A negative, nonzero number that does not use the full precision of the /// floating-point type. case negativeSubnormal /// A value equal to zero with a negative sign. case negativeZero /// A value equal to zero with a positive sign. case positiveZero /// A positive, nonzero number that does not use the full precision of the /// floating-point type. case positiveSubnormal /// A positive value that uses the full precision of the floating-point type. case positiveNormal /// A value equal to `+infinity`. case positiveInfinity } /// A rule for rounding a floating-point number. public enum FloatingPointRoundingRule: Sendable { /// Round to the closest allowed value; if two values are equally close, the /// one with greater magnitude is chosen. /// /// This rounding rule is also known as "schoolbook rounding." The following /// example shows the results of rounding numbers using this rule: /// /// (5.2).rounded(.toNearestOrAwayFromZero) /// // 5.0 /// (5.5).rounded(.toNearestOrAwayFromZero) /// // 6.0 /// (-5.2).rounded(.toNearestOrAwayFromZero) /// // -5.0 /// (-5.5).rounded(.toNearestOrAwayFromZero) /// // -6.0 /// /// This rule is equivalent to the C `round` function and implements the /// `roundToIntegralTiesToAway` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case toNearestOrAwayFromZero /// Round to the closest allowed value; if two values are equally close, the /// even one is chosen. /// /// This rounding rule is also known as "bankers rounding," and is the /// default IEEE 754 rounding mode for arithmetic. The following example /// shows the results of rounding numbers using this rule: /// /// (5.2).rounded(.toNearestOrEven) /// // 5.0 /// (5.5).rounded(.toNearestOrEven) /// // 6.0 /// (4.5).rounded(.toNearestOrEven) /// // 4.0 /// /// This rule implements the `roundToIntegralTiesToEven` operation defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case toNearestOrEven /// Round to the closest allowed value that is greater than or equal to the /// source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.up) /// // 6.0 /// (5.5).rounded(.up) /// // 6.0 /// (-5.2).rounded(.up) /// // -5.0 /// (-5.5).rounded(.up) /// // -5.0 /// /// This rule is equivalent to the C `ceil` function and implements the /// `roundToIntegralTowardPositive` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case up /// Round to the closest allowed value that is less than or equal to the /// source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.down) /// // 5.0 /// (5.5).rounded(.down) /// // 5.0 /// (-5.2).rounded(.down) /// // -6.0 /// (-5.5).rounded(.down) /// // -6.0 /// /// This rule is equivalent to the C `floor` function and implements the /// `roundToIntegralTowardNegative` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case down /// Round to the closest allowed value whose magnitude is less than or equal /// to that of the source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.towardZero) /// // 5.0 /// (5.5).rounded(.towardZero) /// // 5.0 /// (-5.2).rounded(.towardZero) /// // -5.0 /// (-5.5).rounded(.towardZero) /// // -5.0 /// /// This rule is equivalent to the C `trunc` function and implements the /// `roundToIntegralTowardZero` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case towardZero /// Round to the closest allowed value whose magnitude is greater than or /// equal to that of the source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.awayFromZero) /// // 6.0 /// (5.5).rounded(.awayFromZero) /// // 6.0 /// (-5.2).rounded(.awayFromZero) /// // -6.0 /// (-5.5).rounded(.awayFromZero) /// // -6.0 case awayFromZero } extension FloatingPoint { @_transparent public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.isEqual(to: rhs) } @_transparent public static func < (lhs: Self, rhs: Self) -> Bool { return lhs.isLess(than: rhs) } @_transparent public static func <= (lhs: Self, rhs: Self) -> Bool { return lhs.isLessThanOrEqualTo(rhs) } @_transparent public static func > (lhs: Self, rhs: Self) -> Bool { return rhs.isLess(than: lhs) } @_transparent public static func >= (lhs: Self, rhs: Self) -> Bool { return rhs.isLessThanOrEqualTo(lhs) } } /// A radix-2 (binary) floating-point type. /// /// The `BinaryFloatingPoint` protocol extends the `FloatingPoint` protocol /// with operations specific to floating-point binary types, as defined by the /// [IEEE 754 specification][spec]. `BinaryFloatingPoint` is implemented in /// the standard library by `Float`, `Double`, and `Float80` where available. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 public protocol BinaryFloatingPoint: FloatingPoint, ExpressibleByFloatLiteral { /// A type that represents the encoded significand of a value. associatedtype RawSignificand: UnsignedInteger /// A type that represents the encoded exponent of a value. associatedtype RawExponent: UnsignedInteger /// Creates a new instance from the specified sign and bit patterns. /// /// The values passed as `exponentBitPattern` and `significandBitPattern` are /// interpreted in the binary interchange format defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - sign: The sign of the new value. /// - exponentBitPattern: The bit pattern to use for the exponent field of /// the new value. /// - significandBitPattern: The bit pattern to use for the significand /// field of the new value. init(sign: FloatingPointSign, exponentBitPattern: RawExponent, significandBitPattern: RawSignificand) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Float) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Double) #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Float80) #endif /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: A floating-point value to be converted. init<Source: BinaryFloatingPoint>(_ value: Source) /// Creates a new instance from the given value, if it can be represented /// exactly. /// /// If the given floating-point value cannot be represented exactly, the /// result is `nil`. A value that is NaN ("not a number") cannot be /// represented exactly if its payload cannot be encoded exactly. /// /// - Parameter value: A floating-point value to be converted. init?<Source: BinaryFloatingPoint>(exactly value: Source) /// The number of bits used to represent the type's exponent. /// /// A binary floating-point type's `exponentBitCount` imposes a limit on the /// range of the exponent for normal, finite values. The *exponent bias* of /// a type `F` can be calculated as the following, where `**` is /// exponentiation: /// /// let bias = 2 ** (F.exponentBitCount - 1) - 1 /// /// The least normal exponent for values of the type `F` is `1 - bias`, and /// the largest finite exponent is `bias`. An all-zeros exponent is reserved /// for subnormals and zeros, and an all-ones exponent is reserved for /// infinity and NaN. /// /// For example, the `Float` type has an `exponentBitCount` of 8, which gives /// an exponent bias of `127` by the calculation above. /// /// let bias = 2 ** (Float.exponentBitCount - 1) - 1 /// // bias == 127 /// print(Float.greatestFiniteMagnitude.exponent) /// // Prints "127" /// print(Float.leastNormalMagnitude.exponent) /// // Prints "-126" static var exponentBitCount: Int { get } /// The available number of fractional significand bits. /// /// For fixed-width floating-point types, this is the actual number of /// fractional significand bits. /// /// For extensible floating-point types, `significandBitCount` should be the /// maximum allowed significand width (without counting any leading integral /// bit of the significand). If there is no upper limit, then /// `significandBitCount` should be `Int.max`. /// /// Note that `Float80.significandBitCount` is 63, even though 64 bits are /// used to store the significand in the memory representation of a /// `Float80` (unlike other floating-point types, `Float80` explicitly /// stores the leading integral significand bit, but the /// `BinaryFloatingPoint` APIs provide an abstraction so that users don't /// need to be aware of this detail). static var significandBitCount: Int { get } /// The raw encoding of the value's exponent field. /// /// This value is unadjusted by the type's exponent bias. var exponentBitPattern: RawExponent { get } /// The raw encoding of the value's significand field. /// /// The `significandBitPattern` property does not include the leading /// integral bit of the significand, even for types like `Float80` that /// store it explicitly. var significandBitPattern: RawSignificand { get } /// The floating-point value with the same sign and exponent as this value, /// but with a significand of 1.0. /// /// A *binade* is a set of binary floating-point values that all have the /// same sign and exponent. The `binade` property is a member of the same /// binade as this value, but with a unit significand. /// /// In this example, `x` has a value of `21.5`, which is stored as /// `1.34375 * 2**4`, where `**` is exponentiation. Therefore, `x.binade` is /// equal to `1.0 * 2**4`, or `16.0`. /// /// let x = 21.5 /// // x.significand == 1.34375 /// // x.exponent == 4 /// /// let y = x.binade /// // y == 16.0 /// // y.significand == 1.0 /// // y.exponent == 4 var binade: Self { get } /// The number of bits required to represent the value's significand. /// /// If this value is a finite nonzero number, `significandWidth` is the /// number of fractional bits required to represent the value of /// `significand`; otherwise, `significandWidth` is -1. The value of /// `significandWidth` is always -1 or between zero and /// `significandBitCount`. For example: /// /// - For any representable power of two, `significandWidth` is zero, because /// `significand` is `1.0`. /// - If `x` is 10, `x.significand` is `1.01` in binary, so /// `x.significandWidth` is 2. /// - If `x` is Float.pi, `x.significand` is `1.10010010000111111011011` in /// binary, and `x.significandWidth` is 23. var significandWidth: Int { get } } extension FloatingPoint { @inlinable // FIXME(sil-serialize-all) public static var ulpOfOne: Self { return (1 as Self).ulp } @_transparent public func rounded(_ rule: FloatingPointRoundingRule) -> Self { var lhs = self lhs.round(rule) return lhs } @_transparent public func rounded() -> Self { return rounded(.toNearestOrAwayFromZero) } @_transparent public mutating func round() { round(.toNearestOrAwayFromZero) } @inlinable // FIXME(inline-always) public var nextDown: Self { @inline(__always) get { return -(-self).nextUp } } @inlinable // FIXME(inline-always) @inline(__always) public func truncatingRemainder(dividingBy other: Self) -> Self { var lhs = self lhs.formTruncatingRemainder(dividingBy: other) return lhs } @inlinable // FIXME(inline-always) @inline(__always) public func remainder(dividingBy other: Self) -> Self { var lhs = self lhs.formRemainder(dividingBy: other) return lhs } @_transparent public func squareRoot( ) -> Self { var lhs = self lhs.formSquareRoot( ) return lhs } @_transparent public func addingProduct(_ lhs: Self, _ rhs: Self) -> Self { var addend = self addend.addProduct(lhs, rhs) return addend } @inlinable public static func minimum(_ x: Self, _ y: Self) -> Self { if x <= y || y.isNaN { return x } return y } @inlinable public static func maximum(_ x: Self, _ y: Self) -> Self { if x > y || y.isNaN { return x } return y } @inlinable public static func minimumMagnitude(_ x: Self, _ y: Self) -> Self { if x.magnitude <= y.magnitude || y.isNaN { return x } return y } @inlinable public static func maximumMagnitude(_ x: Self, _ y: Self) -> Self { if x.magnitude > y.magnitude || y.isNaN { return x } return y } @inlinable public var floatingPointClass: FloatingPointClassification { if isSignalingNaN { return .signalingNaN } if isNaN { return .quietNaN } if isInfinite { return sign == .minus ? .negativeInfinity : .positiveInfinity } if isNormal { return sign == .minus ? .negativeNormal : .positiveNormal } if isSubnormal { return sign == .minus ? .negativeSubnormal : .positiveSubnormal } return sign == .minus ? .negativeZero : .positiveZero } } extension BinaryFloatingPoint { @inlinable @inline(__always) public static var radix: Int { return 2 } @inlinable public init(signOf: Self, magnitudeOf: Self) { self.init( sign: signOf.sign, exponentBitPattern: magnitudeOf.exponentBitPattern, significandBitPattern: magnitudeOf.significandBitPattern ) } public // @testable static func _convert<Source: BinaryFloatingPoint>( from source: Source ) -> (value: Self, exact: Bool) { guard _fastPath(!source.isZero) else { return (source.sign == .minus ? -0.0 : 0, true) } guard _fastPath(source.isFinite) else { if source.isInfinite { return (source.sign == .minus ? -.infinity : .infinity, true) } // IEEE 754 requires that any NaN payload be propagated, if possible. let payload_ = source.significandBitPattern & ~(Source.nan.significandBitPattern | Source.signalingNaN.significandBitPattern) let mask = Self.greatestFiniteMagnitude.significandBitPattern & ~(Self.nan.significandBitPattern | Self.signalingNaN.significandBitPattern) let payload = Self.RawSignificand(truncatingIfNeeded: payload_) & mask // Although .signalingNaN.exponentBitPattern == .nan.exponentBitPattern, // we do not *need* to rely on this relation, and therefore we do not. let value = source.isSignalingNaN ? Self( sign: source.sign, exponentBitPattern: Self.signalingNaN.exponentBitPattern, significandBitPattern: payload | Self.signalingNaN.significandBitPattern) : Self( sign: source.sign, exponentBitPattern: Self.nan.exponentBitPattern, significandBitPattern: payload | Self.nan.significandBitPattern) // We define exactness by equality after roundtripping; since NaN is never // equal to itself, it can never be converted exactly. return (value, false) } let exponent = source.exponent var exemplar = Self.leastNormalMagnitude let exponentBitPattern: Self.RawExponent let leadingBitIndex: Int let shift: Int let significandBitPattern: Self.RawSignificand if exponent < exemplar.exponent { // The floating-point result is either zero or subnormal. exemplar = Self.leastNonzeroMagnitude let minExponent = exemplar.exponent if exponent + 1 < minExponent { return (source.sign == .minus ? -0.0 : 0, false) } if _slowPath(exponent + 1 == minExponent) { // Although the most significant bit (MSB) of a subnormal source // significand is explicit, Swift BinaryFloatingPoint APIs actually // omit any explicit MSB from the count represented in // significandWidth. For instance: // // Double.leastNonzeroMagnitude.significandWidth == 0 // // Therefore, we do not need to adjust our work here for a subnormal // source. return source.significandWidth == 0 ? (source.sign == .minus ? -0.0 : 0, false) : (source.sign == .minus ? -exemplar : exemplar, false) } exponentBitPattern = 0 as Self.RawExponent leadingBitIndex = Int(Self.Exponent(exponent) - minExponent) shift = leadingBitIndex &- (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) let leadingBit = source.isNormal ? (1 as Self.RawSignificand) << leadingBitIndex : 0 significandBitPattern = leadingBit | (shift >= 0 ? Self.RawSignificand(source.significandBitPattern) << shift : Self.RawSignificand(source.significandBitPattern >> -shift)) } else { // The floating-point result is either normal or infinite. exemplar = Self.greatestFiniteMagnitude if exponent > exemplar.exponent { return (source.sign == .minus ? -.infinity : .infinity, false) } exponentBitPattern = exponent < 0 ? (1 as Self).exponentBitPattern - Self.RawExponent(-exponent) : (1 as Self).exponentBitPattern + Self.RawExponent(exponent) leadingBitIndex = exemplar.significandWidth shift = leadingBitIndex &- (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) let sourceLeadingBit = source.isSubnormal ? (1 as Source.RawSignificand) << (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) : 0 significandBitPattern = shift >= 0 ? Self.RawSignificand( sourceLeadingBit ^ source.significandBitPattern) << shift : Self.RawSignificand( (sourceLeadingBit ^ source.significandBitPattern) >> -shift) } let value = Self( sign: source.sign, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern) if source.significandWidth <= leadingBitIndex { return (value, true) } // We promise to round to the closest representation. Therefore, we must // take a look at the bits that we've just truncated. let ulp = (1 as Source.RawSignificand) << -shift let truncatedBits = source.significandBitPattern & (ulp - 1) if truncatedBits < ulp / 2 { return (value, false) } let rounded = source.sign == .minus ? value.nextDown : value.nextUp if _fastPath(truncatedBits > ulp / 2) { return (rounded, false) } // If two representable values are equally close, we return the value with // more trailing zeros in its significand bit pattern. return significandBitPattern.trailingZeroBitCount > rounded.significandBitPattern.trailingZeroBitCount ? (value, false) : (rounded, false) } /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: A floating-point value to be converted. @inlinable public init<Source: BinaryFloatingPoint>(_ value: Source) { // If two IEEE 754 binary interchange formats share the same exponent bit // count and significand bit count, then they must share the same encoding // for finite and infinite values. switch (Source.exponentBitCount, Source.significandBitCount) { #if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) case (5, 10): guard #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) //SwiftStdlib 5.3 else { // Convert signaling NaN to quiet NaN by multiplying by 1. self = Self._convert(from: value).value * 1 break } let value_ = value as? Float16 ?? Float16( sign: value.sign, exponentBitPattern: UInt(truncatingIfNeeded: value.exponentBitPattern), significandBitPattern: UInt16(truncatingIfNeeded: value.significandBitPattern)) self = Self(Float(value_)) #endif case (8, 23): let value_ = value as? Float ?? Float( sign: value.sign, exponentBitPattern: UInt(truncatingIfNeeded: value.exponentBitPattern), significandBitPattern: UInt32(truncatingIfNeeded: value.significandBitPattern)) self = Self(value_) case (11, 52): let value_ = value as? Double ?? Double( sign: value.sign, exponentBitPattern: UInt(truncatingIfNeeded: value.exponentBitPattern), significandBitPattern: UInt64(truncatingIfNeeded: value.significandBitPattern)) self = Self(value_) #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) case (15, 63): let value_ = value as? Float80 ?? Float80( sign: value.sign, exponentBitPattern: UInt(truncatingIfNeeded: value.exponentBitPattern), significandBitPattern: UInt64(truncatingIfNeeded: value.significandBitPattern)) self = Self(value_) #endif default: // Convert signaling NaN to quiet NaN by multiplying by 1. self = Self._convert(from: value).value * 1 } } /// Creates a new instance from the given value, if it can be represented /// exactly. /// /// If the given floating-point value cannot be represented exactly, the /// result is `nil`. /// /// - Parameter value: A floating-point value to be converted. @inlinable public init?<Source: BinaryFloatingPoint>(exactly value: Source) { // We define exactness by equality after roundtripping; since NaN is never // equal to itself, it can never be converted exactly. if value.isNaN { return nil } if (Source.exponentBitCount > Self.exponentBitCount || Source.significandBitCount > Self.significandBitCount) && value.isFinite && !value.isZero { let exponent = value.exponent if exponent < Self.leastNormalMagnitude.exponent { if exponent < Self.leastNonzeroMagnitude.exponent { return nil } if value.significandWidth > Int(Self.Exponent(exponent) - Self.leastNonzeroMagnitude.exponent) { return nil } } else { if exponent > Self.greatestFiniteMagnitude.exponent { return nil } if value.significandWidth > Self.greatestFiniteMagnitude.significandWidth { return nil } } } self = Self(value) } @inlinable public func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool { // Quick return when possible. if self < other { return true } if other > self { return false } // Self and other are either equal or unordered. // Every negative-signed value (even NaN) is less than every positive- // signed value, so if the signs do not match, we simply return the // sign bit of self. if sign != other.sign { return sign == .minus } // Sign bits match; look at exponents. if exponentBitPattern > other.exponentBitPattern { return sign == .minus } if exponentBitPattern < other.exponentBitPattern { return sign == .plus } // Signs and exponents match, look at significands. if significandBitPattern > other.significandBitPattern { return sign == .minus } if significandBitPattern < other.significandBitPattern { return sign == .plus } // Sign, exponent, and significand all match. return true } } extension BinaryFloatingPoint where Self.RawSignificand: FixedWidthInteger { public // @testable static func _convert<Source: BinaryInteger>( from source: Source ) -> (value: Self, exact: Bool) { // Useful constants: let exponentBias = (1 as Self).exponentBitPattern let significandMask = ((1 as RawSignificand) << Self.significandBitCount) &- 1 // Zero is really extra simple, and saves us from trying to normalize a // value that cannot be normalized. if _fastPath(source == 0) { return (0, true) } // We now have a non-zero value; convert it to a strictly positive value // by taking the magnitude. let magnitude = source.magnitude var exponent = magnitude._binaryLogarithm() // If the exponent would be larger than the largest representable // exponent, the result is just an infinity of the appropriate sign. guard exponent <= Self.greatestFiniteMagnitude.exponent else { return (Source.isSigned && source < 0 ? -.infinity : .infinity, false) } // If exponent <= significandBitCount, we don't need to round it to // construct the significand; we just need to left-shift it into place; // the result is always exact as we've accounted for exponent-too-large // already and no rounding can occur. if exponent <= Self.significandBitCount { let shift = Self.significandBitCount &- exponent let significand = RawSignificand(magnitude) &<< shift let value = Self( sign: Source.isSigned && source < 0 ? .minus : .plus, exponentBitPattern: exponentBias + RawExponent(exponent), significandBitPattern: significand ) return (value, true) } // exponent > significandBitCount, so we need to do a rounding right // shift, and adjust exponent if needed let shift = exponent &- Self.significandBitCount let halfway = (1 as Source.Magnitude) << (shift - 1) let mask = 2 * halfway - 1 let fraction = magnitude & mask var significand = RawSignificand(truncatingIfNeeded: magnitude >> shift) & significandMask if fraction > halfway || (fraction == halfway && significand & 1 == 1) { var carry = false (significand, carry) = significand.addingReportingOverflow(1) if carry || significand > significandMask { exponent += 1 guard exponent <= Self.greatestFiniteMagnitude.exponent else { return (Source.isSigned && source < 0 ? -.infinity : .infinity, false) } } } return (Self( sign: Source.isSigned && source < 0 ? .minus : .plus, exponentBitPattern: exponentBias + RawExponent(exponent), significandBitPattern: significand ), fraction == 0) } /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. @inlinable public init<Source: BinaryInteger>(_ value: Source) { self = Self._convert(from: value).value } /// Creates a new value, if the given integer can be represented exactly. /// /// If the given integer cannot be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to convert to a floating-point value. @inlinable public init?<Source: BinaryInteger>(exactly value: Source) { let (value_, exact) = Self._convert(from: value) guard exact else { return nil } self = value_ } }
apache-2.0
ef8f3ab3f559cf679af3dbdefd6728e6
36.961667
94
0.639538
4.109232
false
false
false
false
hadibadjian/GAlileo
storyboards/Storyboards/Source/InitialViewController.swift
1
942
// Copyright © 2016 HB. All rights reserved. class InitialViewController: UIViewController { @IBOutlet weak var purchaseCountLabel: UILabel! let winningNumber = 5 let wonLotterySegueIdentifier = "wonLotterySegue" var numberOfPurchases = 0 override func viewDidLoad() { super.viewDidLoad() title = "Storyboards" } @IBAction func purchaseTicketButtonPressed(sender: AnyObject) { numberOfPurchases += 1 purchaseCountLabel.text = "You have purchased \(numberOfPurchases) items" if numberOfPurchases == 5 { self.performSegueWithIdentifier(wonLotterySegueIdentifier, sender: nil) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == wonLotterySegueIdentifier { if let winnerVC = segue.destinationViewController as? WinnerViewController { winnerVC.congratsText = "Congratulations Hadi!" } } } } import UIKit
mit
575b5e62cb09ac8a794ef81430cb829d
25.885714
82
0.730074
4.875648
false
false
false
false
thomasvl/swift-protobuf
Sources/SwiftProtobufCore/Enum.swift
2
3260
// Sources/SwiftProtobuf/Enum.swift - Enum support // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Generated enums conform to SwiftProtobufCore.Enum /// /// See ProtobufTypes and JSONTypes for extension /// methods to support binary and JSON coding. /// // ----------------------------------------------------------------------------- /// Generated enum types conform to this protocol. public protocol Enum: RawRepresentable, Hashable, CaseIterable, _ProtoSendable { /// Creates a new instance of the enum initialized to its default value. init() /// Creates a new instance of the enum from the given raw integer value. /// /// For proto2 enums, this initializer will fail if the raw value does not /// correspond to a valid enum value. For proto3 enums, this initializer never /// fails; unknown values are created as instances of the `UNRECOGNIZED` case. /// /// - Parameter rawValue: The raw integer value from which to create the enum /// value. init?(rawValue: Int) /// The raw integer value of the enum value. /// /// For a recognized enum case, this is the integer value of the case as /// defined in the .proto file. For `UNRECOGNIZED` cases in proto3, this is /// the value that was originally decoded. var rawValue: Int { get } } extension Enum { public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } /// Internal convenience property representing the name of the enum value (or /// `nil` if it is an `UNRECOGNIZED` value or doesn't provide names). /// /// Since the text format and JSON names are always identical, we don't need /// to distinguish them. internal var name: _NameMap.Name? { guard let nameProviding = Self.self as? _ProtoNameProviding.Type else { return nil } return nameProviding._protobuf_nameMap.names(for: rawValue)?.proto } /// Internal convenience initializer that returns the enum value with the /// given name, if it provides names. /// /// Since the text format and JSON names are always identical, we don't need /// to distinguish them. /// /// - Parameter name: The name of the enum case. internal init?(name: String) { guard let nameProviding = Self.self as? _ProtoNameProviding.Type, let number = nameProviding._protobuf_nameMap.number(forJSONName: name) else { return nil } self.init(rawValue: number) } /// Internal convenience initializer that returns the enum value with the /// given name, if it provides names. /// /// Since the text format and JSON names are always identical, we don't need /// to distinguish them. /// /// - Parameter name: Buffer holding the UTF-8 bytes of the desired name. internal init?(rawUTF8: UnsafeRawBufferPointer) { guard let nameProviding = Self.self as? _ProtoNameProviding.Type, let number = nameProviding._protobuf_nameMap.number(forJSONName: rawUTF8) else { return nil } self.init(rawValue: number) } }
apache-2.0
5b3689f47b43e3f4a029efd187fa7cfb
36.471264
86
0.669018
4.527778
false
false
false
false
LeeMinglu/LSWeiboSwift
LSWeiboSwift/LSWeiboSwift/Classes/Tools/LSExtension/UIImage+Extensions.swift
1
1954
// // UIImage+Extensions.swift // WeiBo // // Created by yaowei on 2016/7/5. // Copyright © 2016年 itcast. All rights reserved. // import UIKit extension UIImage { /// 创建头像图像 /// /// - parameter size: 尺寸 /// - parameter backColor: 背景颜色 /// /// - returns: 裁切后的图像 func avatarImage(size: CGSize?, backColor: UIColor = UIColor.white, lineColor: UIColor = UIColor.lightGray) -> UIImage? { var size = size if size == nil || size?.width == 0 { size = CGSize(width: 34, height: 34) } let rect = CGRect(origin: CGPoint(), size: size!) UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) backColor.setFill() UIRectFill(rect) let path = UIBezierPath(ovalIn: rect) path.addClip() draw(in: rect) let ovalPath = UIBezierPath(ovalIn: rect) ovalPath.lineWidth = 1 lineColor.setStroke() ovalPath.stroke() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } /// 生成指定大小的不透明图象 /// /// - parameter size: 尺寸 /// - parameter backColor: 背景颜色 /// /// - returns: 图像 func image(size: CGSize? = nil, backColor: UIColor = UIColor.white) -> UIImage? { var size = size if size == nil { size = self.size } let rect = CGRect(origin: CGPoint(), size: size!) UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) backColor.setFill() UIRectFill(rect) draw(in: rect) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } }
apache-2.0
a908ba9c445a66bba2152a1361f081f0
23.671053
125
0.5392
4.92126
false
false
false
false
cocoaheadsru/server
Sources/App/Controllers/Event/Registration/RegistrationControllerHelper.swift
1
2435
import Vapor import Fluent extension RegistrationController { struct Keys { static let regFields = "reg_fields" static let regFormId = "reg_form_id" static let fields = "fields" static let userAnswers = "user_answers" } func checkRadio(fieldId: Identifier, answerCount: Int) throws -> Bool { let fieldType = try RegField.find(fieldId)?.type if fieldType == RegField.FieldType.radio { return answerCount <= 1 } else { return true } } func checkRequired(fieldId: Identifier, answerCount: Int) throws -> Bool { guard let fieldRequired = try RegField.find(fieldId)?.required else { throw Abort(.internalServerError, reason: "Can't get fieldId") } if fieldRequired { return answerCount > 0 } else { return true } } func storeEventRegAnswers(_ request: Request, eventReg: EventReg, connection: Connection? = nil) throws { guard let eventRegId = eventReg.id else { throw Abort(.internalServerError, reason: "Can't get eventRegId") } guard let fields = request.json?[Keys.fields]?.array else { throw Abort(.internalServerError, reason: "Can't get 'fields' and 'reg_form_Id' from request") } for field in fields { let fieldId = try field.get(EventRegAnswer.Keys.regFieldId) as Identifier let userAnswers = try field.get(Keys.userAnswers) as [JSON] guard try checkRequired(fieldId: fieldId, answerCount: userAnswers.count) else { throw Abort(.internalServerError, reason: "The field must have at least one answer. Field id is '\(fieldId.int ?? -1)'") } guard try checkRadio(fieldId: fieldId, answerCount: userAnswers.count) else { throw Abort(.internalServerError, reason: "The answer to field with type radio should be only one. Field id is '\(fieldId.int ?? -1)'") } for userAnswer in userAnswers { let answerId = try userAnswer.get("id") as Identifier let answerValue = try userAnswer.get("value") as String let eventRegAnswer = EventRegAnswer( eventRegId: eventRegId, regFieldId: fieldId, regFieldAnswerId: answerId, answerValue: answerValue) if let conn = connection { try eventRegAnswer.makeQuery(conn).save() } else { try eventRegAnswer.save() } } } } }
mit
afc905b48a7976d915602ad6396dee89
31.466667
143
0.640246
4.443431
false
false
false
false
xuech/OMS-WH
OMS-WH/Classes/OrderDetail/Controller/OrderDetailViewController.swift
1
4337
// // OrderDetailViewController.swift // OMS // // Created by gwy on 16/10/18. // Copyright © 2016年 文羿 顾. All rights reserved. // import UIKit import SVProgressHUD class OrderDetailViewController: UIViewController { fileprivate var viewModel = DealOrderVM() // pageMenu fileprivate var PageMenu:CAPSPageMenu? var sONo:String? var orderDetailModel:DealOrderInfoModel?{ didSet{ initData() setUpPageMenuChildControllers() } } override func viewDidLoad() { super.viewDidLoad() title = "订单详情" view.backgroundColor = UIColor.white view.addSubview(headerView) orderDetail() } // 跟踪按钮 fileprivate lazy var trackBtn:UIButton = { let btn = UIButton(type: .custom) btn.setImage(UIImage(named: "od_track"), for: UIControlState()) btn.addTarget(self, action: #selector(OrderDetailViewController.goToTrackingVC), for: .touchUpInside) btn.sizeToFit() return btn }() // 请求订单详情 fileprivate func orderDetail(){ viewModel.requestOrderData(soNo: sONo!) { (res, error) in if error == nil { self.orderDetailModel = res } } } fileprivate func initData(){ headerView.orderNumLB.text = orderDetailModel?.sONo headerView.ownerLB.text = orderDetailModel?.sOOIOrgCodeName headerView.statusLB.text = orderDetailModel?.statusName //只显示线下处理的状态 if let sOHandleType = orderDetailModel?.sOHandleType{ if sOHandleType == "OFFLINE"{ headerView.typeLB.text = "(线下)" } } let trackItem = UIBarButtonItem.init(customView: trackBtn) navigationItem.rightBarButtonItems = [trackItem] } // 进入跟踪页面 @objc fileprivate func goToTrackingVC(){ let orderTrackVC = OrderTrackingViewController() orderTrackVC.isHomeComin = false orderTrackVC.detailOrderModel = orderDetailModel self.navigationController?.pushViewController(orderTrackVC, animated: true) } fileprivate lazy var headerView:OrderDetailHeaderView = { let headerView = OrderDetailHeaderView() headerView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 60) return headerView }() fileprivate func setUpPageMenuChildControllers(){ var controllerArray:[UIViewController] = [] let saleOrderVC = SaleOrderViewController() saleOrderVC.title = "销售下单" saleOrderVC.orderDetailModel = orderDetailModel let storehouseVC = StorehouseViewController() storehouseVC.title = "仓配中心配货" storehouseVC.orderDetailModel = orderDetailModel let outboundOrderVC = OutboundOrderViewController() outboundOrderVC.title = "出库单" outboundOrderVC.sONo = orderDetailModel?.sONo let feedBackOrderVC = FeedbackOrderViewController() feedBackOrderVC.title = "反馈单" feedBackOrderVC.orderDetailModel = orderDetailModel controllerArray.append(saleOrderVC) controllerArray.append(storehouseVC) controllerArray.append(outboundOrderVC) controllerArray.append(feedBackOrderVC) let parameters: [CAPSPageMenuOption] = [ .scrollMenuBackgroundColor(UIColor.white), .selectedMenuItemLabelColor(kAppearanceColor), .unselectedMenuItemLabelColor(UIColor.black), .useMenuLikeSegmentedControl(true), .selectionIndicatorColor(kAppearanceColor), .menuHeight(50), .menuItemFont(UIFont.systemFont(ofSize: 14)) ] let meunPic = ["od_salesOrder","od_storeHouse","od_outBoundOrder","od_feedback"] PageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(x: 0.0, y: 61, width: kScreenWidth, height: kScreenHeight-61), pageMenuOptions: parameters, menuItemImages: meunPic) PageMenu?.bottomMenuHairlineColor = UIColor.colorHexStr("aaaaaa", alpha: 1) view.addSubview(PageMenu!.view) self.addChildViewController(PageMenu!) } }
mit
b2000382b5829b0b06eb8e9ca1fd3e36
32.856
196
0.646267
4.955504
false
false
false
false
zisko/swift
stdlib/public/core/Range.swift
1
31247
//===--- Range.swift ------------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that can be used to slice a collection. /// /// A type that conforms to `RangeExpression` can convert itself to a /// `Range<Bound>` of indices within a given collection. public protocol RangeExpression { /// The type for which the expression describes a range. associatedtype Bound: Comparable /// Returns the range of indices described by this range expression within /// the given collection. /// /// You can use the `relative(to:)` method to convert a range expression, /// which could be missing one or both of its endpoints, into a concrete /// range that is bounded on both sides. The following example uses this /// method to convert a partial range up to `4` into a half-open range, /// using an array instance to add the range's lower bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// let upToFour = ..<4 /// /// let r1 = upToFour.relative(to: numbers) /// // r1 == 0..<4 /// /// The `r1` range is bounded on the lower end by `0` because that is the /// starting index of the `numbers` array. When the collection passed to /// `relative(to:)` starts with a different index, that index is used as the /// lower bound instead. The next example creates a slice of `numbers` /// starting at index `2`, and then uses the slice with `relative(to:)` to /// convert `upToFour` to a concrete range. /// /// let numbersSuffix = numbers[2...] /// // numbersSuffix == [30, 40, 50, 60, 70] /// /// let r2 = upToFour.relative(to: numbersSuffix) /// // r2 == 2..<4 /// /// Use this method only if you need the concrete range it produces. To /// access a slice of a collection using a range expression, use the /// collection's generic subscript that uses a range expression as its /// parameter. /// /// let numbersPrefix = numbers[upToFour] /// // numbersPrefix == [10, 20, 30, 40] /// /// - Parameter collection: The collection to evaluate this range expression /// in relation to. /// - Returns: A range suitable for slicing `collection`. The returned range /// is *not* guaranteed to be inside the bounds of `collection`. Callers /// should apply the same preconditions to the return value as they would /// to a range provided directly by the user. func relative<C: Collection>( to collection: C ) -> Range<Bound> where C.Index == Bound /// Returns a Boolean value indicating whether the given element is contained /// within the range expression. /// /// - Parameter element: The element to check for containment. /// - Returns: `true` if `element` is contained in the range expression; /// otherwise, `false`. func contains(_ element: Bound) -> Bool } extension RangeExpression { @_inlineable public static func ~= (pattern: Self, value: Bound) -> Bool { return pattern.contains(value) } } /// A half-open interval from a lower bound up to, but not including, an upper /// bound. /// /// You create a `Range` instance by using the half-open range operator /// (`..<`). /// /// let underFive = 0.0..<5.0 /// /// You can use a `Range` instance to quickly check if a value is contained in /// a particular range of values. For example: /// /// underFive.contains(3.14) /// // true /// underFive.contains(6.28) /// // false /// underFive.contains(5.0) /// // false /// /// `Range` instances can represent an empty interval, unlike `ClosedRange`. /// /// let empty = 0.0..<0.0 /// empty.contains(0.0) /// // false /// empty.isEmpty /// // true /// /// Using a Range as a Collection of Consecutive Values /// ---------------------------------------------------- /// /// When a range uses integers as its lower and upper bounds, or any other type /// that conforms to the `Strideable` protocol with an integer stride, you can /// use that range in a `for`-`in` loop or with any sequence or collection /// method. The elements of the range are the consecutive values from its /// lower bound up to, but not including, its upper bound. /// /// for n in 3..<5 { /// print(n) /// } /// // Prints "3" /// // Prints "4" /// /// Because floating-point types such as `Float` and `Double` are their own /// `Stride` types, they cannot be used as the bounds of a countable range. If /// you need to iterate over consecutive floating-point values, see the /// `stride(from:to:by:)` function. @_fixed_layout public struct Range<Bound : Comparable> { /// The range's lower bound. /// /// In an empty range, `lowerBound` is equal to `upperBound`. public let lowerBound: Bound /// The range's upper bound. /// /// In an empty range, `upperBound` is equal to `lowerBound`. A `Range` /// instance does not contain its upper bound. public let upperBound: Bound /// Creates an instance with the given bounds. /// /// Because this initializer does not perform any checks, it should be used /// as an optimization only when you are absolutely certain that `lower` is /// less than or equal to `upper`. Using the half-open range operator /// (`..<`) to form `Range` instances is preferred. /// /// - Parameter bounds: A tuple of the lower and upper bounds of the range. @_inlineable public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) { self.lowerBound = bounds.lower self.upperBound = bounds.upper } /// Returns a Boolean value indicating whether the given element is contained /// within the range. /// /// Because `Range` represents a half-open range, a `Range` instance does not /// contain its upper bound. `element` is contained in the range if it is /// greater than or equal to the lower bound and less than the upper bound. /// /// - Parameter element: The element to check for containment. /// - Returns: `true` if `element` is contained in the range; otherwise, /// `false`. @_inlineable public func contains(_ element: Bound) -> Bool { return lowerBound <= element && element < upperBound } /// A Boolean value indicating whether the range contains no elements. /// /// An empty `Range` instance has equal lower and upper bounds. /// /// let empty: Range = 10..<10 /// print(empty.isEmpty) /// // Prints "true" @_inlineable public var isEmpty: Bool { return lowerBound == upperBound } } extension Range: Sequence where Bound: Strideable, Bound.Stride : SignedInteger { public typealias Element = Bound public typealias Iterator = IndexingIterator<Range<Bound>> } // FIXME: should just be RandomAccessCollection extension Range: Collection, BidirectionalCollection, RandomAccessCollection where Bound : Strideable, Bound.Stride : SignedInteger { /// A type that represents a position in the range. public typealias Index = Bound public typealias Indices = Range<Bound> public typealias SubSequence = Range<Bound> @_inlineable public var startIndex: Index { return lowerBound } @_inlineable public var endIndex: Index { return upperBound } @_inlineable public func index(after i: Index) -> Index { _failEarlyRangeCheck(i, bounds: startIndex..<endIndex) return i.advanced(by: 1) } @_inlineable public func index(before i: Index) -> Index { _precondition(i > lowerBound) _precondition(i <= upperBound) return i.advanced(by: -1) } @_inlineable public func index(_ i: Index, offsetBy n: Int) -> Index { let r = i.advanced(by: numericCast(n)) _precondition(r >= lowerBound) _precondition(r <= upperBound) return r } @_inlineable public func distance(from start: Index, to end: Index) -> Int { return numericCast(start.distance(to: end)) } /// Accesses the subsequence bounded by the given range. /// /// - Parameter bounds: A range of the range's indices. The upper and lower /// bounds of the `bounds` range must be valid indices of the collection. @_inlineable public subscript(bounds: Range<Index>) -> Range<Bound> { return bounds } /// The indices that are valid for subscripting the range, in ascending /// order. @_inlineable public var indices: Indices { return self } @_inlineable public func _customContainsEquatableElement(_ element: Element) -> Bool? { return lowerBound <= element && element < upperBound } @_inlineable public func _customIndexOfEquatableElement(_ element: Bound) -> Index?? { return lowerBound <= element && element < upperBound ? element : nil } /// Accesses the element at specified position. /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one past /// the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the range, and must not equal the range's end /// index. @_inlineable public subscript(position: Index) -> Element { // FIXME: swift-3-indexing-model: tests for the range check. _debugPrecondition(self.contains(position), "Index out of range") return position } } extension Range where Bound: Strideable, Bound.Stride : SignedInteger { /// Now that Range is conditionally a collection when Bound: Strideable, /// CountableRange is no longer needed. This is a deprecated initializer /// for any remaining uses of Range(countableRange). @available(*,deprecated: 4.2, message: "CountableRange is now Range. No need to convert any more.") public init(_ other: Range<Bound>) { self = other } /// Creates an instance equivalent to the given `ClosedRange`. /// /// - Parameter other: A closed range to convert to a `Range` instance. /// /// An equivalent range must be representable as an instance of Range<Bound>. /// For example, passing a closed range with an upper bound of `Int.max` /// triggers a runtime error, because the resulting half-open range would /// require an upper bound of `Int.max + 1`, which is not representable as public init(_ other: ClosedRange<Bound>) { let upperBound = other.upperBound.advanced(by: 1) self.init(uncheckedBounds: (lower: other.lowerBound, upper: upperBound)) } } extension Range: RangeExpression { /// Returns the range of indices described by this range expression within /// the given collection. /// /// - Parameter collection: The collection to evaluate this range expression /// in relation to. /// - Returns: A range suitable for slicing `collection`. The returned range /// is *not* guaranteed to be inside the bounds of `collection`. Callers /// should apply the same preconditions to the return value as they would /// to a range provided directly by the user. @_inlineable // FIXME(sil-serialize-all) public func relative<C: Collection>(to collection: C) -> Range<Bound> where C.Index == Bound { return Range(uncheckedBounds: (lower: lowerBound, upper: upperBound)) } } extension Range { /// Returns a copy of this range clamped to the given limiting range. /// /// The bounds of the result are always limited to the bounds of `limits`. /// For example: /// /// let x: Range = 0..<20 /// print(x.clamped(to: 10..<1000)) /// // Prints "10..<20" /// /// If the two ranges do not overlap, the result is an empty range within the /// bounds of `limits`. /// /// let y: Range = 0..<5 /// print(y.clamped(to: 10..<1000)) /// // Prints "10..<10" /// /// - Parameter limits: The range to clamp the bounds of this range. /// - Returns: A new range clamped to the bounds of `limits`. @_inlineable // FIXME(sil-serialize-all) @inline(__always) public func clamped(to limits: Range) -> Range { let lower = limits.lowerBound > self.lowerBound ? limits.lowerBound : limits.upperBound < self.lowerBound ? limits.upperBound : self.lowerBound let upper = limits.upperBound < self.upperBound ? limits.upperBound : limits.lowerBound > self.upperBound ? limits.lowerBound : self.upperBound return Range(uncheckedBounds: (lower: lower, upper: upper)) } } extension Range : CustomStringConvertible { /// A textual representation of the range. @_inlineable // FIXME(sil-serialize-all) public var description: String { return "\(lowerBound)..<\(upperBound)" } } extension Range : CustomDebugStringConvertible { /// A textual representation of the range, suitable for debugging. @_inlineable // FIXME(sil-serialize-all) public var debugDescription: String { return "Range(\(String(reflecting: lowerBound))" + "..<\(String(reflecting: upperBound)))" } } extension Range : CustomReflectable { @_inlineable // FIXME(sil-serialize-all) public var customMirror: Mirror { return Mirror( self, children: ["lowerBound": lowerBound, "upperBound": upperBound]) } } extension Range: Equatable { /// Returns a Boolean value indicating whether two ranges are equal. /// /// Two ranges are equal when they have the same lower and upper bounds. /// That requirement holds even for empty ranges. /// /// let x: Range = 5..<15 /// print(x == 5..<15) /// // Prints "true" /// /// let y: Range = 5..<5 /// print(y == 15..<15) /// // Prints "false" /// /// - Parameters: /// - lhs: A range to compare. /// - rhs: Another range to compare. @_inlineable public static func == (lhs: Range<Bound>, rhs: Range<Bound>) -> Bool { return lhs.lowerBound == rhs.lowerBound && lhs.upperBound == rhs.upperBound } } /// A partial half-open interval up to, but not including, an upper bound. /// /// You create `PartialRangeUpTo` instances by using the prefix half-open range /// operator (prefix `..<`). /// /// let upToFive = ..<5.0 /// /// You can use a `PartialRangeUpTo` instance to quickly check if a value is /// contained in a particular range of values. For example: /// /// upToFive.contains(3.14) // true /// upToFive.contains(6.28) // false /// upToFive.contains(5.0) // false /// /// You can use a `PartialRangeUpTo` instance of a collection's indices to /// represent the range from the start of the collection up to, but not /// including, the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[..<3]) /// // Prints "[10, 20, 30]" @_fixed_layout public struct PartialRangeUpTo<Bound: Comparable> { public let upperBound: Bound @_inlineable // FIXME(sil-serialize-all) public init(_ upperBound: Bound) { self.upperBound = upperBound } } extension PartialRangeUpTo: RangeExpression { @_inlineable // FIXME(sil-serialize-all) @_transparent public func relative<C: Collection>(to collection: C) -> Range<Bound> where C.Index == Bound { return collection.startIndex..<self.upperBound } @_inlineable // FIXME(sil-serialize-all) @_transparent public func contains(_ element: Bound) -> Bool { return element < upperBound } } /// A partial interval up to, and including, an upper bound. /// /// You create `PartialRangeThrough` instances by using the prefix closed range /// operator (prefix `...`). /// /// let throughFive = ...5.0 /// /// You can use a `PartialRangeThrough` instance to quickly check if a value is /// contained in a particular range of values. For example: /// /// throughFive.contains(4.0) // true /// throughFive.contains(5.0) // true /// throughFive.contains(6.0) // false /// /// You can use a `PartialRangeThrough` instance of a collection's indices to /// represent the range from the start of the collection up to, and including, /// the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[...3]) /// // Prints "[10, 20, 30, 40]" @_fixed_layout public struct PartialRangeThrough<Bound: Comparable> { public let upperBound: Bound @_inlineable // FIXME(sil-serialize-all) public init(_ upperBound: Bound) { self.upperBound = upperBound } } extension PartialRangeThrough: RangeExpression { @_inlineable // FIXME(sil-serialize-all) @_transparent public func relative<C: Collection>(to collection: C) -> Range<Bound> where C.Index == Bound { return collection.startIndex..<collection.index(after: self.upperBound) } @_inlineable // FIXME(sil-serialize-all) @_transparent public func contains(_ element: Bound) -> Bool { return element <= upperBound } } /// A partial interval extending upward from a lower bound. /// /// You create `PartialRangeFrom` instances by using the postfix range operator /// (postfix `...`). /// /// let atLeastFive = 5... /// /// You can use a partial range to quickly check if a value is contained in a /// particular range of values. For example: /// /// atLeastFive.contains(4) /// // false /// atLeastFive.contains(5) /// // true /// atLeastFive.contains(6) /// // true /// /// You can use a partial range of a collection's indices to represent the /// range from the partial range's lower bound up to the end of the /// collection. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[3...]) /// // Prints "[40, 50, 60, 70]" /// /// Using a Partial Range as a Sequence /// ----------------------------------- /// /// When a partial range uses integers as its lower and upper bounds, or any /// other type that conforms to the `Strideable` protocol with an integer /// stride, you can use that range in a `for`-`in` loop or with any sequence /// method that doesn't require that the sequence is finite. The elements of /// a partial range are the consecutive values from its lower bound continuing /// upward indefinitely. /// /// func isTheMagicNumber(_ x: Int) -> Bool { /// return x == 3 /// } /// /// for x in 1... { /// if isTheMagicNumber(x) { /// print("\(x) is the magic number!") /// break /// } else { /// print("\(x) wasn't it...") /// } /// } /// // "1 wasn't it..." /// // "2 wasn't it..." /// // "3 is the magic number!" /// /// Because a `PartialRangeFrom` sequence counts upward indefinitely, do not /// use one with methods that read the entire sequence before returning, such /// as `map(_:)`, `filter(_:)`, or `suffix(_:)`. It is safe to use operations /// that put an upper limit on the number of elements they access, such as /// `prefix(_:)` or `dropFirst(_:)`, and operations that you can guarantee /// will terminate, such as passing a closure you know will eventually return /// `true` to `first(where:)`. /// /// In the following example, the `asciiTable` sequence is made by zipping /// together the characters in the `alphabet` string with a partial range /// starting at 65, the ASCII value of the capital letter A. Iterating over /// two zipped sequences continues only as long as the shorter of the two /// sequences, so the iteration stops at the end of `alphabet`. /// /// let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /// let asciiTable = zip(65..., alphabet) /// for (code, letter) in asciiTable { /// print(code, letter) /// } /// // "65 A" /// // "66 B" /// // "67 C" /// // ... /// // "89 Y" /// // "90 Z" /// /// The behavior of incrementing indefinitely is determined by the type of /// `Bound`. For example, iterating over an instance of /// `PartialRangeFrom<Int>` traps when the sequence's next value would be /// above `Int.max`. @_fixed_layout public struct PartialRangeFrom<Bound: Comparable> { public let lowerBound: Bound @_inlineable // FIXME(sil-serialize-all) public init(_ lowerBound: Bound) { self.lowerBound = lowerBound } } extension PartialRangeFrom: RangeExpression { @_inlineable // FIXME(sil-serialize-all) @_transparent public func relative<C: Collection>( to collection: C ) -> Range<Bound> where C.Index == Bound { return self.lowerBound..<collection.endIndex } @_inlineable // FIXME(sil-serialize-all) public func contains(_ element: Bound) -> Bool { return lowerBound <= element } } extension PartialRangeFrom: Sequence where Bound : Strideable, Bound.Stride : SignedInteger { public typealias Element = Bound @_fixed_layout public struct Iterator: IteratorProtocol { @_versioned internal var _current: Bound @_inlineable public init(_current: Bound) { self._current = _current } @_inlineable public mutating func next() -> Bound? { defer { _current = _current.advanced(by: 1) } return _current } } @_inlineable public func makeIterator() -> Iterator { return Iterator(_current: lowerBound) } } extension Comparable { /// Returns a half-open range that contains its lower bound but not its upper /// bound. /// /// Use the half-open range operator (`..<`) to create a range of any type /// that conforms to the `Comparable` protocol. This example creates a /// `Range<Double>` from zero up to, but not including, 5.0. /// /// let lessThanFive = 0.0..<5.0 /// print(lessThanFive.contains(3.14)) // Prints "true" /// print(lessThanFive.contains(5.0)) // Prints "false" /// /// - Parameters: /// - minimum: The lower bound for the range. /// - maximum: The upper bound for the range. @_inlineable // FIXME(sil-serialize-all) @_transparent public static func ..< (minimum: Self, maximum: Self) -> Range<Self> { _precondition(minimum <= maximum, "Can't form Range with upperBound < lowerBound") return Range(uncheckedBounds: (lower: minimum, upper: maximum)) } /// Returns a partial range up to, but not including, its upper bound. /// /// Use the prefix half-open range operator (prefix `..<`) to create a /// partial range of any type that conforms to the `Comparable` protocol. /// This example creates a `PartialRangeUpTo<Double>` instance that includes /// any value less than `5.0`. /// /// let upToFive = ..<5.0 /// /// upToFive.contains(3.14) // true /// upToFive.contains(6.28) // false /// upToFive.contains(5.0) // false /// /// You can use this type of partial range of a collection's indices to /// represent the range from the start of the collection up to, but not /// including, the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[..<3]) /// // Prints "[10, 20, 30]" /// /// - Parameter maximum: The upper bound for the range. @_inlineable // FIXME(sil-serialize-all) @_transparent public static prefix func ..< (maximum: Self) -> PartialRangeUpTo<Self> { return PartialRangeUpTo(maximum) } /// Returns a partial range up to, and including, its upper bound. /// /// Use the prefix closed range operator (prefix `...`) to create a partial /// range of any type that conforms to the `Comparable` protocol. This /// example creates a `PartialRangeThrough<Double>` instance that includes /// any value less than or equal to `5.0`. /// /// let throughFive = ...5.0 /// /// throughFive.contains(4.0) // true /// throughFive.contains(5.0) // true /// throughFive.contains(6.0) // false /// /// You can use this type of partial range of a collection's indices to /// represent the range from the start of the collection up to, and /// including, the partial range's upper bound. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[...3]) /// // Prints "[10, 20, 30, 40]" /// /// - Parameter maximum: The upper bound for the range. @_inlineable // FIXME(sil-serialize-all) @_transparent public static prefix func ... (maximum: Self) -> PartialRangeThrough<Self> { return PartialRangeThrough(maximum) } /// Returns a partial range extending upward from a lower bound. /// /// Use the postfix range operator (postfix `...`) to create a partial range /// of any type that conforms to the `Comparable` protocol. This example /// creates a `PartialRangeFrom<Double>` instance that includes any value /// greater than or equal to `5.0`. /// /// let atLeastFive = 5.0... /// /// atLeastFive.contains(4.0) // false /// atLeastFive.contains(5.0) // true /// atLeastFive.contains(6.0) // true /// /// You can use this type of partial range of a collection's indices to /// represent the range from the partial range's lower bound up to the end /// of the collection. /// /// let numbers = [10, 20, 30, 40, 50, 60, 70] /// print(numbers[3...]) /// // Prints "[40, 50, 60, 70]" /// /// - Parameter minimum: The lower bound for the range. @_inlineable // FIXME(sil-serialize-all) @_transparent public static postfix func ... (minimum: Self) -> PartialRangeFrom<Self> { return PartialRangeFrom(minimum) } } /// A range expression that represents the entire range of a collection. /// /// You can use the unbounded range operator (`...`) to create a slice of a /// collection that contains all of the collection's elements. Slicing with an /// unbounded range is essentially a conversion of a collection instance into /// its slice type. /// /// For example, the following code declares `levenshteinDistance(_:_:)`, a /// function that calculates the number of changes required to convert one /// string into another. `levenshteinDistance(_:_:)` uses `Substring`, a /// string's slice type, for its parameters. /// /// func levenshteinDistance(_ s1: Substring, _ s2: Substring) -> Int { /// if s1.isEmpty { return s2.count } /// if s2.isEmpty { return s1.count } /// /// let cost = s1.first == s2.first ? 0 : 1 /// /// return min( /// levenshteinDistance(s1.dropFirst(), s2) + 1, /// levenshteinDistance(s1, s2.dropFirst()) + 1, /// levenshteinDistance(s1.dropFirst(), s2.dropFirst()) + cost) /// } /// /// To call `levenshteinDistance(_:_:)` with two strings, use an unbounded /// range in each string's subscript to convert it to a `Substring`. /// /// let word1 = "grizzly" /// let word2 = "grisly" /// let distance = levenshteinDistance(word1[...], word2[...]) /// // distance == 2 @_fixed_layout // FIXME(sil-serialize-all) public enum UnboundedRange_ { // FIXME: replace this with a computed var named `...` when the language makes // that possible. /// Creates an unbounded range expression. /// /// The unbounded range operator (`...`) is valid only within a collection's /// subscript. @_inlineable // FIXME(sil-serialize-all) public static postfix func ... (_: UnboundedRange_) -> () { fatalError("uncallable") } } /// The type of an unbounded range operator. public typealias UnboundedRange = (UnboundedRange_)->() extension Collection { /// Accesses the contiguous subrange of the collection's elements specified /// by a range expression. /// /// The range expression is converted to a concrete subrange relative to this /// collection. For example, using a `PartialRangeFrom` range expression /// with an array accesses the subrange from the start of the range /// expression until the end of the array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2...] /// print(streetsSlice) /// // ["Channing", "Douglas", "Evarts"] /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. This example searches `streetsSlice` for one /// of the strings in the slice, and then uses that index in the original /// array. /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// print(streets[index!]) /// // "Evarts" /// /// Always use the slice's `startIndex` property instead of assuming that its /// indices start at a particular value. Attempting to access an element by /// using an index outside the bounds of the slice's indices may result in a /// runtime error, even if that index is valid for the original collection. /// /// print(streetsSlice.startIndex) /// // 2 /// print(streetsSlice[2]) /// // "Channing" /// /// print(streetsSlice[0]) /// // error: Index out of bounds /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) @_inlineable public subscript<R: RangeExpression>(r: R) -> SubSequence where R.Bound == Index { return self[r.relative(to: self)] } @_inlineable public subscript(x: UnboundedRange) -> SubSequence { return self[startIndex...] } } extension MutableCollection { @_inlineable public subscript<R: RangeExpression>(r: R) -> SubSequence where R.Bound == Index { get { return self[r.relative(to: self)] } set { self[r.relative(to: self)] = newValue } } @_inlineable // FIXME(sil-serialize-all) public subscript(x: UnboundedRange) -> SubSequence { get { return self[startIndex...] } set { self[startIndex...] = newValue } } } // TODO: enhance RangeExpression to make this generic and available on // any expression. extension Range { /// Returns a Boolean value indicating whether this range and the given range /// contain an element in common. /// /// This example shows two overlapping ranges: /// /// let x: Range = 0..<20 /// print(x.overlaps(10...1000)) /// // Prints "true" /// /// Because a half-open range does not include its upper bound, the ranges /// in the following example do not overlap: /// /// let y = 20..<30 /// print(x.overlaps(y)) /// // Prints "false" /// /// - Parameter other: A range to check for elements in common. /// - Returns: `true` if this range and `other` have at least one element in /// common; otherwise, `false`. @_inlineable public func overlaps(_ other: Range<Bound>) -> Bool { return (!other.isEmpty && self.contains(other.lowerBound)) || (!self.isEmpty && other.contains(self.lowerBound)) } @_inlineable public func overlaps(_ other: ClosedRange<Bound>) -> Bool { return self.contains(other.lowerBound) || (!self.isEmpty && other.contains(self.lowerBound)) } } @available(*, deprecated, renamed: "Range") public typealias CountableRange<Bound: Comparable> = Range<Bound>
apache-2.0
41fbdfcacfae73ee17c1531fab48a31d
34.427438
80
0.645662
4.143065
false
false
false
false
jkereako/autocomplete-text-field
Source/TableViewController.swift
1
1378
// // ViewController.swift // AutocompleteTextField // // Created by Jeffrey Kereakoglow on 12/22/15. // Copyright © 2015 Alexis Digital. All rights reserved. // import UIKit class TableViewController: UITableViewController { @IBOutlet weak var nameField: AutocompleteTextField? @IBOutlet weak var emailField: AutocompleteTextField? override func viewDidLoad() { super.viewDidLoad() guard let name = nameField, let email = emailField else { assertionFailure("Name field is nil. Did you forget to wire it up in Storyboard Builder?") return } name.autoCompleteDataSource = DataSource() name.autoCompleteDelegate = self name.suggestionLabelPosition = CGPointMake(0, -0.5) } } // MARK: - UITextFieldDelegate extension TableViewController: UITextFieldDelegate { func textFieldShouldEndEditing(textField: UITextField) -> Bool { return true } // Dismiss the keyboard when the user hits the return key func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } extension TableViewController: AutocompleteDelegate { func textfield(textfield: AutocompleteTextField, didAcceptSuggestion suggestion: String) { let dataSource = DataSource() if let rawText = dataSource.rawTextForSuggestion(suggestion) { textfield.text = rawText } } }
mit
3da1bf095e7096b4c7592e46a3bdd45e
24.981132
96
0.737836
5.0625
false
false
false
false
macmade/AtomicKit
AtomicKit/Source/DispatchedMutableDictionary.swift
1
4712
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2017 Jean-David Gadina - www.xs-labs.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 Cocoa /** * Thread-safe value wrapper for `NSMutableDictionary`, using dispatch queues to * achieve synchronization. * This class is KVO-compliant. You may observe its `value` property to be * notified of changes. This is applicable to Cocoa bindings. * * - seealso: DispatchedValueWrapper */ @objc public class DispatchedMutableDictionary: NSObject, DispatchedValueWrapper { /** * The wrapped value type, `NSMutableDictionary`. */ public typealias ValueType = NSMutableDictionary? /** * Initializes a dispatched value object. * This initializer will use the main queue for synchronization. * * - parameter value: The initial value. */ public required convenience init( value: ValueType ) { self.init( value: value, queue: DispatchQueue.main ) } /** * Initializes a dispatched value object. * * - parameter value: The initial `NSMutableDictionary` value. * - parameter queue: The queue to use to achieve synchronization. */ public required init( value: ValueType = nil, queue: DispatchQueue = DispatchQueue.main ) { self._value = DispatchedValue< ValueType >( value: value, queue: queue ) } /** * The wrapped `NSMutableDictionary` value. * This property is KVO-compliant. */ @objc public dynamic var value: ValueType { get { return self._value.get() } set( value ) { self.willChangeValue( forKey: "value" ) self._value.set( value ) self.didChangeValue( forKey: "value" ) } } /** * Atomically gets the wrapped `NSMutableDictionary` value. * The getter will be executed on the queue specified in the initialzer. * * - returns: The actual `NSMutableDictionary` value. */ public func get() -> ValueType { return self.value } /** * Atomically sets the wrapped `NSMutableDictionary` value. * The setter will be executed on the queue specified in the initialzer. * * -parameter value: The `NSMutableDictionary` value to set. */ public func set( _ value: ValueType ) { self.value = value } /** * Atomically executes a closure on the wrapped `NSMutableDictionary` value. * The closure will be passed the actual value of the wrapped * `NSMutableDictionary` value, and is guaranteed to be executed atomically, * on the queue specified in the initialzer. * * -parameter closure: The close to execute. */ public func execute( closure: ( ValueType ) -> Swift.Void ) { self._value.execute( closure: closure ) } /** * Atomically executes a closure on the wrapped `NSMutableDictionary` value, * returning some value. * The closure will be passed the actual value of the wrapped * `NSMutableDictionary` value, and is guaranteed to be executed atomically, * on the queue specified in the initialzer. * * -parameter closure: The close to execute, returning some value. */ public func execute< R >( closure: ( ValueType ) -> R ) -> R { return self._value.execute( closure: closure ) } private var _value: DispatchedValue< ValueType > }
mit
9320c72d5c704745003dd312d3742976
33.144928
93
0.633913
4.92372
false
false
false
false
vermont42/Conjugar
Conjugar/World.swift
1
4162
// // World.swift // Conjugar // // Created by Joshua Adams on 1/15/19. // Enhanced by Stephen Celis on 1/16/19. // Copyright © 2019 Josh Adams. All rights reserved. // import Foundation import SwiftUI #if targetEnvironment(simulator) var Current = World.simulator #else var Current = World.device #endif class World: ObservableObject { @Published var analytics: AnalyticsServiceable @Published var reviewPrompter: ReviewPromptable @Published var gameCenter: GameCenterable @Published var settings: Settings @Published var quiz: Quiz @Published var session: URLSession @Published var communGetter: CommunGetter @Published var locale: Locale @Published var parentViewController: UIViewController? private static let fakeRatingsCount = 42 init( analytics: AnalyticsServiceable, reviewPrompter: ReviewPromptable, gameCenter: GameCenterable, settings: Settings, quiz: Quiz, session: URLSession, communGetter: CommunGetter, locale: Locale ) { self.analytics = analytics self.reviewPrompter = reviewPrompter self.gameCenter = gameCenter self.settings = settings self.quiz = quiz self.session = session self.communGetter = communGetter self.locale = locale } static let device: World = { let settings = Settings(getterSetter: UserDefaultsGetterSetter()) let gameCenter = GameCenter.shared return World( analytics: AWSAnalyticsService(), reviewPrompter: ReviewPrompter(), gameCenter: gameCenter, settings: settings, quiz: Quiz(settings: settings, gameCenter: gameCenter, shouldShuffle: true), session: URLSession.shared, communGetter: CloudCommunGetter(), locale: RealLocale() ) }() static let simulator: World = { let settings = Settings(getterSetter: UserDefaultsGetterSetter()) let gameCenter = TestGameCenter() return World( analytics: TestAnalyticsService(), reviewPrompter: TestReviewPrompter(), gameCenter: gameCenter, settings: settings, quiz: Quiz(settings: settings, gameCenter: gameCenter, shouldShuffle: true), session: URLSession.stubSession(ratingsCount: fakeRatingsCount), communGetter: StubCommunGetter(), locale: StubLocale(languageCode: "en", regionCode: "US") ) }() static let unitTest: World = { let settings = Settings(getterSetter: DictionaryGetterSetter()) let gameCenter = TestGameCenter() return World( analytics: TestAnalyticsService(), reviewPrompter: TestReviewPrompter(), gameCenter: gameCenter, settings: settings, quiz: Quiz(settings: settings, gameCenter: gameCenter, shouldShuffle: false), session: URLSession.stubSession(ratingsCount: fakeRatingsCount), communGetter: StubCommunGetter(), locale: StubLocale() ) }() static func uiTest(launchArguments arguments: [String]) -> World { let region: Region if arguments.contains(Region.spain.rawValue) { region = .spain } else if arguments.contains(Region.latinAmerica.rawValue) { region = .latinAmerica } else { region = Settings.regionDefault } let difficulty: Difficulty if arguments.contains(Difficulty.difficult.rawValue) { difficulty = .difficult } else if arguments.contains(Difficulty.moderate.rawValue) { difficulty = .moderate } else if arguments.contains(Difficulty.easy.rawValue) { difficulty = .easy } else { difficulty = Settings.difficultyDefault } let dictionary = [Settings.regionKey: region.rawValue, Settings.difficultyKey: difficulty.rawValue] let settings = Settings(getterSetter: DictionaryGetterSetter(dictionary: dictionary)) let gameCenter = TestGameCenter() return World( analytics: TestAnalyticsService(), reviewPrompter: TestReviewPrompter(), gameCenter: gameCenter, settings: settings, quiz: Quiz(settings: settings, gameCenter: gameCenter, shouldShuffle: false), session: URLSession.stubSession(ratingsCount: fakeRatingsCount), communGetter: StubCommunGetter(), locale: StubLocale() ) } }
agpl-3.0
43261715ad11c363139dfc12d58bd69b
29.595588
103
0.709205
4.832753
false
true
false
false
lemonkey/iOS
WatchKit/_Apple/ListerforAppleWatchiOSandOSX/Swift/ListerKitOSX/CheckBox.swift
1
1546
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A layer-backed custom check box that is IBDesignable and IBInspectable. */ import Cocoa @IBDesignable public class CheckBox: NSButton { // MARK: Properties @IBInspectable public var tintColor: NSColor { get { return NSColor(CGColor: checkBoxLayer.tintColor)! } set { checkBoxLayer.tintColor = newValue.CGColor } } @IBInspectable public var isChecked: Bool { get { return checkBoxLayer.isChecked } set { checkBoxLayer.isChecked = newValue } } private var checkBoxLayer: CheckBoxLayer { return layer as! CheckBoxLayer } override public var intrinsicContentSize: NSSize { return NSSize(width: 40, height: 40) } // MARK: View Life Cycle override public func awakeFromNib() { super.awakeFromNib() wantsLayer = true layer = CheckBoxLayer() layer!.setNeedsDisplay() } // MARK: Events override public func mouseDown(event: NSEvent) { isChecked = !isChecked cell()!.performClick(self) } override public func viewDidChangeBackingProperties() { super.viewDidChangeBackingProperties() if let window = window { layer?.contentsScale = window.backingScaleFactor } } }
mit
864a3bdbd9913395c9baae5f8fdc055f
22.409091
75
0.593912
5.594203
false
false
false
false
google/iosched-ios
Source/IOsched/Screens/Map/MapCardView.swift
1
7954
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import MaterialComponents protocol MapCardViewDelegate: class { func viewDidTapDismiss() } class MapCardView: UIView { private enum Constants { static let titleFont = ProductSans.regular.style(.callout) static let titleColor = UIColor(red: 20 / 255, green: 21 / 255, blue: 24 / 255, alpha: 1) static let detailFont = ProductSans.regular.style(.footnote) static let detailColor = UIColor(hex: 0x5f6368) static let cornerRadius = CGFloat(8) static let cardElevation = ShadowElevation(rawValue: 4) static let buttonTextColor = UIColor(red: 0.34, green: 0.46, blue: 0.96, alpha: 1.0) static let dismissButtonTitle = NSLocalizedString("Dismiss", comment: "Button title that will dismiss info text about a map location.") } private lazy var titleLabel: UILabel = self.setupTitleLabel() private lazy var detailTextView: UITextView = self.setupDetailTextView() private lazy var detailTextViewHeightConstraint = NSLayoutConstraint(item: detailTextView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0) weak var delegate: MapCardViewDelegate? var title: String? { didSet { titleLabel.text = composite(title: title, subtitle: subtitle) } } var subtitle: String? { didSet { titleLabel.text = composite(title: title, subtitle: subtitle) } } private func composite(title: String?, subtitle: String?) -> String { switch (title, subtitle) { case (nil, nil): return "" case (nil, let value?): return value case (let value?, nil): return value case (let lhs?, let rhs?): return lhs + ": " + rhs } } var details: String? { didSet { setHeightForTextView(with: details) guard let details = details else { detailTextView.attributedText = nil return } let attributedString = InfoDetail.attributedText(detail: details) detailTextView.attributedText = attributedString } } override class var layerClass: AnyClass { return MDCShadowLayer.self } var shadowLayer: MDCShadowLayer { return self.layer as! MDCShadowLayer } override init(frame: CGRect) { super.init(frame: frame) setupViews() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupTitleLabel() -> UILabel { let titleLabel = UILabel() titleLabel.font = Constants.titleFont titleLabel.textColor = Constants.titleColor titleLabel.enableAdjustFontForContentSizeCategory() titleLabel.numberOfLines = 0 return titleLabel } func setupDetailTextView() -> UITextView { let detailTextView = UITextView() detailTextView.textColor = Constants.detailColor detailTextView.isEditable = false detailTextView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0) detailTextView.textContainer.lineFragmentPadding = 0 if #available(iOS 10, *) { detailTextView.adjustsFontForContentSizeCategory = true } return detailTextView } func setupDismissButton() -> MDCFlatButton { let dismissButton = MDCFlatButton() dismissButton.setTitleColor(Constants.buttonTextColor, for: .normal) dismissButton.setTitle(Constants.dismissButtonTitle, for: .normal) dismissButton.isUppercaseTitle = false dismissButton.sizeToFit() dismissButton.addTarget(self, action: #selector(dismiss), for: .touchUpInside) return dismissButton } func setupViews() { backgroundColor = .white titleLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(titleLabel) detailTextView.translatesAutoresizingMaskIntoConstraints = false addSubview(detailTextView) let dismissButton = self.setupDismissButton() dismissButton.translatesAutoresizingMaskIntoConstraints = false addSubview(dismissButton) let views: [String: UIView] = ["title": titleLabel, "details": detailTextView, "dismiss": dismissButton] var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[title]-20-|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[details]-20-|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[dismiss]-20-|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[title]-16-[details]-14-[dismiss]-20-|", options: [], metrics: nil, views: views) NSLayoutConstraint.activate(constraints) detailTextViewHeightConstraint.isActive = true layer.cornerRadius = Constants.cornerRadius shadowLayer.elevation = Constants.cardElevation } override func layoutSubviews() { super.layoutSubviews() let maxTitleLabelWidth = bounds.size.width - 28 if titleLabel.preferredMaxLayoutWidth != maxTitleLabelWidth { titleLabel.preferredMaxLayoutWidth = maxTitleLabelWidth titleLabel.setNeedsLayout() } } private func setHeightForTextView(with detail: String?) { guard let detail = detail else { detailTextViewHeightConstraint.constant = 0 return } guard let attributedString = InfoDetail.attributedText(detail: detail) else { detailTextViewHeightConstraint.constant = 0 return } let inset: CGFloat = 40 let maxHeight: CGFloat = 300 let boundingSize = CGSize(width: frame.size.width - inset, height: .greatestFiniteMagnitude) let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesDeviceMetrics, .usesFontLeading] let textRect = attributedString.boundingRect(with: boundingSize, options: options, context: nil) let totalHeight = textRect.size.height.rounded(.up) + detailTextView.textContainerInset.top + detailTextView.textContainerInset.bottom let clampedHeight = min(totalHeight, maxHeight) detailTextViewHeightConstraint.constant = clampedHeight detailTextView.isScrollEnabled = totalHeight > maxHeight } @objc func dismiss() { delegate?.viewDidTapDismiss() } }
apache-2.0
4978d7dd5212a2e0a3bcd8e8d730cbc9
36.518868
116
0.616922
5.605356
false
false
false
false
salmojunior/TMDb
TMDb/TMDb/Source/Provider/API/APIProvider.swift
1
1588
// // APIProvider.swift // TMDb // // Created by SalmoJunior on 13/05/17. // Copyright © 2017 Salmo Junior. All rights reserved. // import Foundation struct APIProvider { // MARK: - Properties /// API version private static let apiVersion = "3" /// Auth header Key private static let authKey = "api_key" private static let authValue = "1f54bd990f1cdfb230adb312546d765d" /// Language Key private static let languageKey = "language" /// Shared Networking Provider used to access API Services static var sharedProvider: NetworkingProvider { let urlSession = URLSession(configuration: URLSessionConfiguration.ephemeral) guard let baseURL = URL(string: APIProvider.baseURL()) else { fatalError("Base URL should not be empty") } return NetworkingProvider(session: urlSession, baseURL: baseURL) } // MARK: - Public Static Functions /// API Base URL /// /// - Returns: return baseURL private static func baseURL() -> String { return "https://api.themoviedb.org/" + apiVersion } /// Base Header for authentication /// /// - Returns: Dictionary<String, String> static func baseParameters() -> NetworkingParameters { var queryParameters = [authKey:authValue] if let appLang = Locale.current.languageCode { queryParameters[languageKey] = appLang } let parameters: NetworkingParameters = (bodyParameters: nil, queryParameters: queryParameters) return parameters } }
mit
1c8005843c16776d51fb05262984b27a
29.519231
114
0.649023
4.794562
false
false
false
false
adrfer/swift
test/SILOptimizer/devirt_covariant_return.swift
3
8195
// RUN: %target-swift-frontend -O -primary-file %s -emit-sil -sil-inline-threshold 1000 -sil-verify-all | FileCheck %s // Make sure that we can dig all the way through the class hierarchy and // protocol conformances with covariant return types correctly. The verifier // should trip if we do not handle things correctly. // // As a side-test it also checks if all allocs can be promoted to the stack. // CHECK-LABEL: sil hidden @_TF23devirt_covariant_return6driverFT_T_ : $@convention(thin) () -> () { // CHECK: bb0 // CHECK: alloc_ref [stack] // CHECK: alloc_ref [stack] // CHECK: alloc_ref [stack] // CHECK: function_ref @unknown1a : $@convention(thin) () -> () // CHECK: apply // CHECK: function_ref @defenestrate : $@convention(thin) () -> () // CHECK: apply // CHECK: function_ref @unknown2a : $@convention(thin) () -> () // CHECK: apply // CHECK: apply // CHECK: function_ref @unknown3a : $@convention(thin) () -> () // CHECK: apply // CHECK: apply // CHECK: dealloc_ref [stack] // CHECK: dealloc_ref [stack] // CHECK: dealloc_ref [stack] // CHECK: tuple // CHECK: return @_silgen_name("unknown1a") func unknown1a() -> () @_silgen_name("unknown1b") func unknown1b() -> () @_silgen_name("unknown2a") func unknown2a() -> () @_silgen_name("unknown2b") func unknown2b() -> () @_silgen_name("unknown3a") func unknown3a() -> () @_silgen_name("unknown3b") func unknown3b() -> () @_silgen_name("defenestrate") func defenestrate() -> () class B<T> { // We do not specialize typealias's correctly now. //typealias X = B func doSomething() -> B<T> { unknown1a() return self } // See comment in protocol P //class func doSomethingMeta() { // unknown1b() //} func doSomethingElse() { defenestrate() } } class B2<T> : B<T> { // When we have covariance in protocols, change this to B2. // We do not specialize typealias correctly now. //typealias X = B override func doSomething() -> B2<T> { unknown2a() return self } // See comment in protocol P //override class func doSomethingMeta() { // unknown2b() //} } class B3<T> : B2<T> { override func doSomething() -> B3<T> { unknown3a() return self } } func WhatShouldIDo<T>(b : B<T>) -> B<T> { b.doSomething().doSomethingElse() return b } func doSomethingWithB<T>(b : B<T>) { } struct S {} func driver() -> () { let b = B<S>() let b2 = B2<S>() let b3 = B3<S>() WhatShouldIDo(b) WhatShouldIDo(b2) WhatShouldIDo(b3) } driver() class Payload { let value: Int32 init(_ n: Int32) { value = n } func getValue() -> Int32 { return value } } final class Payload1: Payload { override init(_ n: Int32) { super.init(n) } } class C { func doSomething() -> Payload? { return Payload(1) } } final class C1:C { // Override base method, but return a non-optional result override func doSomething() -> Payload { return Payload(2) } } final class C2:C { // Override base method, but return a non-optional result of a type, // which is derived from the expected type. override func doSomething() -> Payload1 { return Payload1(2) } } // Check that the Optional return value from doSomething // gets properly unwrapped into a Payload object and then further // devirtualized. // CHECK-LABEL: sil hidden @_TF23devirt_covariant_return7driver1FCS_2C1Vs5Int32 : // CHECK: integer_literal $Builtin.Int32, 2 // CHECK: struct $Int32 (%{{.*}} : $Builtin.Int32) // CHECK-NOT: class_method // CHECK-NOT: function_ref // CHECK: return func driver1(c: C1) -> Int32 { return c.doSomething().getValue() } // Check that the Optional return value from doSomething // gets properly unwrapped into a Payload object and then further // devirtualized. // CHECK-LABEL: sil hidden @_TF23devirt_covariant_return7driver3FCS_1CVs5Int32 : // CHECK: bb{{[0-9]+}}(%{{[0-9]+}} : $C2): // CHECK-NOT: bb{{.*}}: // check that for C2, we convert the non-optional result into an optional and then cast. // CHECK: enum $Optional // CHECK-NEXT: upcast // CHECK: return func driver3(c: C) -> Int32 { return c.doSomething()!.getValue() } public class Bear { public init?(fail: Bool) { if fail { return nil } } // Check that devirtualizer can handle convenience initializers, which have covariant optional // return types. // CHECK-LABEL: sil @_TFC23devirt_covariant_return4Bearc // CHECK: checked_cast_br [exact] %{{.*}} : $Bear to $PolarBear // CHECK: upcast %{{.*}} : $Optional<PolarBear> to $Optional<Bear> // CHECK: } public convenience init?(delegateFailure: Bool, failAfter: Bool) { self.init(fail: delegateFailure) if failAfter { return nil } } } final class PolarBear: Bear { override init?(fail: Bool) { super.init(fail: fail) } init?(chainFailure: Bool, failAfter: Bool) { super.init(fail: chainFailure) if failAfter { return nil } } } public class D { let v: Int32 init(_ n: Int32) { v = n } } public class D1 : D { public func foo() -> D? { return nil } public func boo() -> Int32 { return foo()!.v } } let sD = D(0) public class D2: D1 { // Override base method, but return a non-optional result override public func foo() -> D { return sD } } // Check that the boo call gets properly devirtualized and that // that D2.foo() is inlined thanks to this. // CHECK-LABEL: sil hidden @_TF23devirt_covariant_return7driver2FCS_2D2Vs5Int32 // CHECK-NOT: class_method // CHECK: checked_cast_br [exact] %{{.*}} : $D1 to $D2 // CHECK: bb2 // CHECK: global_addr // CHECK: load // CHECK: ref_element_addr // CHECK: bb3 // CHECK: class_method // CHECK: } func driver2(d: D2) -> Int32 { return d.boo() } class AA { } class BB : AA { } class CCC { @inline(never) func foo(b: BB) -> (AA, AA) { return (b, b) } } class DDD : CCC { @inline(never) override func foo(b: BB) -> (BB, BB) { return (b, b) } } class EEE : CCC { @inline(never) override func foo(b: BB) -> (AA, AA) { return (b, b) } } // Check that c.foo() is devirtualized, because the optimizer can handle the casting the return type // correctly, i.e. it can cast (BBB, BBB) into (AAA, AAA) // CHECK-LABEL: sil hidden @_TF23devirt_covariant_return37testDevirtOfMethodReturningTupleTypesFTCS_3CCC1bCS_2BB_TCS_2AAS2__ // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $CCC // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $DDD // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $EEE // CHECK: class_method // CHECK: } func testDevirtOfMethodReturningTupleTypes(c: CCC, b: BB) -> (AA, AA) { return c.foo(b) } class AAAA { } class BBBB : AAAA { } class CCCC { let a: BBBB var foo : (AAAA, AAAA) { @inline(never) get { return (a, a) } } init(x: BBBB) { a = x } } class DDDD : CCCC { override var foo : (BBBB, BBBB) { @inline(never) get { return (a, a) } } } // Check that c.foo OSX 10.9 be devirtualized, because the optimizer can handle the casting the return type // correctly, i.e. it cannot cast (BBBB, BBBB) into (AAAA, AAAA) // CHECK-LABEL: sil hidden @_TF23devirt_covariant_return38testDevirtOfMethodReturningTupleTypes2FCS_4CCCCTCS_4AAAAS1__ // CHECK: checked_cast_br [exact] %{{.*}} : $CCCC to $CCCC // CHECK: checked_cast_br [exact] %{{.*}} : $CCCC to $DDDD // CHECK: class_method // CHECK: } func testDevirtOfMethodReturningTupleTypes2(c: CCCC) -> (AAAA, AAAA) { return c.foo } public class F { @inline(never) public func foo() -> (F?, Int)? { return (F(), 1) } } public class G: F { @inline(never) override public func foo() -> (G?, Int)? { return (G(), 2) } } public class H: F { @inline(never) override public func foo() -> (H?, Int)? { return nil } } // Check devirtualization of methods with optional results, where // optional results need to be casted. // CHECK-LABEL: sil @{{.*}}testOverridingMethodWithOptionalResult // CHECK: checked_cast_br [exact] %{{.*}} : $F to $F // CHECK: checked_cast_br [exact] %{{.*}} : $F to $G // CHECK: switch_enum // CHECK: checked_cast_br [exact] %{{.*}} : $F to $H // CHECK: switch_enum public func testOverridingMethodWithOptionalResult(f: F) -> (F?, Int)? { return f.foo() }
apache-2.0
0be2d1400c8baa258b8b4cbc00f4a24f
21.955182
124
0.639048
3.173896
false
false
false
false
wendyabrantes/WAActivityIndicatorView
WAActivityIndicatorView/WAActivityIndicatorView.swift
1
1978
// // WAActivityIndicatorView.swift // WAActivityIndicatorViewExample // // Created by Wendy Abrantes on 03/10/2015. // Copyright © 2015 ABRANTES DIGITAL LTD. All rights reserved. // import UIKit protocol WAActivityIndicatorProtocol { func setupAnimationInLayer(layer: CALayer, size: CGFloat, tintColor: UIColor); } enum ActivityIndicatorType{ case Pulse case ThreeDotsScale case DotTriangle case GridDots func animation() -> WAActivityIndicatorProtocol { switch self { case .Pulse: return PulseAnimation(); case .ThreeDotsScale: return ThreeDotsScaleAnimation(); case .DotTriangle: return DotTriangleAnimation(); case .GridDots: return GridDotsAnimation(); } } } class WAActivityIndicatorView: UIView { var indicatorType: ActivityIndicatorType; private var indicatorSize : CGFloat = 40.0 private var _tintColor = UIColor.whiteColor() private var _isAnimating = false; init(frame: CGRect, indicatorType : ActivityIndicatorType, tintColor: UIColor, indicatorSize: CGFloat) { self.indicatorType = indicatorType self.indicatorSize = indicatorSize _tintColor = tintColor super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupAnimation(){ layer.sublayers = nil let animation : WAActivityIndicatorProtocol = indicatorType.animation() animation.setupAnimationInLayer(layer, size: indicatorSize, tintColor: _tintColor) layer.speed = 0.0 } func startAnimating(){ if layer.sublayers == nil { setupAnimation() } layer.speed = 1.0 _isAnimating = true } func stopAnimating(){ layer.speed = 0.0 _isAnimating = false } }
mit
f42fa97b7a08bb80ead901db1b3fdb95
22.258824
108
0.632271
5.082262
false
false
false
false
J3D1-WARR10R/WikiRaces
WKRUIKit/WKRUIKit/Elements/WKRUILabel.swift
2
1041
// // WKRUILabel.swift // WKRUIKit // // Created by Andrew Finke on 8/5/17. // Copyright © 2017 Andrew Finke. All rights reserved. // import UIKit final public class WKRUILabel: UILabel { // MARK: - Properties private let spacing: Double public override var text: String? { didSet { if let text = text?.uppercased() { super.attributedText = NSAttributedString(string: text, spacing: spacing) } else { super.attributedText = nil } } } // MARK: - Initialization - public init(spacing: Double = 2.0) { self.spacing = spacing super.init(frame: .zero) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle - public override func layoutSubviews() { super.layoutSubviews() textColor = .wkrTextColor(for: traitCollection) } }
mit
6038f3741599d4a66863dd4eeee6dfa5
22.636364
75
0.555769
4.60177
false
false
false
false
exyte/Macaw-Examples
PeriodicTable/UI/Main/PeriodicTable.swift
1
6794
// // PeriodicTable.swift // Example // // Created by Yuri Strot on 9/14/16. // Copyright © 2016 Exyte. All rights reserved. // import UIKit import Macaw class PeriodicTable: MacawView { private static let elementSize = Size(w: 120, h: 160) private static let elementSpace = Size(w: 20, h: 20) private static let gaps = Size(w: 275, h: 240) private static let screen = UIScreen.main.bounds private static let content = Size(w: 18 * elementSize.w + 17 * elementSpace.w, h: 10 * elementSize.h + 9 * elementSpace.h) private static let scale = 1.0 / 3.0 private let elements: [Node] private var showTable = true private var animation: Animation? private static let table: [Element] = PeriodicTable.fillTable() required init?(coder aDecoder: NSCoder) { self.elements = PeriodicTable.fillElements() super.init(node: Group(contents: elements), coder: aDecoder) self.backgroundColor = UIColor.black } private static func fillElements() -> [Node] { var elements: [Node] = [] for (i, element) in PeriodicTable.table.enumerated() { drand48() let group = Group(contents: [ Shape(form: Rect(w: elementSize.w, h: elementSize.h), fill: getColor(element)), Text(text: "\(i+1)", font: Font(name: "Helvetica", size: 12), fill: Color(val: 0xc1f7f7), align: .max, place: .move(dx: elementSize.w * 5 / 6, dy: elementSize.h / 8)), Text(text: element.symbol, font: Font(name: "Helvetica Bold", size: 60), fill: Color(val: 0xc1f7f7), align: .mid, place: .move(dx: elementSize.w / 2, dy: elementSize.h / 4)), Text(text: element.name, font: Font(name: "Helvetica", size: 12), fill: Color(val: 0xc1f7f7), align: .mid, place: .move(dx: elementSize.w / 2, dy: 121)), Text(text: element.mass, font: Font(name: "Helvetica", size: 12), fill: Color(val: 0xc1f7f7), align: .mid, place: .move(dx: elementSize.w / 2, dy: 133)) ]) elements.append(group) } let data = PeriodicTable.gridData() for (i, node) in elements.enumerated() { node.place = data[i] } return elements } private static func gridData() -> [Transform] { var result: [Transform] = [] result.append(contentsOf: gridLayer(5)) result.append(contentsOf: gridLayer(4)) result.append(contentsOf: gridLayer(3)) result.append(contentsOf: gridLayer(2)) result.append(contentsOf: gridLayer(1)) return result } func start() { var animations = [Animation]() for (i, node) in elements.enumerated() { let layer = (i % 25) let sign = ((layer % 5) % 2) == 0 ? 1.0 : -1.0 let sign2 = (i / 25) % 2 == 0 ? 1.0 : -1.0 let newPlace = node.place.concat(with: .move(dx: 0, dy: sign * sign2 * 300)) let anim = node.placeVar.animation(from: node.place, to: newPlace, during: 10.0).easing(.linear) animations.append(anim) } animation = animations.combine() animation?.play() } static func gridLayer(_ scale: Double) -> [Transform] { var result: [Transform] = [] let xFull = 5 * elementSize.w + 4 * gaps.w let yFull = 5 * elementSize.h + 4 * gaps.h let xShift = (xFull / scale - Double(screen.width)) / 2 let yShift = (yFull / scale - Double(screen.height)) / 2 for i in 0...4 { for j in 0...4 { let dx = Double(j) * (gaps.w + elementSize.w) let dy = Double(i) * (gaps.h + elementSize.h) let pos = Transform.move(dx: -xShift, dy: -yShift).scale(sx: 1 / scale, sy: 1 / scale).move(dx: dx, dy: dy) result.append(pos) } } return result } static func getPos(row: Int, column: Int) -> Transform { let dx = Double(column) * (elementSize.w + elementSpace.w) let dy = Double(row) * (elementSize.h + elementSpace.h) let shift = (Double(screen.width) - content.w * scale) / 2 return Transform.move(dx: shift, dy: elementSize.h * scale).scale(sx: scale, sy: scale).move(dx: dx, dy: dy) } static func fillTable() -> [Element] { let tableUrl = Bundle.main.url(forResource: "table", withExtension: "json") let tableData = NSData(contentsOf: tableUrl!) do { let elementsJson = try JSONSerialization.jsonObject(with: tableData! as Data, options: .allowFragments) as! NSArray var elements: [Element] = [] elementsJson.forEach { json in guard let dictionary = json as? [String: AnyObject] else { return } let newElement = Element( symbol: dictionary["symbol"] as! String, name: dictionary["name"] as! String, mass: dictionary["mass"] as! String, type: ElementType(rawValue: dictionary["type"] as! String)!, row: dictionary["row"] as! Int, column: dictionary["column"] as! Int ) elements.append(newElement) } return elements } catch { return [] } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { animation?.stop() var animations = [Animation]() if (showTable) { for (i, node) in elements.enumerated() { let element = PeriodicTable.table[i] let pos = PeriodicTable.getPos(row: element.row, column: element.column) animations.append(node.placeVar.animation(to: pos, during: 1.0)) } } else { let data = PeriodicTable.gridData() for (i, node) in elements.enumerated() { animations.append(node.placeVar.animation(to: data[i], during: 1.0)) } } showTable = !showTable animation = animations.combine() animation?.play() } static func getColor(_ element: Element) -> Color { switch element.type { case .Alkali: return Color(val: 0xFD9856).with(a: 0.5) case .Alkaline: return Color(val: 0xEE1B1A).with(a: 0.5) case .Transition: return Color(val: 0xFEE734).with(a: 0.5) case .Basic: return Color(val: 0x1DBE54).with(a: 0.5) case .Semi: return Color(val: 0x7ECF46).with(a: 0.5) case .Nonmetal: return Color(val: 0xB2B3B5).with(a: 0.5) case .Halogen: return Color(val: 0x23C8CA).with(a: 0.5) case .NobleGas: return Color(val: 0x168CD0).with(a: 0.5) case .Lanthanide: return Color(val: 0x8977B5).with(a: 0.5) case .Actinide: return Color(val: 0xFD93BE).with(a: 0.5) } } } internal enum ElementType: String { case Alkali case Alkaline case Transition case Basic case Semi case Nonmetal case Halogen case NobleGas case Lanthanide case Actinide } internal class Element { let symbol: String let name: String let mass: String let type: ElementType let row: Int let column: Int init(symbol: String, name: String, mass: String, type: ElementType, row: Int, column: Int) { self.symbol = symbol self.name = name self.mass = mass self.type = type self.row = row self.column = column } }
mit
e45cbc429509e3287fd4fa34550ce251
28.663755
123
0.634035
3.104662
false
false
false
false
practicalswift/swift
test/Constraints/function_conversion.swift
8
1719
// RUN: %target-typecheck-verify-swift -swift-version 4 // rdar://problem/31969605 class Base {} class Derived : Base {} protocol Refined {} protocol Proto : Refined {} extension Base : Refined {} func baseFn(_: Base) {} func superclassConversion(fn: @escaping (Base) -> ()) { let _: (Derived) -> () = fn } func existentialConversion(fn: @escaping (Refined) -> ()) { let _: (Proto) -> () = fn let _: (Base) -> () = fn let _: (Derived) -> () = fn } // rdar://problem/31725325 func a<b>(_: [(String, (b) -> () -> Void)]) {} func a<b>(_: [(String, (b) -> () throws -> Void)]) {} class c { func e() {} static var d = [("", e)] } a(c.d) func b<T>(_: (T) -> () -> ()) {} b(c.e) func bar(_: () -> ()) {} func bar(_: () throws -> ()) {} func bar_empty() {} bar(bar_empty) func consumeNoEscape(_ f: (Int) -> Int) {} func consumeEscaping(_ f: @escaping (Int) -> Int) {} func takesAny(_ f: Any) {} func twoFns(_ f: (Int) -> Int, _ g: @escaping (Int) -> Int) { // expected-note@-1 {{parameter 'f' is implicitly non-escaping}} takesAny(f) // expected-error {{converting non-escaping value to 'Any' may allow it to escape}} takesAny(g) var h = g h = f // expected-error {{assigning non-escaping parameter 'f' to an @escaping closure}} } takesAny(consumeNoEscape) takesAny(consumeEscaping) var noEscapeParam: ((Int) -> Int) -> () = consumeNoEscape var escapingParam: (@escaping (Int) -> Int) -> () = consumeEscaping noEscapeParam = escapingParam // expected-error {{cannot assign value of type '(@escaping (Int) -> Int) -> ()' to type '((Int) -> Int) -> ()}} escapingParam = takesAny noEscapeParam = takesAny // expected-error {{converting non-escaping value to 'Any' may allow it to escape}}
apache-2.0
ca358453e5156f14c7c075315e104d24
25.446154
142
0.603839
3.219101
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPPhotoDisplayTransition.swift
1
6281
// // KPPhotoTransition.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/4/19. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit protocol ImageTransitionProtocol { func tranisitionSetup() func tranisitionCleanup() func imageWindowFrame() -> CGRect } class KPPhotoDisplayTransition: NSObject, UIViewControllerAnimatedTransitioning { enum photoTransitionType: String, RawRepresentable { case normal = "normal" case damping = "damping" } private var image: UIImage? private var fromDelegate: ImageTransitionProtocol? private var toDelegate: ImageTransitionProtocol? var presenting: Bool = true var transitionType: photoTransitionType = .normal // MARK: Setup Methods func setupImageTransition(_ image: UIImage, fromDelegate: ImageTransitionProtocol, toDelegate: ImageTransitionProtocol){ self.image = image self.fromDelegate = fromDelegate self.toDelegate = toDelegate } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView; let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! // 3: Set the destination view controllers frame toVC.view.frame = fromVC.view.frame // 4: Create transition image view let imageView = UIImageView(image: image) imageView.contentMode = .scaleAspectFill imageView.frame = (fromDelegate == nil) ? CGRect(x: 0, y: 0, width: 0, height: 0) : fromDelegate!.imageWindowFrame() imageView.clipsToBounds = true containerView.addSubview(imageView) // 5: Create from screen snapshot let fromSnapshot = fromVC.view.snapshotView(afterScreenUpdates: true) fromSnapshot?.frame = fromVC.view.frame containerView.addSubview(fromSnapshot!) fromDelegate!.tranisitionSetup() toDelegate!.tranisitionSetup() // 6: Create to screen snapshot let toSnapshot = toVC.view.snapshotView(afterScreenUpdates: true) toSnapshot?.frame = fromVC.view.frame containerView.addSubview(toSnapshot!) toSnapshot?.alpha = 0 // 7: Bring the image view to the front and get the final frame containerView.bringSubview(toFront: imageView) let toFrame = (self.toDelegate == nil) ? CGRect(x: 0, y: 0, width: 0, height: 0) : self.toDelegate!.imageWindowFrame() if transitionType == .normal { CATransaction.setDisableActions(true) imageView.layer.bounds = CGRect(x: 0, y: 0, width: toFrame.width, height: toFrame.height) imageView.layer.position = CGPoint(x: toFrame.origin.x+toFrame.width/2, y: toFrame.origin.y+toFrame.height/2) let animationBound = CABasicAnimation(keyPath: "bounds") animationBound.duration = 0.4 animationBound.timingFunction = CAMediaTimingFunction(controlPoints: 0.13, 1.03, 0.65, 0.96) let animationPosition = CABasicAnimation(keyPath: "position") animationPosition.duration = 0.4 animationPosition.timingFunction = CAMediaTimingFunction(controlPoints: 0.13, 1.03, 0.65, 0.96) CATransaction.setCompletionBlock { self.toDelegate!.tranisitionCleanup() self.fromDelegate!.tranisitionCleanup() // 9: Remove transition views imageView.removeFromSuperview() fromSnapshot?.removeFromSuperview() toSnapshot?.removeFromSuperview() // 10: Complete transition if !transitionContext.transitionWasCancelled { containerView.addSubview(toVC.view) } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } imageView.layer.add(animationBound, forKey: nil) imageView.layer.add(animationPosition, forKey: nil) // 8: Animate change UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.3, options: .curveEaseOut, animations: { toSnapshot?.alpha = 1 }) { (_) in } } else { UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.3, options: .curveEaseOut, animations: { toSnapshot?.alpha = 1 imageView.frame = toFrame }) { (_) in self.toDelegate!.tranisitionCleanup() self.fromDelegate!.tranisitionCleanup() // 9: Remove transition views imageView.removeFromSuperview() fromSnapshot?.removeFromSuperview() toSnapshot?.removeFromSuperview() // 10: Complete transition if !transitionContext.transitionWasCancelled { containerView.addSubview(toVC.view) } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } } }
mit
fbb306d6a2877cfb7d959ca2348e1a96
38.734177
109
0.564989
6.11295
false
false
false
false
charmaex/mini-RPG
MiniRPG/Controller.swift
2
2754
// // ViewController.swift // MiniRPG // // Created by Jan Dammshäuser on 01.02.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import UIKit class Controller: UIViewController { @IBOutlet weak var playerOne: UIImageView! @IBOutlet weak var playerTwo: UIImageView! @IBOutlet weak var playerOneButton: AttackButton! @IBOutlet weak var playerTwoButton: AttackButton! @IBOutlet weak var playerOneHP: UILabel! @IBOutlet weak var playerTwoHP: UILabel! @IBOutlet weak var playerOneInfo: UIView! @IBOutlet weak var playerTwoInfo: UIView! @IBOutlet weak var infoLabel: UILabel! var model: Model! override func viewDidLoad() { super.viewDidLoad() startGame() } func startGame() { model = Model() infoLabel.text = "Start the fight!" playerOne.image = model.playerOneImage playerTwo.image = model.playerTwoImage playerOne.showObject() playerTwo.showObject() playerOneInfo.showObject() playerTwoInfo.showObject() hpLabelSet() } func hpLabelSet() { playerOneHP.text = model.playerOne.hpForLabel playerTwoHP.text = model.playerTwo.hpForLabel } @IBAction func attackBtn(sender: UIButton!) { guard let playerNumber = Player.PlayerPositions(rawValue: sender.tag) else { return } let damageToEnemy = sender.alpha == 1 let infoText = model.attack(playerNumber: playerNumber, damageToEnemy: damageToEnemy) let rndTime = 1 + Double(arc4random_uniform(10)) / 10 //random Time 1-2seconds playerOneButton.disableButton(forTime: rndTime) playerTwoButton.disableButton(forTime: rndTime) infoLabel.text = infoText hpLabelSet() guard let deadPlayer = model.playerDied() else { return } NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: #selector(Controller.startGame), userInfo: nil, repeats: false) playerOneInfo.hideObject() playerTwoInfo.hideObject() let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))) var message: String switch deadPlayer { case .Left: playerOne.hideObject() message = self.model.playerTwo.winner case .Right: playerTwo.hideObject() message = self.model.playerOne.winner } dispatch_after(dispatchTime, dispatch_get_main_queue(), { self.infoLabel.text = message }) } }
gpl-3.0
2795dfea61f743d919611d0718fb2043
28.265957
136
0.613959
4.767764
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/ModelParser/QuestPageMP.swift
1
805
// // QuestPageMP.swift // AwesomeCore // // Created by Evandro Harrison Hoffmann on 11/3/17. // import Foundation struct QuestPageMP { static func parseQuestPagesFrom(_ questPagesJSON: Data) -> [QuestPage] { var pages: [QuestPage] = [] if let decoded = try? JSONDecoder().decode(QuestPages.self, from: questPagesJSON) { pages = decoded.pages } return pages } static func parseQuestPageFrom(_ QuestPageJSON: Data) -> QuestPage? { var page: QuestPage? do { let decoded = try JSONDecoder().decode(SingleQuestPageDataKey.self, from: QuestPageJSON) page = decoded.data.page } catch { print("\(#function) error: \(error)") } return page } }
mit
75b71172d686d2e4122a1c5aa55be7d7
24.15625
100
0.578882
4.327957
false
false
false
false
Authman2/Pix
Pix/ActivitySectionController.swift
1
1784
// // ActivitySectionController.swift // Pix // // Created by Adeola Uthman on 1/8/17. // Copyright © 2017 Adeola Uthman. All rights reserved. // import UIKit import IGListKit class ActivitySectionController: IGListSectionController, IGListSectionType { /* The activity object. */ var activityObject: Activity?; func numberOfItems() -> Int { return 1; } func sizeForItem(at index: Int) -> CGSize { if activityObject?.interactionRequired == true { return CGSize(width: (collectionContext?.containerSize.width)!, height: 60); } else { return CGSize(width: (collectionContext?.containerSize.width)!, height: 50); } } func cellForItem(at index: Int) -> UICollectionViewCell { let cellClass: AnyClass = activityObject?.interactionRequired == true ? ActivityRequestCell.self : ActivityCell.self; let cell = collectionContext!.dequeueReusableCell(of: cellClass, for: self, at: index); if let cell = cell as? ActivityRequestCell { cell.activity = self.activityObject!; cell.titleLabel.text = "\(activityObject!.text!)"; if self.activityObject?.interactedWith == true { cell.acceptButton.isHidden = true; cell.declineButton.isHidden = true; } } else if let cell = cell as? ActivityCell { cell.titleLabel.text = "\(activityObject!.text!)"; } return cell; } func didUpdate(to object: Any) { self.activityObject = object as? Activity; } func didSelectItem(at index: Int) { } }
gpl-3.0
4ef8900826a32f3204e169de3c9f8d6e
24.84058
125
0.575996
5.138329
false
false
false
false
robrix/Surge
Source/Trigonometric.swift
1
2952
// Trigonometric.swift // // Copyright (c) 2014 Mattt Thompson (http://mattt.me) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public func sincos(x: [Double]) -> (sin: [Double], cos: [Double]) { var sin = [Double](count: x.count, repeatedValue: 0.0) var cos = [Double](count: x.count, repeatedValue: 0.0) vvsincos(&sin, &cos, x, [Int32(x.count)]) return (sin, cos) } public func sin(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvsin(&results, x, [Int32(x.count)]) return results } public func cos(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvcos(&results, x, [Int32(x.count)]) return results } public func tan(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvtan(&results, x, [Int32(x.count)]) return results } public func asin(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvasin(&results, x, [Int32(x.count)]) return results } public func acos(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvacos(&results, x, [Int32(x.count)]) return results } public func atan(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) vvatan(&results, x, [Int32(x.count)]) return results } // MARK: - func rad2deg(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) var divisor = [Double](count: x.count, repeatedValue: M_PI / 180.0) vvdiv(&results, x, divisor, [Int32(x.count)]) return results } func deg2rad(x: [Double]) -> [Double] { var results = [Double](count: x.count, repeatedValue: 0.0) var divisor = [Double](count: x.count, repeatedValue: 180.0 / M_PI) vvdiv(&results, x, divisor, [Int32(x.count)]) return results }
mit
27b612b579d094dce29e7893ded1e3e8
32.168539
80
0.674458
3.46886
false
false
false
false
devincoughlin/swift
test/Serialization/comments.swift
1
6492
// Test the case when we have a single file in a module. // // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc -emit-module-source-info-path %t/comments.swiftsourceinfo %s // RUN: llvm-bcanalyzer %t/comments.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER // RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER // RUN: llvm-bcanalyzer %t/comments.swiftsourceinfo | %FileCheck %s -check-prefix=BCANALYZER // RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -I %t | %FileCheck %s -check-prefix=FIRST // Test the case when we have a multiple files in a module. // // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/first.swiftmodule -emit-module-doc -emit-module-doc-path %t/first.swiftdoc -primary-file %s %S/Inputs/def_comments.swift -emit-module-source-info-path %t/first.swiftsourceinfo // RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/second.swiftmodule -emit-module-doc -emit-module-doc-path %t/second.swiftdoc %s -primary-file %S/Inputs/def_comments.swift -emit-module-source-info-path %t/second.swiftsourceinfo // RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc %t/first.swiftmodule %t/second.swiftmodule -emit-module-source-info-path %t/comments.swiftsourceinfo // RUN: llvm-bcanalyzer %t/comments.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER // RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER // RUN: llvm-bcanalyzer %t/comments.swiftsourceinfo | %FileCheck %s -check-prefix=BCANALYZER // RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -I %t > %t.printed.txt // RUN: %FileCheck %s -check-prefix=FIRST < %t.printed.txt // RUN: %FileCheck %s -check-prefix=SECOND < %t.printed.txt // BCANALYZER-NOT: UnknownCode /// first_decl_generic_class_1 Aaa. public class first_decl_generic_class_1<T> { /// deinit of first_decl_generic_class_1 Aaa. deinit { } } /// first_decl_class_1 Aaa. public class first_decl_class_1 { /// decl_func_1 Aaa. public func decl_func_1() {} /** * decl_func_3 Aaa. */ public func decl_func_2() {} /// decl_func_3 Aaa. /** Bbb. */ public func decl_func_3() {} } /// Comment for bar1 extension first_decl_class_1 { func bar1(){} } /// Comment for bar2 extension first_decl_class_1 { func bar2(){} } public protocol P1 { } /// Comment for no member extension extension first_decl_class_1 : P1 {} // FIRST: comments.swift:26:14: Class/first_decl_generic_class_1 RawComment=[/// first_decl_generic_class_1 Aaa.\n] // FIRST: comments.swift:28:3: Destructor/first_decl_generic_class_1.deinit RawComment=[/// deinit of first_decl_generic_class_1 Aaa.\n] // FIRST: comments.swift:33:14: Class/first_decl_class_1 RawComment=[/// first_decl_class_1 Aaa.\n] // FIRST: comments.swift:36:15: Func/first_decl_class_1.decl_func_1 RawComment=[/// decl_func_1 Aaa.\n] // FIRST: comments.swift:41:15: Func/first_decl_class_1.decl_func_2 RawComment=[/**\n * decl_func_3 Aaa.\n */] // FIRST: comments.swift:45:15: Func/first_decl_class_1.decl_func_3 RawComment=[/// decl_func_3 Aaa.\n/** Bbb. */] // SECOND: comments.swift:49:1: Extension/ RawComment=[/// Comment for bar1\n] BriefComment=[Comment for bar1] // SECOND: comments.swift:54:1: Extension/ RawComment=[/// Comment for bar2\n] BriefComment=[Comment for bar2] // SECOND: comments.swift:61:1: Extension/ RawComment=[/// Comment for no member extension\n] BriefComment=[Comment for no member extension] // SECOND: Inputs/def_comments.swift:2:14: Class/second_decl_class_1 RawComment=[/// second_decl_class_1 Aaa.\n] // SECOND: Inputs/def_comments.swift:5:15: Struct/second_decl_struct_1 // SECOND: Inputs/def_comments.swift:7:9: Accessor/second_decl_struct_1.<getter for second_decl_struct_1.instanceVar> // SECOND: Inputs/def_comments.swift:8:9: Accessor/second_decl_struct_1.<setter for second_decl_struct_1.instanceVar> // SECOND: Inputs/def_comments.swift:10:17: Enum/second_decl_struct_1.NestedEnum // SECOND: Inputs/def_comments.swift:11:22: TypeAlias/second_decl_struct_1.NestedTypealias // SECOND: Inputs/def_comments.swift:14:13: Enum/second_decl_enum_1 // SECOND: Inputs/def_comments.swift:15:10: EnumElement/second_decl_enum_1.Case1 // SECOND: Inputs/def_comments.swift:16:10: EnumElement/second_decl_enum_1.Case2 // SECOND: Inputs/def_comments.swift:20:12: Constructor/second_decl_class_2.init // SECOND: Inputs/def_comments.swift:23:17: Protocol/second_decl_protocol_1 // SECOND: Inputs/def_comments.swift:24:20: AssociatedType/second_decl_protocol_1.NestedTypealias // SECOND: Inputs/def_comments.swift:25:5: Subscript/second_decl_protocol_1.subscript // SECOND: Inputs/def_comments.swift:25:35: Accessor/second_decl_protocol_1.<getter for second_decl_protocol_1.subscript> // SECOND: Inputs/def_comments.swift:25:39: Accessor/second_decl_protocol_1.<setter for second_decl_protocol_1.subscript> // SECOND: Inputs/def_comments.swift:28:13: Var/decl_var_2 RawComment=none BriefComment=none DocCommentAsXML=none // SECOND: Inputs/def_comments.swift:28:25: Var/decl_var_3 RawComment=none BriefComment=none DocCommentAsXML=none // SECOND: Inputs/def_comments.swift:28:25: Var/decl_var_3 RawComment=none BriefComment=none DocCommentAsXML=none // SECOND: NonExistingSource.swift:100000:13: Func/functionAfterPoundSourceLoc // Test the case when we have to import via a .swiftinterface file. // // RUN: %empty-directory(%t) // RUN: %empty-directory(%t/Hidden) // RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/Hidden/comments.swiftmodule -emit-module-interface-path %t/comments.swiftinterface -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc -emit-module-source-info-path %t/comments.swiftsourceinfo %s -enable-library-evolution -swift-version 5 // RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER // RUN: llvm-bcanalyzer %t/comments.swiftsourceinfo | %FileCheck %s -check-prefix=BCANALYZER // RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -I %t -swift-version 5 | %FileCheck %s -check-prefix=FIRST
apache-2.0
b36ce85f202cdd5e551dcade184f3cae
63.92
333
0.745687
3.213861
false
true
false
false
profburke/AppLister
AppLister/AppDelegate.swift
1
1441
// // AppDelegate.swift // AppLister // // Created by Matthew Burke on 11/12/14. // Copyright (c) 2014-2017 BlueDino Software. // Availble under the MIT License. See the file, LICENSE, for details. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let splitViewController = window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self return true } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController, let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController, topAsDetailController.detailItem == nil { return true } return false } }
mit
5263cc3984da57945b6a24e93b2f44dd
39.027778
187
0.773074
6.211207
false
false
false
false
sonsongithub/KeychainAccess
Lib/KeychainAccessTests/KeychainAccessTests.swift
2
63172
// // KeychainAccessTests.swift // KeychainAccessTests // // Created by kishikawa katsumi on 2014/12/24. // Copyright (c) 2014 kishikawa katsumi. All rights reserved. // import Foundation import XCTest import KeychainAccess class KeychainAccessTests: XCTestCase { override func setUp() { super.setUp() do { try Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared").removeAll() } catch {} do { try Keychain(service: "Twitter").removeAll() } catch {} do { try Keychain(server: NSURL(string: "https://example.com")!, protocolType: .HTTPS).removeAll() } catch {} do { try Keychain(server: NSURL(string: "https://example.com:443")!, protocolType: .HTTPS).removeAll() } catch {} do { try Keychain().removeAll() } catch {} } override func tearDown() { super.tearDown() } // MARK: func testGenericPassword() { do { // Add Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.set("kishikawa_katsumi", key: "username") } catch {} do { try keychain.set("password_1234", key: "password") } catch {} let username = try! keychain.get("username") XCTAssertEqual(username, "kishikawa_katsumi") let password = try! keychain.get("password") XCTAssertEqual(password, "password_1234") } do { // Update Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.set("katsumi_kishikawa", key: "username") } catch {} do { try keychain.set("1234_password", key: "password") } catch {} let username = try! keychain.get("username") XCTAssertEqual(username, "katsumi_kishikawa") let password = try! keychain.get("password") XCTAssertEqual(password, "1234_password") } do { // Remove Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.remove("username") } catch {} do { try keychain.remove("password") } catch {} XCTAssertNil(try! keychain.get("username")) XCTAssertNil(try! keychain.get("password")) } } func testGenericPasswordSubscripting() { do { // Add Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = "kishikawa_katsumi" keychain["password"] = "password_1234" let username = keychain["username"] XCTAssertEqual(username, "kishikawa_katsumi") let password = keychain["password"] XCTAssertEqual(password, "password_1234") } do { // Update Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = "katsumi_kishikawa" keychain["password"] = "1234_password" let username = keychain["username"] XCTAssertEqual(username, "katsumi_kishikawa") let password = keychain["password"] XCTAssertEqual(password, "1234_password") } do { // Remove Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = nil keychain["password"] = nil XCTAssertNil(keychain["username"]) XCTAssertNil(keychain["password"]) } } // MARK: func testInternetPassword() { do { // Add Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) do { try keychain.set("kishikawa_katsumi", key: "username") } catch {} do { try keychain.set("password_1234", key: "password") } catch {} let username = try! keychain.get("username") XCTAssertEqual(username, "kishikawa_katsumi") let password = try! keychain.get("password") XCTAssertEqual(password, "password_1234") } do { // Update Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) do { try keychain.set("katsumi_kishikawa", key: "username") } catch {} do { try keychain.set("1234_password", key: "password") } catch {} let username = try! keychain.get("username") XCTAssertEqual(username, "katsumi_kishikawa") let password = try! keychain.get("password") XCTAssertEqual(password, "1234_password") } do { // Remove Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) do { try keychain.remove("username") } catch {} do { try keychain.remove("password") } catch {} XCTAssertNil(try! keychain.get("username")) XCTAssertNil(try! keychain.get("password")) } } func testInternetPasswordSubscripting() { do { // Add Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = "kishikawa_katsumi" keychain["password"] = "password_1234" let username = keychain["username"] XCTAssertEqual(username, "kishikawa_katsumi") let password = keychain["password"] XCTAssertEqual(password, "password_1234") } do { // Update Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = "katsumi_kishikawa" keychain["password"] = "1234_password" let username = keychain["username"] XCTAssertEqual(username, "katsumi_kishikawa") let password = keychain["password"] XCTAssertEqual(password, "1234_password") } do { // Remove Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = nil keychain["password"] = nil XCTAssertNil(keychain["username"]) XCTAssertNil(keychain["password"]) } } // MARK: func testDefaultInitializer() { let keychain = Keychain() XCTAssertEqual(keychain.service, "") XCTAssertNil(keychain.accessGroup) } func testInitializerWithService() { let keychain = Keychain(service: "com.example.github-token") XCTAssertEqual(keychain.service, "com.example.github-token") XCTAssertNil(keychain.accessGroup) } func testInitializerWithAccessGroup() { let keychain = Keychain(accessGroup: "12ABCD3E4F.shared") XCTAssertEqual(keychain.service, "") XCTAssertEqual(keychain.accessGroup, "12ABCD3E4F.shared") } func testInitializerWithServiceAndAccessGroup() { let keychain = Keychain(service: "com.example.github-token", accessGroup: "12ABCD3E4F.shared") XCTAssertEqual(keychain.service, "com.example.github-token") XCTAssertEqual(keychain.accessGroup, "12ABCD3E4F.shared") } func testInitializerWithServer() { let server = "https://kishikawakatsumi.com" let URL = NSURL(string: server)! do { let keychain = Keychain(server: server, protocolType: .HTTPS) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.Default) } do { let keychain = Keychain(server: URL, protocolType: .HTTPS) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.Default) } } func testInitializerWithServerAndAuthenticationType() { let server = "https://kishikawakatsumi.com" let URL = NSURL(string: server)! do { let keychain = Keychain(server: server, protocolType: .HTTPS, authenticationType: .HTMLForm) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.HTMLForm) } do { let keychain = Keychain(server: URL, protocolType: .HTTPS, authenticationType: .HTMLForm) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.HTMLForm) } } // MARK: func testContains() { let keychain = Keychain(service: "Twitter") XCTAssertFalse(try! keychain.contains("username"), "not stored username") XCTAssertFalse(try! keychain.contains("password"), "not stored password") do { try keychain.set("kishikawakatsumi", key: "username") } catch {} XCTAssertTrue(try! keychain.contains("username"), "stored username") XCTAssertFalse(try! keychain.contains("password"), "not stored password") do { try keychain.set("password1234", key: "password") } catch {} XCTAssertTrue(try! keychain.contains("username"), "stored username") XCTAssertTrue(try! keychain.contains("password"), "stored password") } // MARK: func testSetString() { let keychain = Keychain(service: "Twitter") XCTAssertNil(try! keychain.get("username"), "not stored username") XCTAssertNil(try! keychain.get("password"), "not stored password") do { try keychain.set("kishikawakatsumi", key: "username") } catch {} XCTAssertEqual(try! keychain.get("username"), "kishikawakatsumi", "stored username") XCTAssertNil(try! keychain.get("password"), "not stored password") do { try keychain.set("password1234", key: "password") } catch {} XCTAssertEqual(try! keychain.get("username"), "kishikawakatsumi", "stored username") XCTAssertEqual(try! keychain.get("password"), "password1234", "stored password") } func testSetStringWithLabel() { let keychain = Keychain(service: "Twitter") .label("Twitter Account") XCTAssertNil(keychain["kishikawakatsumi"], "not stored password") do { let label = try keychain.get("kishikawakatsumi") { (attributes) -> String? in return attributes?.label } XCTAssertNil(label) } catch { XCTFail("error occurred") } keychain["kishikawakatsumi"] = "password1234" XCTAssertEqual(keychain["kishikawakatsumi"], "password1234", "stored password") do { let label = try keychain.get("kishikawakatsumi") { (attributes) -> String? in return attributes?.label } XCTAssertEqual(label, "Twitter Account") } catch { XCTFail("error occurred") } } func testSetStringWithComment() { let keychain = Keychain(service: "Twitter") .comment("Kishikawa Katsumi") XCTAssertNil(keychain["kishikawakatsumi"], "not stored password") do { let comment = try keychain.get("kishikawakatsumi") { (attributes) -> String? in return attributes?.comment } XCTAssertNil(comment) } catch { XCTFail("error occurred") } keychain["kishikawakatsumi"] = "password1234" XCTAssertEqual(keychain["kishikawakatsumi"], "password1234", "stored password") do { let comment = try keychain.get("kishikawakatsumi") { (attributes) -> String? in return attributes?.comment } XCTAssertEqual(comment, "Kishikawa Katsumi") } catch { XCTFail("error occurred") } } func testSetStringWithLabelAndComment() { let keychain = Keychain(service: "Twitter") .label("Twitter Account") .comment("Kishikawa Katsumi") XCTAssertNil(keychain["kishikawakatsumi"], "not stored password") do { let label = try keychain.get("kishikawakatsumi") { (attributes) -> String? in return attributes?.label } XCTAssertNil(label) let comment = try keychain.get("kishikawakatsumi") { (attributes) -> String? in return attributes?.comment } XCTAssertNil(comment) } catch { XCTFail("error occurred") } keychain["kishikawakatsumi"] = "password1234" XCTAssertEqual(keychain["kishikawakatsumi"], "password1234", "stored password") do { let label = try keychain.get("kishikawakatsumi") { (attributes) -> String? in return attributes?.label } XCTAssertEqual(label, "Twitter Account") let comment = try keychain.get("kishikawakatsumi") { (attributes) -> String? in return attributes?.comment } XCTAssertEqual(comment, "Kishikawa Katsumi") } catch { XCTFail("error occurred") } } func testSetData() { let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = try! NSJSONSerialization.dataWithJSONObject(JSONObject, options: []) let keychain = Keychain(service: "Twitter") XCTAssertNil(try! keychain.getData("JSONData"), "not stored JSON data") do { try keychain.set(JSONData, key: "JSONData") } catch {} XCTAssertEqual(try! keychain.getData("JSONData"), JSONData, "stored JSON data") } func testStringConversionError() { let keychain = Keychain(service: "Twitter") let length = 256 let data = NSMutableData(length: length)! SecRandomCopyBytes(kSecRandomDefault, length, UnsafeMutablePointer<UInt8>(data.mutableBytes)) do { try keychain.set(data, key: "RandomData") let _ = try keychain.getString("RandomData") } catch let error as NSError { XCTAssertEqual(error.domain, KeychainAccessErrorDomain) XCTAssertEqual(error.code, Int(Status.ConversionError.rawValue)) } } func testGetPersistentRef() { let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain["kishikawakatsumi"], "not stored password") do { let persistentRef = try keychain.get("kishikawakatsumi") { $0?.persistentRef } XCTAssertNil(persistentRef) } catch { XCTFail("error occurred") } keychain["kishikawakatsumi"] = "password1234" XCTAssertEqual(keychain["kishikawakatsumi"], "password1234", "stored password") do { let persistentRef = try keychain.get("kishikawakatsumi") { $0?.persistentRef } XCTAssertNotNil(persistentRef) } catch { XCTFail("error occurred") } } #if os(iOS) || os(tvOS) func testSetAttributes() { do { var attributes = [String: AnyObject]() attributes[String(kSecAttrDescription)] = "Description Test" attributes[String(kSecAttrComment)] = "Comment Test" attributes[String(kSecAttrCreator)] = "Creator Test" attributes[String(kSecAttrType)] = "Type Test" attributes[String(kSecAttrLabel)] = "Label Test" attributes[String(kSecAttrIsInvisible)] = true attributes[String(kSecAttrIsNegative)] = true let keychain = Keychain(service: "Twitter") .attributes(attributes) .accessibility(.WhenPasscodeSetThisDeviceOnly, authenticationPolicy: .UserPresence) XCTAssertNil(keychain["kishikawakatsumi"], "not stored password") do { let attributes = try keychain.get("kishikawakatsumi") { $0 } XCTAssertNil(attributes) } catch { XCTFail("error occurred") } keychain["kishikawakatsumi"] = "password1234" XCTAssertEqual(keychain["kishikawakatsumi"], "password1234", "stored password") do { let attributes = try keychain.get("kishikawakatsumi") { $0 } XCTAssertEqual(attributes?.`class`, ItemClass.GenericPassword.rawValue) XCTAssertEqual(attributes?.data, "password1234".dataUsingEncoding(NSUTF8StringEncoding)) XCTAssertNil(attributes?.ref) XCTAssertNotNil(attributes?.persistentRef) XCTAssertEqual(attributes?.accessible, Accessibility.WhenPasscodeSetThisDeviceOnly.rawValue) XCTAssertNotNil(attributes?.accessControl) XCTAssertEqual(attributes?.accessGroup, "") XCTAssertNotNil(attributes?.synchronizable) XCTAssertNotNil(attributes?.creationDate) XCTAssertNotNil(attributes?.modificationDate) XCTAssertEqual(attributes?.attributeDescription, "Description Test") XCTAssertEqual(attributes?.comment, "Comment Test") XCTAssertEqual(attributes?.creator, "Creator Test") XCTAssertEqual(attributes?.type, "Type Test") XCTAssertEqual(attributes?.label, "Label Test") XCTAssertEqual(attributes?.isInvisible, true) XCTAssertEqual(attributes?.isNegative, true) XCTAssertEqual(attributes?.account, "kishikawakatsumi") XCTAssertEqual(attributes?.service, "Twitter") XCTAssertNil(attributes?.generic) XCTAssertNil(attributes?.securityDomain) XCTAssertNil(attributes?.server) XCTAssertNil(attributes?.`protocol`) XCTAssertNil(attributes?.authenticationType) XCTAssertNil(attributes?.port) XCTAssertNil(attributes?.path) XCTAssertEqual(attributes![String(kSecClass)] as? String, ItemClass.GenericPassword.rawValue) XCTAssertEqual(attributes![String(kSecValueData)] as? NSData, "password1234".dataUsingEncoding(NSUTF8StringEncoding)) } catch { XCTFail("error occurred") } } do { var attributes = [String: AnyObject]() attributes[String(kSecAttrDescription)] = "Description Test" attributes[String(kSecAttrComment)] = "Comment Test" attributes[String(kSecAttrCreator)] = "Creator Test" attributes[String(kSecAttrType)] = "Type Test" attributes[String(kSecAttrLabel)] = "Label Test" attributes[String(kSecAttrIsInvisible)] = true attributes[String(kSecAttrIsNegative)] = true attributes[String(kSecAttrSecurityDomain)] = "securitydomain" let keychain = Keychain(server: NSURL(string: "https://example.com:443/api/login/")!, protocolType: .HTTPS) .attributes(attributes) XCTAssertNil(keychain["kishikawakatsumi"], "not stored password") do { let attributes = try keychain.get("kishikawakatsumi") { $0 } XCTAssertNil(attributes) } catch { XCTFail("error occurred") } do { keychain["kishikawakatsumi"] = "password1234" XCTAssertEqual(keychain["kishikawakatsumi"], "password1234", "stored password") let attributes = try keychain.get("kishikawakatsumi") { $0 } XCTAssertEqual(attributes?.`class`, ItemClass.InternetPassword.rawValue) XCTAssertEqual(attributes?.data, "password1234".dataUsingEncoding(NSUTF8StringEncoding)) XCTAssertNil(attributes?.ref) XCTAssertNotNil(attributes?.persistentRef) XCTAssertEqual(attributes?.accessible, Accessibility.AfterFirstUnlock.rawValue) if #available(iOS 9.0, *) { XCTAssertNil(attributes?.accessControl) } else { XCTAssertNotNil(attributes?.accessControl) } XCTAssertEqual(attributes?.accessGroup, "") XCTAssertNotNil(attributes?.synchronizable) XCTAssertNotNil(attributes?.creationDate) XCTAssertNotNil(attributes?.modificationDate) XCTAssertEqual(attributes?.attributeDescription, "Description Test") XCTAssertEqual(attributes?.comment, "Comment Test") XCTAssertEqual(attributes?.creator, "Creator Test") XCTAssertEqual(attributes?.type, "Type Test") XCTAssertEqual(attributes?.label, "Label Test") XCTAssertEqual(attributes?.isInvisible, true) XCTAssertEqual(attributes?.isNegative, true) XCTAssertEqual(attributes?.account, "kishikawakatsumi") XCTAssertNil(attributes?.service) XCTAssertNil(attributes?.generic) XCTAssertEqual(attributes?.securityDomain, "securitydomain") XCTAssertEqual(attributes?.server, "example.com") XCTAssertEqual(attributes?.`protocol`, ProtocolType.HTTPS.rawValue) XCTAssertEqual(attributes?.authenticationType, AuthenticationType.Default.rawValue) XCTAssertEqual(attributes?.port, 443) XCTAssertEqual(attributes?.path, "") } catch { XCTFail("error occurred") } do { let keychain = Keychain(server: NSURL(string: "https://example.com:443/api/login/")!, protocolType: .HTTPS) XCTAssertEqual(keychain["kishikawakatsumi"], "password1234", "stored password") keychain["kishikawakatsumi"] = "1234password" XCTAssertEqual(keychain["kishikawakatsumi"], "1234password", "updated password") let attributes = try keychain.get("kishikawakatsumi") { $0 } XCTAssertEqual(attributes?.`class`, ItemClass.InternetPassword.rawValue) XCTAssertEqual(attributes?.data, "1234password".dataUsingEncoding(NSUTF8StringEncoding)) XCTAssertNil(attributes?.ref) XCTAssertNotNil(attributes?.persistentRef) XCTAssertEqual(attributes?.accessible, Accessibility.AfterFirstUnlock.rawValue) if #available(iOS 9.0, *) { XCTAssertNil(attributes?.accessControl) } else { XCTAssertNotNil(attributes?.accessControl) } XCTAssertEqual(attributes?.accessGroup, "") XCTAssertNotNil(attributes?.synchronizable) XCTAssertNotNil(attributes?.creationDate) XCTAssertNotNil(attributes?.modificationDate) XCTAssertEqual(attributes?.attributeDescription, "Description Test") XCTAssertEqual(attributes?.comment, "Comment Test") XCTAssertEqual(attributes?.creator, "Creator Test") XCTAssertEqual(attributes?.type, "Type Test") XCTAssertEqual(attributes?.label, "Label Test") XCTAssertEqual(attributes?.isInvisible, true) XCTAssertEqual(attributes?.isNegative, true) XCTAssertEqual(attributes?.account, "kishikawakatsumi") XCTAssertNil(attributes?.service) XCTAssertNil(attributes?.generic) XCTAssertEqual(attributes?.securityDomain, "securitydomain") XCTAssertEqual(attributes?.server, "example.com") XCTAssertEqual(attributes?.`protocol`, ProtocolType.HTTPS.rawValue) XCTAssertEqual(attributes?.authenticationType, AuthenticationType.Default.rawValue) XCTAssertEqual(attributes?.port, 443) XCTAssertEqual(attributes?.path, "") } catch { XCTFail("error occurred") } do { let keychain = Keychain(server: NSURL(string: "https://example.com:443/api/login/")!, protocolType: .HTTPS) .attributes([String(kSecAttrDescription): "Updated Description"]) XCTAssertEqual(keychain["kishikawakatsumi"], "1234password", "stored password") keychain["kishikawakatsumi"] = "password1234" XCTAssertEqual(keychain["kishikawakatsumi"], "password1234", "updated password") let attributes = keychain[attributes: "kishikawakatsumi"] XCTAssertEqual(attributes?.`class`, ItemClass.InternetPassword.rawValue) XCTAssertEqual(attributes?.data, "password1234".dataUsingEncoding(NSUTF8StringEncoding)) XCTAssertNil(attributes?.ref) XCTAssertNotNil(attributes?.persistentRef) XCTAssertEqual(attributes?.accessible, Accessibility.AfterFirstUnlock.rawValue) if #available(iOS 9.0, *) { XCTAssertNil(attributes?.accessControl) } else { XCTAssertNotNil(attributes?.accessControl) } XCTAssertEqual(attributes?.accessGroup, "") XCTAssertNotNil(attributes?.synchronizable) XCTAssertNotNil(attributes?.creationDate) XCTAssertNotNil(attributes?.modificationDate) XCTAssertEqual(attributes?.attributeDescription, "Updated Description") XCTAssertEqual(attributes?.comment, "Comment Test") XCTAssertEqual(attributes?.creator, "Creator Test") XCTAssertEqual(attributes?.type, "Type Test") XCTAssertEqual(attributes?.label, "Label Test") XCTAssertEqual(attributes?.isInvisible, true) XCTAssertEqual(attributes?.isNegative, true) XCTAssertEqual(attributes?.account, "kishikawakatsumi") XCTAssertNil(attributes?.service) XCTAssertNil(attributes?.generic) XCTAssertEqual(attributes?.securityDomain, "securitydomain") XCTAssertEqual(attributes?.server, "example.com") XCTAssertEqual(attributes?.`protocol`, ProtocolType.HTTPS.rawValue) XCTAssertEqual(attributes?.authenticationType, AuthenticationType.Default.rawValue) XCTAssertEqual(attributes?.port, 443) XCTAssertEqual(attributes?.path, "") } } } #endif func testRemoveString() { let keychain = Keychain(service: "Twitter") XCTAssertNil(try! keychain.get("username"), "not stored username") XCTAssertNil(try! keychain.get("password"), "not stored password") do { try keychain.set("kishikawakatsumi", key: "username") } catch {} XCTAssertEqual(try! keychain.get("username"), "kishikawakatsumi", "stored username") do { try keychain.set("password1234", key: "password") } catch {} XCTAssertEqual(try! keychain.get("password"), "password1234", "stored password") do { try keychain.remove("username") } catch {} XCTAssertNil(try! keychain.get("username"), "removed username") XCTAssertEqual(try! keychain.get("password"), "password1234", "left password") do { try keychain.remove("password") } catch {} XCTAssertNil(try! keychain.get("username"), "removed username") XCTAssertNil(try! keychain.get("password"), "removed password") } func testRemoveData() { let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = try! NSJSONSerialization.dataWithJSONObject(JSONObject, options: []) let keychain = Keychain(service: "Twitter") XCTAssertNil(try! keychain.getData("JSONData"), "not stored JSON data") do { try keychain.set(JSONData, key: "JSONData") } catch {} XCTAssertEqual(try! keychain.getData("JSONData"), JSONData, "stored JSON data") do { try keychain.remove("JSONData") } catch {} XCTAssertNil(try! keychain.getData("JSONData"), "removed JSON data") } // MARK: func testSubscripting() { let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain["username"], "not stored username") XCTAssertNil(keychain["password"], "not stored password") XCTAssertNil(keychain[string: "username"], "not stored username") XCTAssertNil(keychain[string: "password"], "not stored password") keychain["username"] = "kishikawakatsumi" XCTAssertEqual(keychain["username"], "kishikawakatsumi", "stored username") XCTAssertEqual(keychain[string: "username"], "kishikawakatsumi", "stored username") keychain["password"] = "password1234" XCTAssertEqual(keychain["password"], "password1234", "stored password") XCTAssertEqual(keychain[string: "password"], "password1234", "stored password") keychain[string: "username"] = nil XCTAssertNil(keychain["username"], "removed username") XCTAssertEqual(keychain["password"], "password1234", "left password") XCTAssertNil(keychain[string: "username"], "removed username") XCTAssertEqual(keychain[string: "password"], "password1234", "left password") keychain[string: "password"] = nil XCTAssertNil(keychain["username"], "removed username") XCTAssertNil(keychain["password"], "removed password") XCTAssertNil(keychain[string: "username"], "removed username") XCTAssertNil(keychain[string: "password"], "removed password") let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = try! NSJSONSerialization.dataWithJSONObject(JSONObject, options: []) XCTAssertNil(keychain[data:"JSONData"], "not stored JSON data") keychain[data: "JSONData"] = JSONData XCTAssertEqual(keychain[data: "JSONData"], JSONData, "stored JSON data") keychain[data: "JSONData"] = nil XCTAssertNil(keychain[data:"JSONData"], "removed JSON data") } // MARK: #if os(iOS) func testErrorHandling() { do { let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") try keychain.removeAll() XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { let keychain = Keychain(service: "Twitter") try keychain.removeAll() XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) try keychain.removeAll() XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { let keychain = Keychain() try keychain.removeAll() XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { // Add Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.set("kishikawa_katsumi", key: "username") XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { try keychain.set("password_1234", key: "password") XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { let username = try keychain.get("username") XCTAssertEqual(username, "kishikawa_katsumi") } catch { XCTFail("error occurred") } do { let password = try keychain.get("password") XCTAssertEqual(password, "password_1234") } catch { XCTFail("error occurred") } } do { // Update Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.set("katsumi_kishikawa", key: "username") XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { try keychain.set("1234_password", key: "password") XCTAssertTrue(true, "no error occurred") } catch { XCTFail("error occurred") } do { let username = try keychain.get("username") XCTAssertEqual(username, "katsumi_kishikawa") } catch { XCTFail("error occurred") } do { let password = try keychain.get("password") XCTAssertEqual(password, "1234_password") } catch { XCTFail("error occurred") } } do { // Remove Keychain items let keychain = Keychain(service: "Twitter") do { try keychain.remove("username") XCTAssertNil(try! keychain.get("username")) } catch { XCTFail("error occurred") } do { try keychain.remove("password") XCTAssertNil(try! keychain.get("username")) } catch { XCTFail("error occurred") } } } #endif // MARK: func testSetStringWithCustomService() { let username_1 = "kishikawakatsumi" let password_1 = "password1234" let username_2 = "kishikawa_katsumi" let password_2 = "password_1234" let username_3 = "k_katsumi" let password_3 = "12341234" let service_1 = "" let service_2 = "com.kishikawakatsumi.KeychainAccess" let service_3 = "example.com" do { try Keychain().removeAll() } catch {} do { try Keychain(service: service_1).removeAll() } catch {} do { try Keychain(service: service_2).removeAll() } catch {} do { try Keychain(service: service_3).removeAll() } catch {} XCTAssertNil(try! Keychain().get("username"), "not stored username") XCTAssertNil(try! Keychain().get("password"), "not stored password") XCTAssertNil(try! Keychain(service: service_1).get("username"), "not stored username") XCTAssertNil(try! Keychain(service: service_1).get("password"), "not stored password") XCTAssertNil(try! Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(try! Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(try! Keychain(service: service_3).get("username"), "not stored username") XCTAssertNil(try! Keychain(service: service_3).get("password"), "not stored password") do { try Keychain().set(username_1, key: "username") } catch {} XCTAssertEqual(try! Keychain().get("username"), username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_1).get("username"), username_1, "stored username") XCTAssertNil(try! Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(try! Keychain(service: service_3).get("username"), "not stored username") do { try Keychain(service: service_1).set(username_1, key: "username") } catch {} XCTAssertEqual(try! Keychain().get("username"), username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_1).get("username"), username_1, "stored username") XCTAssertNil(try! Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(try! Keychain(service: service_3).get("username"), "not stored username") do { try Keychain(service: service_2).set(username_2, key: "username") } catch {} XCTAssertEqual(try! Keychain().get("username"), username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_1).get("username"), username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_2).get("username"), username_2, "stored username") XCTAssertNil(try! Keychain(service: service_3).get("username"), "not stored username") do { try Keychain(service: service_3).set(username_3, key: "username") } catch {} XCTAssertEqual(try! Keychain().get("username"), username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_1).get("username"), username_1, "stored username") XCTAssertEqual(try! Keychain(service: service_2).get("username"), username_2, "stored username") XCTAssertEqual(try! Keychain(service: service_3).get("username"), username_3, "stored username") do { try Keychain().set(password_1, key: "password") } catch {} XCTAssertEqual(try! Keychain().get("password"), password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_1).get("password"), password_1, "stored password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(try! Keychain(service: service_3).get("password"), "not stored password") do { try Keychain(service: service_1).set(password_1, key: "password") } catch {} XCTAssertEqual(try! Keychain().get("password"), password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_1).get("password"), password_1, "stored password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(try! Keychain(service: service_3).get("password"), "not stored password") do { try Keychain(service: service_2).set(password_2, key: "password") } catch {} XCTAssertEqual(try! Keychain().get("password"), password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_1).get("password"), password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_2).get("password"), password_2, "stored password") XCTAssertNil(try! Keychain(service: service_3).get("password"), "not stored password") do { try Keychain(service: service_3).set(password_3, key: "password") } catch {} XCTAssertEqual(try! Keychain().get("password"), password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_1).get("password"), password_1, "stored password") XCTAssertEqual(try! Keychain(service: service_2).get("password"), password_2, "stored password") XCTAssertEqual(try! Keychain(service: service_3).get("password"), password_3, "stored password") do { try Keychain().remove("username") } catch {} XCTAssertNil(try! Keychain().get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_1).get("username"), "removed username") XCTAssertEqual(try! Keychain(service: service_2).get("username"), username_2, "left username") XCTAssertEqual(try! Keychain(service: service_3).get("username"), username_3, "left username") do { try Keychain(service: service_1).remove("username") } catch {} XCTAssertNil(try! Keychain().get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_1).get("username"), "removed username") XCTAssertEqual(try! Keychain(service: service_2).get("username"), username_2, "left username") XCTAssertEqual(try! Keychain(service: service_3).get("username"), username_3, "left username") do { try Keychain(service: service_2).remove("username") } catch {} XCTAssertNil(try! Keychain().get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_1).get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_2).get("username"), "removed username") XCTAssertEqual(try! Keychain(service: service_3).get("username"), username_3, "left username") do { try Keychain(service: service_3).remove("username") } catch {} XCTAssertNil(try! Keychain().get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_1).get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_2).get("username"), "removed username") XCTAssertNil(try! Keychain(service: service_3).get("username"), "removed username") do { try Keychain().remove("password") } catch {} XCTAssertNil(try! Keychain().get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_1).get("password"), "removed password") XCTAssertEqual(try! Keychain(service: service_2).get("password"), password_2, "left password") XCTAssertEqual(try! Keychain(service: service_3).get("password"), password_3, "left password") do { try Keychain(service: service_1).remove("password") } catch {} XCTAssertNil(try! Keychain().get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_1).get("password"), "removed password") XCTAssertEqual(try! Keychain(service: service_2).get("password"), password_2, "left password") XCTAssertEqual(try! Keychain(service: service_3).get("password"), password_3, "left password") do { try Keychain(service: service_2).remove("password") } catch {} XCTAssertNil(try! Keychain().get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_1).get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "removed password") XCTAssertEqual(try! Keychain(service: service_3).get("password"), password_3, "left password") do { try Keychain(service: service_3).remove("password") } catch {} XCTAssertNil(try! Keychain().get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "removed password") XCTAssertNil(try! Keychain(service: service_2).get("password"), "removed password") } // MARK: func testProperties() { guard #available(OSX 10.10, *) else { return } let keychain = Keychain() XCTAssertEqual(keychain.synchronizable, false) XCTAssertEqual(keychain.synchronizable(true).synchronizable, true) XCTAssertEqual(keychain.synchronizable(false).synchronizable, false) XCTAssertEqual(keychain.accessibility(.AfterFirstUnlock).accessibility, Accessibility.AfterFirstUnlock) XCTAssertEqual(keychain.accessibility(.WhenPasscodeSetThisDeviceOnly, authenticationPolicy: .UserPresence).accessibility, Accessibility.WhenPasscodeSetThisDeviceOnly) XCTAssertEqual(keychain.accessibility(.WhenPasscodeSetThisDeviceOnly, authenticationPolicy: .UserPresence).authenticationPolicy, AuthenticationPolicy.UserPresence) XCTAssertNil(keychain.label) XCTAssertEqual(keychain.label("Label").label, "Label") XCTAssertNil(keychain.comment) XCTAssertEqual(keychain.comment("Comment").comment, "Comment") XCTAssertEqual(keychain.authenticationPrompt("Prompt").authenticationPrompt, "Prompt") } // MARK: #if os(iOS) func testAllKeys() { do { let keychain = Keychain() keychain["key1"] = "value1" keychain["key2"] = "value2" keychain["key3"] = "value3" let allKeys = keychain.allKeys() XCTAssertEqual(allKeys.count, 3) XCTAssertEqual(allKeys.sort(), ["key1", "key2", "key3"]) let allItems = keychain.allItems() XCTAssertEqual(allItems.count, 3) let sortedItems = allItems.sort { (item1, item2) -> Bool in let value1 = item1["value"] as! String let value2 = item2["value"] as! String return value1.compare(value2) == NSComparisonResult.OrderedAscending || value1.compare(value2) == NSComparisonResult.OrderedSame } XCTAssertEqual(sortedItems[0]["accessGroup"] as? String, "") XCTAssertEqual(sortedItems[0]["synchronizable"] as? String, "false") XCTAssertEqual(sortedItems[0]["service"] as? String, "") XCTAssertEqual(sortedItems[0]["value"] as? String, "value1") XCTAssertEqual(sortedItems[0]["key"] as? String, "key1") XCTAssertEqual(sortedItems[0]["class"] as? String, "GenericPassword") XCTAssertEqual(sortedItems[0]["accessibility"] as? String, "AfterFirstUnlock") XCTAssertEqual(sortedItems[1]["accessGroup"] as? String, "") XCTAssertEqual(sortedItems[1]["synchronizable"] as? String, "false") XCTAssertEqual(sortedItems[1]["service"] as? String, "") XCTAssertEqual(sortedItems[1]["value"] as? String, "value2") XCTAssertEqual(sortedItems[1]["key"] as? String, "key2") XCTAssertEqual(sortedItems[1]["class"] as? String, "GenericPassword") XCTAssertEqual(sortedItems[1]["accessibility"] as? String, "AfterFirstUnlock") XCTAssertEqual(sortedItems[2]["accessGroup"] as? String, "") XCTAssertEqual(sortedItems[2]["synchronizable"] as? String, "false") XCTAssertEqual(sortedItems[2]["service"] as? String, "") XCTAssertEqual(sortedItems[2]["value"] as? String, "value3") XCTAssertEqual(sortedItems[2]["key"] as? String, "key3") XCTAssertEqual(sortedItems[2]["class"] as? String, "GenericPassword") XCTAssertEqual(sortedItems[2]["accessibility"] as? String, "AfterFirstUnlock") } do { let keychain = Keychain(service: "service1") try! keychain .synchronizable(true) .accessibility(.WhenUnlockedThisDeviceOnly) .set("service1_value1", key: "service1_key1") try! keychain .synchronizable(false) .accessibility(.AfterFirstUnlockThisDeviceOnly) .set("service1_value2", key: "service1_key2") let allKeys = keychain.allKeys() XCTAssertEqual(allKeys.count, 2) XCTAssertEqual(allKeys.sort(), ["service1_key1", "service1_key2"]) let allItems = keychain.allItems() XCTAssertEqual(allItems.count, 2) let sortedItems = allItems.sort { (item1, item2) -> Bool in let value1 = item1["value"] as! String let value2 = item2["value"] as! String return value1.compare(value2) == NSComparisonResult.OrderedAscending || value1.compare(value2) == NSComparisonResult.OrderedSame } XCTAssertEqual(sortedItems[0]["accessGroup"] as? String, "") XCTAssertEqual(sortedItems[0]["synchronizable"] as? String, "true") XCTAssertEqual(sortedItems[0]["service"] as? String, "service1") XCTAssertEqual(sortedItems[0]["value"] as? String, "service1_value1") XCTAssertEqual(sortedItems[0]["key"] as? String, "service1_key1") XCTAssertEqual(sortedItems[0]["class"] as? String, "GenericPassword") XCTAssertEqual(sortedItems[0]["accessibility"] as? String, "WhenUnlockedThisDeviceOnly") XCTAssertEqual(sortedItems[1]["accessGroup"] as? String, "") XCTAssertEqual(sortedItems[1]["synchronizable"] as? String, "false") XCTAssertEqual(sortedItems[1]["service"] as? String, "service1") XCTAssertEqual(sortedItems[1]["value"] as? String, "service1_value2") XCTAssertEqual(sortedItems[1]["key"] as? String, "service1_key2") XCTAssertEqual(sortedItems[1]["class"] as? String, "GenericPassword") XCTAssertEqual(sortedItems[1]["accessibility"] as? String, "AfterFirstUnlockThisDeviceOnly") } do { let keychain = Keychain(server: "https://google.com", protocolType: .HTTPS) try! keychain .synchronizable(false) .accessibility(.AlwaysThisDeviceOnly) .set("google.com_value1", key: "google.com_key1") try! keychain .synchronizable(true) .accessibility(.Always) .set("google.com_value2", key: "google.com_key2") let allKeys = keychain.allKeys() XCTAssertEqual(allKeys.count, 2) XCTAssertEqual(allKeys.sort(), ["google.com_key1", "google.com_key2"]) let allItems = keychain.allItems() XCTAssertEqual(allItems.count, 2) let sortedItems = allItems.sort { (item1, item2) -> Bool in let value1 = item1["value"] as! String let value2 = item2["value"] as! String return value1.compare(value2) == NSComparisonResult.OrderedAscending || value1.compare(value2) == NSComparisonResult.OrderedSame } XCTAssertEqual(sortedItems[0]["synchronizable"] as? String, "false") XCTAssertEqual(sortedItems[0]["value"] as? String, "google.com_value1") XCTAssertEqual(sortedItems[0]["key"] as? String, "google.com_key1") XCTAssertEqual(sortedItems[0]["server"] as? String, "google.com") XCTAssertEqual(sortedItems[0]["class"] as? String, "InternetPassword") XCTAssertEqual(sortedItems[0]["authenticationType"] as? String, "Default") XCTAssertEqual(sortedItems[0]["protocol"] as? String, "HTTPS") XCTAssertEqual(sortedItems[0]["accessibility"] as? String, "AlwaysThisDeviceOnly") XCTAssertEqual(sortedItems[1]["synchronizable"] as? String, "true") XCTAssertEqual(sortedItems[1]["value"] as? String, "google.com_value2") XCTAssertEqual(sortedItems[1]["key"] as? String, "google.com_key2") XCTAssertEqual(sortedItems[1]["server"] as? String, "google.com") XCTAssertEqual(sortedItems[1]["class"] as? String, "InternetPassword") XCTAssertEqual(sortedItems[1]["authenticationType"] as? String, "Default") XCTAssertEqual(sortedItems[1]["protocol"] as? String, "HTTPS") XCTAssertEqual(sortedItems[1]["accessibility"] as? String, "Always") } do { let allKeys = Keychain.allKeys(.GenericPassword) XCTAssertEqual(allKeys.count, 5) let sortedKeys = allKeys.sort { (key1, key2) -> Bool in return key1.1.compare(key2.1) == NSComparisonResult.OrderedAscending || key1.1.compare(key2.1) == NSComparisonResult.OrderedSame } XCTAssertEqual(sortedKeys[0].0, "") XCTAssertEqual(sortedKeys[0].1, "key1") XCTAssertEqual(sortedKeys[1].0, "") XCTAssertEqual(sortedKeys[1].1, "key2") XCTAssertEqual(sortedKeys[2].0, "") XCTAssertEqual(sortedKeys[2].1, "key3") XCTAssertEqual(sortedKeys[3].0, "service1") XCTAssertEqual(sortedKeys[3].1, "service1_key1") XCTAssertEqual(sortedKeys[4].0, "service1") XCTAssertEqual(sortedKeys[4].1, "service1_key2") } do { let allKeys = Keychain.allKeys(.InternetPassword) XCTAssertEqual(allKeys.count, 2) let sortedKeys = allKeys.sort { (key1, key2) -> Bool in return key1.1.compare(key2.1) == NSComparisonResult.OrderedAscending || key1.1.compare(key2.1) == NSComparisonResult.OrderedSame } XCTAssertEqual(sortedKeys[0].0, "google.com") XCTAssertEqual(sortedKeys[0].1, "google.com_key1") XCTAssertEqual(sortedKeys[1].0, "google.com") XCTAssertEqual(sortedKeys[1].1, "google.com_key2") } } func testDescription() { do { let keychain = Keychain() XCTAssertEqual(keychain.description, "[]") XCTAssertEqual(keychain.debugDescription, "[]") } } #endif // MARK: func testAuthenticationPolicy() { guard #available(iOS 9.0, OSX 10.11, *) else { return } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.UserPresence] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } #if os(iOS) do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.UserPresence, .ApplicationPassword] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.UserPresence, .ApplicationPassword, .PrivateKeyUsage] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.ApplicationPassword] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.ApplicationPassword, .PrivateKeyUsage] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.PrivateKeyUsage] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny, .DevicePasscode] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny, .ApplicationPassword] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny, .ApplicationPassword, .PrivateKeyUsage] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDCurrentSet] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDCurrentSet, .DevicePasscode] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDCurrentSet, .ApplicationPassword] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDCurrentSet, .ApplicationPassword, .PrivateKeyUsage] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny, .Or, .DevicePasscode] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.TouchIDAny, .And, .DevicePasscode] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } #endif #if os(OSX) do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.UserPresence] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } do { let accessibility: Accessibility = .WhenPasscodeSetThisDeviceOnly let policy: AuthenticationPolicy = [.DevicePasscode] let flags = SecAccessControlCreateFlags(rawValue: policy.rawValue) var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, flags, &error) XCTAssertNil(error) XCTAssertNotNil(accessControl) } #endif } }
mit
667fa9b4988601f3eec19dcc4dc18272
44.187411
174
0.610872
5.404397
false
false
false
false
linhaosunny/yeehaiyake
椰海雅客微博/Pods/LSXPropertyTool/LSXPropertyTool/LSXPropertyTool/PropertyCodeMake/NSObject+Property.swift
2
6562
// // NSObject+Property.swift // LSXPropertyTool // // Created by 李莎鑫 on 2017/4/8. // Copyright © 2017年 李莎鑫. All rights reserved. // 属性代码生成底层处理 (仅支持swift3.+)工具使用如有问题,期待打脸QQ:120834064 // 邮箱:[email protected] import Foundation import UIKit extension NSObject { class func propertyCode(withFile file:String,withDictionary dictionary:[String:Any], update:((_ newData:String) -> Void)?,option: @escaping (_ name:String?,_ type:String?,_ value:Any?) -> Bool ) -> String { var code:String = "" var temp:String = "" let model = PropertyModel() for (key, value) in dictionary { //: 匹配关键字搜索转换 var keyName = key for i in 0..<maskKeyword.count { //: 如果匹配到为系统关键字转义 if key.compare(maskKeyword[i]) == .orderedSame { keyName = keyPreffix + key } } if option(keyName, propertyType(withValue: value), value) { model.propertyName = keyName model.propertyType = propertyType(withValue: value) temp = propertyTypeCode(propertyMode: model,withValue: value) code += temp //: 新增内容 if (file != "") && !file.contains(temp) { let index = file.index(file.endIndex, offsetBy: -updateEndIndex) let end = file.substring(from: index) var newfile = file.substring(to: index) newfile.append(temp + end) //: 更新新数据 if update != nil { update!(newfile) } return "new" } } } return code } class func propertyTypeCode(propertyMode model:PropertyModel,withValue value:Any) -> String { //: 如果属性名加了转义字符,注释中说明 var extesionNote = "." if (model.propertyName?.hasPrefix(keyPreffix))! { extesionNote = ".Noteice you are using system keywords,Now the property name [\(model.propertyName!)] is add Preffix [\(keyPreffix)] from origin name [\(model.propertyName?.substring(from: keyPreffix.endIndex))]." } let code = PropertyModel.propertyNote(noteString: "\(model.propertyName),\(model.propertyType)" + extesionNote) switch model.propertyType! { //: 处理数组类型 case swf3Array: let data = value as! NSArray if data.count == 0 { return code.appending(PropertyModel.propertyCodeArray(propertyName: model.propertyName!, popertyType: model.propertyType!,subPropertyType:swf3AnyObject)) } return propertySpecialArrayType(propertyMode: model, withValue: data[0], withNote: extesionNote) //: 处理数组字典类型 case swf3Dictionary: return code.appending(PropertyModel.propertyCodeObject(propertyName: model.propertyName!, popertyType: model.propertyName!.capitalized)) //: 处理通用对象类型 case swf3String,swf3AnyObject,swf3Any: return code.appending(PropertyModel.propertyCodeObject(propertyName: model.propertyName!, popertyType: model.propertyType!)) //: 处理Bool类型 case swf3Bool: return code.appending(PropertyModel.propertyCodeBool(propertyName: model.propertyName!, popertyType: model.propertyType!)) default: return code.appending(PropertyModel.propertyCode(propertyName: model.propertyName!, popertyType: model.propertyType!)) } } class func propertyType(withValue value:Any) -> String { switch propertyClassType(withValue: value) { case BaseStringType,String_Type: return swf3String case BaseNumberType,Number_Type: if propertySpecialBoolType(withValue: value) { return swf3Bool } return swf3Number case Bool_Type: return swf3Bool case BaseArrayType,Array_Type: return swf3Array case BaseDictionaryType,Dictionary_Type: return swf3Dictionary case BaseNullType: return swf3Any default: return swf3Any } } //: 推导真实类型 class func propertyClassType(withValue value:Any) -> String{ return NSStringFromClass((value as! NSObject).classForCoder) } class func propertySpecialBoolType(withValue value:Any) -> Bool { return (value as! NSObject).isKind(of: NSClassFromString(Bool_Type)!) } class func propertySpecialArrayType(propertyMode model:PropertyModel,withValue value:Any,withNote extesionNote:String) -> String{ let code = PropertyModel.propertyNote(noteString: "\(model.propertyName),\(model.propertyType)" + extesionNote) switch propertyClassType(withValue: value) { case BaseArrayType,Array_Type: return code.appending(PropertyModel.propertyCodeArray(propertyName: model.propertyName!, popertyType: model.propertyType!,subPropertyType:swf3Array)) case BaseDictionaryType,Dictionary_Type: return code.appending(PropertyModel.propertyCodeSpecialArray(propertyName: model.propertyName!, popertyType: model.propertyType!)) case BaseStringType,String_Type: return code.appending(PropertyModel.propertyCodeArray(propertyName: model.propertyName!, popertyType: model.propertyType!,subPropertyType:swf3String)) case BaseNumberType,Number_Type: if propertySpecialBoolType(withValue: value) { return code.appending(PropertyModel.propertyCodeArray(propertyName: model.propertyName!, popertyType: model.propertyType!,subPropertyType:swf3Bool)) } return code.appending(PropertyModel.propertyCodeArray(propertyName: model.propertyName!, popertyType: model.propertyType!,subPropertyType:swf3Number)) default: return code.appending(PropertyModel.propertyCodeArray(propertyName: model.propertyName!, popertyType: model.propertyType!,subPropertyType:swf3AnyObject)) } } }
mit
1b42b3daa30a8a551b2b57c9b7edeff6
41.463087
225
0.614351
5.102419
false
false
false
false
benlangmuir/swift
test/type/explicit_existential.swift
4
11418
// RUN: %target-typecheck-verify-swift protocol HasSelfRequirements { func foo(_ x: Self) func returnsOwnProtocol() -> any HasSelfRequirements } protocol Bar { init() func bar() -> any Bar } func useBarAsType(_ x: any Bar) {} protocol Pub : Bar { } func refinementErasure(_ p: any Pub) { useBarAsType(p) } typealias Compo = HasSelfRequirements & Bar struct CompoAssocType { typealias Compo = HasSelfRequirements & Bar } func useAsRequirement<T: HasSelfRequirements>(_ x: T) { } func useCompoAsRequirement<T: HasSelfRequirements & Bar>(_ x: T) { } func useCompoAliasAsRequirement<T: Compo>(_ x: T) { } func useNestedCompoAliasAsRequirement<T: CompoAssocType.Compo>(_ x: T) { } func useAsWhereRequirement<T>(_ x: T) where T: HasSelfRequirements {} func useCompoAsWhereRequirement<T>(_ x: T) where T: HasSelfRequirements & Bar {} func useCompoAliasAsWhereRequirement<T>(_ x: T) where T: Compo {} func useNestedCompoAliasAsWhereRequirement<T>(_ x: T) where T: CompoAssocType.Compo {} func useAsType(_: any HasSelfRequirements, _: any HasSelfRequirements & Bar, _: any Compo, _: any CompoAssocType.Compo) { } struct TypeRequirement<T: HasSelfRequirements> {} struct CompoTypeRequirement<T: HasSelfRequirements & Bar> {} struct CompoAliasTypeRequirement<T: Compo> {} struct NestedCompoAliasTypeRequirement<T: CompoAssocType.Compo> {} struct CompoTypeWhereRequirement<T> where T: HasSelfRequirements & Bar {} struct CompoAliasTypeWhereRequirement<T> where T: Compo {} struct NestedCompoAliasTypeWhereRequirement<T> where T: CompoAssocType.Compo {} struct Struct1<T> { } typealias T1 = Pub & Bar typealias T2 = any Pub & Bar protocol HasAssoc { associatedtype Assoc func foo() } do { enum MyError: Error { case bad(Any) } func checkIt(_ js: Any) throws { switch js { case let dbl as any HasAssoc: throw MyError.bad(dbl) default: fatalError("wrong") } } } func testHasAssoc(_ x: Any, _: any HasAssoc) { if let p = x as? any HasAssoc { p.foo() } struct ConformingType : HasAssoc { typealias Assoc = Int func foo() {} func method() -> any HasAssoc {} } } var b: any HasAssoc protocol P {} typealias MoreHasAssoc = HasAssoc & P func testHasMoreAssoc(_ x: Any) { if let p = x as? any MoreHasAssoc { p.foo() } } typealias X = Struct1<any Pub & Bar> _ = Struct1<any Pub & Bar>.self typealias AliasWhere<T> = T where T: HasAssoc, T.Assoc == any HasAssoc struct StructWhere<T> where T: HasAssoc, T.Assoc == any HasAssoc {} protocol ProtocolWhere where T == any HasAssoc { associatedtype T associatedtype U: HasAssoc where U.Assoc == any HasAssoc } extension HasAssoc where Assoc == any HasAssoc {} func FunctionWhere<T>(_: T) where T : HasAssoc, T.Assoc == any HasAssoc {} struct SubscriptWhere { subscript<T>(_: T) -> Int where T : HasAssoc, T.Assoc == any HasAssoc { get {} set {} } } struct OuterGeneric<T> { func contextuallyGenericMethod() where T == any HasAssoc {} } func testInvalidAny() { struct S: HasAssoc { typealias Assoc = Int func foo() {} } let _: any S = S() // expected-error{{'any' has no effect on concrete type 'S'}} func generic<T: HasAssoc>(t: T) { let _: any T = t // expected-error{{'any' has no effect on type parameter 'T'}} let _: any T.Assoc // expected-error {{'any' has no effect on type parameter 'T.Assoc'}} } let _: any ((S) -> Void) = generic // expected-error{{'any' has no effect on concrete type '(S) -> Void'}} } func anyAny() { let _: any Any let _: any AnyObject } protocol P1 {} protocol P2 {} protocol P3 {} do { // Test that we don't accidentally misparse an 'any' type as a 'some' type // and vice versa. let _: P1 & any P2 // expected-error {{'any' should appear at the beginning of a composition}} {{15-19=}} {{10-10=any }} let _: any P1 & any P2 // expected-error {{'any' should appear at the beginning of a composition}} {{19-23=}} let _: any P1 & P2 & any P3 // expected-error {{'any' should appear at the beginning of a composition}} {{24-28=}} let _: any P1 & some P2 // expected-error {{'some' should appear at the beginning of a composition}} {{19-24=}} let _: some P1 & any P2 // expected-error@-1 {{'some' type can only be declared on a single property declaration}} // expected-error@-2 {{'any' should appear at the beginning of a composition}} {{20-24=}} } struct ConcreteComposition: P1, P2 {} func testMetatypes() { let _: any P1.Type = ConcreteComposition.self let _: any (P1 & P2).Type = ConcreteComposition.self } func generic<T: any P1>(_ t: T) {} // expected-error {{type 'T' constrained to non-protocol, non-class type 'any P1'}} protocol RawRepresentable { associatedtype RawValue var rawValue: RawValue { get } } enum E1: RawRepresentable { typealias RawValue = P1 var rawValue: P1 { return ConcreteComposition() } } enum E2: RawRepresentable { typealias RawValue = any P1 var rawValue: any P1 { return ConcreteComposition() } } public protocol MyError {} extension MyError { static func ~=(lhs: any Error, rhs: Self) -> Bool { return true } } struct Wrapper { typealias E = Error } func typealiasMemberReferences(metatype: Wrapper.Type) { let _: Wrapper.E.Protocol = metatype.E.self let _: (any Wrapper.E).Type = metatype.E.self } func testAnyTypeExpr() { let _: (any P).Type = (any P).self func test(_: (any P).Type) {} test((any P).self) // expected-error@+2 {{expected member name or constructor call after type name}} // expected-note@+1 {{use '.self' to reference the type object}} let invalid = any P test(invalid) // Make sure 'any' followed by an identifier // on the next line isn't parsed as a type. func doSomething() {} let any = 10 let _ = any doSomething() } func hasInvalidExistential(_: any DoesNotExistIHope) {} // expected-error@-1 {{cannot find type 'DoesNotExistIHope' in scope}} protocol Input { associatedtype A } protocol Output { associatedtype A } // expected-error@+2{{use of protocol 'Input' as a type must be written 'any Input'}}{{30-35=any Input}} // expected-error@+1{{use of protocol 'Output' as a type must be written 'any Output'}}{{40-46=any Output}} typealias InvalidFunction = (Input) -> Output func testInvalidFunctionAlias(fn: InvalidFunction) {} typealias ExistentialFunction = (any Input) -> any Output func testFunctionAlias(fn: ExistentialFunction) {} typealias Constraint = Input func testConstraintAlias(x: Constraint) {} // expected-error{{use of 'Constraint' (aka 'Input') as a type must be written 'any Constraint'}}{{29-39=any Constraint}} typealias Existential = any Input func testExistentialAlias(x: Existential, y: any Constraint) {} // Reject explicit existential types in inheritance clauses protocol Empty {} struct S : any Empty {} // expected-error {{inheritance from non-protocol type 'any Empty'}} class C : any Empty {} // expected-error {{inheritance from non-protocol, non-class type 'any Empty'}} // FIXME: Diagnostics are not great in the enum case because we confuse this with a raw type enum E : any Empty { // expected-error {{raw type 'any Empty' is not expressible by a string, integer, or floating-point literal}} // expected-error@-1 {{'E' declares raw type 'any Empty', but does not conform to RawRepresentable and conformance could not be synthesized}} // expected-error@-2 {{RawRepresentable conformance cannot be synthesized because raw type 'any Empty' is not Equatable}} case hack } enum EE : Equatable, any Empty { // expected-error {{raw type 'any Empty' is not expressible by a string, integer, or floating-point literal}} // expected-error@-1 {{'EE' declares raw type 'any Empty', but does not conform to RawRepresentable and conformance could not be synthesized}} // expected-error@-2 {{RawRepresentable conformance cannot be synthesized because raw type 'any Empty' is not Equatable}} // expected-error@-3 {{raw type 'any Empty' must appear first in the enum inheritance clause}} case hack } func testAnyFixIt() { struct ConformingType : HasAssoc { typealias Assoc = Int func foo() {} func method() -> any HasAssoc {} } // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-18=any HasAssoc}} let _: HasAssoc = ConformingType() // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{19-27=any HasAssoc}} let _: Optional<HasAssoc> = nil // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-23=any HasAssoc.Type}} let _: HasAssoc.Type = ConformingType.self // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-25=any (HasAssoc).Type}} let _: (HasAssoc).Type = ConformingType.self // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-27=any ((HasAssoc)).Type}} let _: ((HasAssoc)).Type = ConformingType.self // expected-error@+2 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-18=(any HasAssoc)}} // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{30-38=(any HasAssoc)}} let _: HasAssoc.Protocol = HasAssoc.self // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{11-19=any HasAssoc}} let _: (HasAssoc).Protocol = (any HasAssoc).self // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-18=(any HasAssoc)}} let _: HasAssoc? = ConformingType() // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-23=(any HasAssoc.Type)}} let _: HasAssoc.Type? = ConformingType.self // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-18=(any HasAssoc)}} let _: HasAssoc.Protocol? = (any HasAssoc).self // expected-error@+1 {{optional 'any' type must be written '(any HasAssoc)?'}}{{10-23=(any HasAssoc)?}} let _: any HasAssoc? = nil // expected-error@+1 {{optional 'any' type must be written '(any HasAssoc.Type)?'}}{{10-28=(any HasAssoc.Type)?}} let _: any HasAssoc.Type? = nil } func testNestedMetatype() { let _: (any P.Type).Type = (any P.Type).self let _: (any (P.Type)).Type = (any P.Type).self let _: ((any (P.Type))).Type = (any P.Type).self } func testEnumAssociatedValue() { enum E { case c1((any HasAssoc) -> Void) // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}} case c2((HasAssoc) -> Void) case c3((P) -> Void) } } // https://github.com/apple/swift/issues/58920 typealias Iterator = any IteratorProtocol var example: any Iterator = 5 // expected-error{{redundant 'any' in type 'any Iterator' (aka 'any any IteratorProtocol')}} {{14-18=}} // expected-error@-1{{value of type 'Int' does not conform to specified type 'IteratorProtocol'}} var example1: any (any IteratorProtocol) = 5 // expected-error{{redundant 'any' in type 'any (any IteratorProtocol)'}} {{15-19=}} // expected-error@-1{{value of type 'Int' does not conform to specified type 'IteratorProtocol'}} protocol PP {} struct A : PP {} let _: any PP = A() // Ok let _: any (any PP) = A() // expected-error{{redundant 'any' in type 'any (any PP)'}} {{8-12=}}
apache-2.0
6ba839950d688497e8fdcc4e6d528684
32.098551
164
0.682869
3.785809
false
false
false
false