repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
FoodMob/FoodMob-iOS
FoodMob/ViewControllers/LoginViewController.swift
1
5928
// // LoginViewController.swift // FoodMob // // Created by Jonathan Jemson on 2/5/16. // Copyright © 2016 Jonathan Jemson. All rights reserved. // import UIKit /** Segues from Login View Controller to other controllers */ enum LoginViewControllerSegue: String { case ToMainSegue = "loginToMainSegue" case ToRegisterSegue = "loginToRegisterSegue" } class LoginViewController: UIViewController, UITextFieldDelegate { // MARK: - UI Elements @IBOutlet weak var emailAddressField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var bottomLayoutConstraint: NSLayoutConstraint! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var signUpButton: UIButton! private var tapRecognizer = UITapGestureRecognizer() private var keyboardShowing = false @IBOutlet var controls: [UIControl]! private var dispatchToken: dispatch_once_t = 0 // MARK: - Model Elements private var currentUser: User? // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() emailAddressField.delegate = self passwordField.delegate = self tapRecognizer.numberOfTapsRequired = 1 tapRecognizer.numberOfTouchesRequired = 1 tapRecognizer.addTarget(self, action: #selector(LoginViewController.hideKeyboard)) self.view.addGestureRecognizer(tapRecognizer) } func hideKeyboard() { self.emailAddressField.resignFirstResponder() self.passwordField.resignFirstResponder() keyboardShowing = false } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) dispatch_once(&dispatchToken) { [weak self] in self?.currentUser = User(emailAddress: nil) if self?.currentUser != nil { self?.performSegueWithIdentifier(LoginViewControllerSegue.ToMainSegue.rawValue, sender: nil) Session.sharedSession.currentUser = self?.currentUser } } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Text Field and Keyboard Management func textFieldShouldBeginEditing(textField: UITextField) -> Bool { return true } func textFieldShouldReturn(textField: UITextField) -> Bool { switch textField { case emailAddressField: passwordField.becomeFirstResponder() default: loginButtonPressed(UIButton()) textField.resignFirstResponder() } return true } func keyboardWillShow(notification: NSNotification) { guard keyboardShowing == false else { return } if let userInfo = notification.userInfo, keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { bottomLayoutConstraint.constant = keyboardSize.height + CGFloat(20) self.view.layoutIfNeeded() keyboardShowing = true } } func keyboardWillHide(notification: NSNotification) { bottomLayoutConstraint.constant = 0 keyboardShowing = false self.view.layoutIfNeeded() } // MARK: - Navigation override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { return true } @IBAction func loginButtonPressed(sender: UIButton) { controls.forEach { (control) in control.enabled = false } UIApplication.sharedApplication().networkActivityIndicatorVisible = true FoodMob.currentDataProvider.login(emailAddressField.safeText, password: passwordField.safeText) { [weak self] (user) -> () in if let user = user { self?.currentUser = user Session.sharedSession.currentUser = user self?.performSegueWithIdentifier(LoginViewControllerSegue.ToMainSegue.rawValue, sender: nil) } else { self?.alert("Log In Failed", message: "Check your email address and password, and try again.") } self?.controls.forEach({ (control) in control.enabled = true }) UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { super.prepareForSegue(segue, sender: sender) if let destination = segue.destinationViewController as? RegistrationViewController { destination.userDictionary = ["username": emailAddressField.text ?? "", "password": passwordField.text ?? ""] } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } @IBAction func unwindToLoginViewController(segue: UIStoryboardSegue) { if let registrationController = segue.sourceViewController as? RegistrationViewController { self.emailAddressField.text = registrationController.emailAddressField.text self.passwordField.text = registrationController.passwordField.text } } }
mit
d4e2a6698623996f82519045bcf1a930
35.58642
176
0.669647
5.833661
false
false
false
false
xuanyi0627/jetstream-ios
Jetstream/ScopeSyncReplyMessage.swift
1
3452
// // ScopeSyncReplyMessage.swift // Jetstream // // Copyright (c) 2014 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation struct SyncFragmentReply { var accepted: Bool = true var error: NSError? var modifications: [NSString: AnyObject]? } class ScopeSyncReplyMessage: ReplyMessage { class var messageType: String { return "ScopeSyncReply" } override var type: String { return ScopeSyncReplyMessage.messageType } let fragmentReplies: [SyncFragmentReply] init(index: UInt, replyTo: UInt, fragmentReplies: [SyncFragmentReply]) { self.fragmentReplies = fragmentReplies super.init(index: index, replyTo: replyTo) } override func serialize() -> [String: AnyObject] { assertionFailure("ScopeSyncReplyMessage cannot serialize itself") return [String: AnyObject]() } class func unserialize(dictionary: [String: AnyObject]) -> NetworkMessage? { var index = dictionary["index"] as? UInt var replyTo = dictionary["replyTo"] as? UInt var serializedFragmentReplies = dictionary["fragmentReplies"] as? [[String: AnyObject]] if index == nil || replyTo == nil || serializedFragmentReplies == nil { return nil } else { var fragmentReplies = [SyncFragmentReply]() for serializedFragmentReply in serializedFragmentReplies! { var accepted = true var error: NSError? var modifications = [NSString: AnyObject]() if let serializedError = serializedFragmentReply["error"] as? [String: AnyObject] { accepted = false error = errorFromDictionary(.SyncFragmentApplyError, serializedError) } if let serializedModifications = serializedFragmentReply["modifications"] as? [String: AnyObject] { modifications = serializedModifications } var fragmentReply = SyncFragmentReply(accepted: accepted, error: error, modifications: modifications) fragmentReplies.append(fragmentReply) } return ScopeSyncReplyMessage(index: index!, replyTo: replyTo!, fragmentReplies: fragmentReplies) } } }
mit
ffabb1551ac3443582b61e9160d10ccd
39.611765
117
0.658749
5.046784
false
false
false
false
glock45/swifter
Sources/Swifter/HttpRouter.swift
1
5068
// // HttpRouter.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // import Foundation public class HttpRouter { private class Node { var nodes = [String: Node]() var handler: ((HttpRequest) -> HttpResponse)? = nil } private var rootNode = Node() public init() { } public func routes() -> [String] { var routes = [String]() for (_, child) in rootNode.nodes { routes.append(contentsOf: routesForNode(child)); } return routes } private func routesForNode(_ node: Node, prefix: String = "") -> [String] { var result = [String]() if let _ = node.handler { result.append(prefix) } for (key, child) in node.nodes { result.append(contentsOf: routesForNode(child, prefix: prefix + "/" + key)); } return result } public func register(_ method: String?, path: String, handler: ((HttpRequest) -> HttpResponse)?) { var pathSegments = stripQuery(path).split("/") if let method = method { pathSegments.insert(method, at: 0) } else { pathSegments.insert("*", at: 0) } var pathSegmentsGenerator = pathSegments.makeIterator() inflate(&rootNode, generator: &pathSegmentsGenerator).handler = handler } public func route(_ method: String?, path: String) -> ([String: String], (HttpRequest) -> HttpResponse)? { if let method = method { let pathSegments = (method + "/" + stripQuery(path)).split("/") var pathSegmentsGenerator = pathSegments.makeIterator() var params = [String:String]() if let handler = findHandler(&rootNode, params: &params, generator: &pathSegmentsGenerator) { return (params, handler) } } let pathSegments = ("*/" + stripQuery(path)).split("/") var pathSegmentsGenerator = pathSegments.makeIterator() var params = [String:String]() if let handler = findHandler(&rootNode, params: &params, generator: &pathSegmentsGenerator) { return (params, handler) } return nil } private func inflate(_ node: inout Node, generator: inout IndexingIterator<[String]>) -> Node { if let pathSegment = generator.next() { if let _ = node.nodes[pathSegment] { return inflate(&node.nodes[pathSegment]!, generator: &generator) } var nextNode = Node() node.nodes[pathSegment] = nextNode return inflate(&nextNode, generator: &generator) } return node } private func findHandler(_ node: inout Node, params: inout [String: String], generator: inout IndexingIterator<[String]>) -> ((HttpRequest) -> HttpResponse)? { guard let pathToken = generator.next() else { // if it's the last element of the requested URL, check if there is a pattern with variable tail. if let variableNode = node.nodes.filter({ $0.0.characters.first == ":" }).first { if variableNode.value.nodes.isEmpty { params[variableNode.0] = "" return variableNode.value.handler } } return node.handler } let variableNodes = node.nodes.filter { $0.0.characters.first == ":" } if let variableNode = variableNodes.first { if variableNode.1.nodes.count == 0 { // if it's the last element of the pattern and it's a variable, stop the search and // append a tail as a value for the variable. let tail = generator.joined(separator: "/") if tail.characters.count > 0 { params[variableNode.0] = pathToken + "/" + tail } else { params[variableNode.0] = pathToken } return variableNode.1.handler } params[variableNode.0] = pathToken return findHandler(&node.nodes[variableNode.0]!, params: &params, generator: &generator) } if let _ = node.nodes[pathToken] { return findHandler(&node.nodes[pathToken]!, params: &params, generator: &generator) } if let _ = node.nodes["*"] { return findHandler(&node.nodes["*"]!, params: &params, generator: &generator) } if let startStarNode = node.nodes["**"] { let startStarNodeKeys = startStarNode.nodes.keys while let pathToken = generator.next() { if startStarNodeKeys.contains(pathToken) { return findHandler(&startStarNode.nodes[pathToken]!, params: &params, generator: &generator) } } } return nil } private func stripQuery(_ path: String) -> String { if let path = path.split("?").first { return path } return path } }
bsd-3-clause
4f27928cbcf442c25d9b66d28715b27d
37.679389
163
0.558516
4.665746
false
false
false
false
ZamzamInc/SwiftyPress
Sources/SwiftyPress/Views/UIKit/Controls/DataViews/PostsDataView/Cells/PopularPostCollectionViewCell.swift
1
4023
// // PopularPostCollectionViewCell.swift // Basem Emara // // Created by Basem Emara on 2018-06-24. // Copyright © 2018 Zamzam Inc. All rights reserved. // import UIKit import ZamzamCore public final class PopularPostCollectionViewCell: UICollectionViewCell { private let titleLabel = ThemedHeadline().apply { $0.font = .preferredFont(forTextStyle: .headline) $0.numberOfLines = 2 } private let summaryLabel = ThemedSubhead().apply { $0.font = .preferredFont(forTextStyle: .subheadline) $0.numberOfLines = 1 } private let featuredImage = ThemedImageView(imageNamed: .placeholder).apply { $0.contentMode = .scaleAspectFill $0.clipsToBounds = true } private lazy var favoriteButton = ThemedImageButton().apply { $0.setImage(UIImage(named: .favoriteEmpty), for: .normal) $0.setImage(UIImage(named: .favoriteFilled), for: .selected) $0.imageView?.contentMode = .scaleAspectFit $0.addTarget(self, action: #selector(didTapFavoriteButton), for: .touchUpInside) // Must be in lazy init } private var model: PostsDataViewModel? private weak var delegate: PostsDataViewDelegate? override init(frame: CGRect) { super.init(frame: frame) prepare() } @available(*, unavailable) required init?(coder: NSCoder) { nil } } // MARK: - Setup private extension PopularPostCollectionViewCell { func prepare() { let separator = ThemedSeparator() let favoriteView = UIView().apply { $0.backgroundColor = .clear $0.addSubview(favoriteButton) } let stackView = UIStackView(arrangedSubviews: [ featuredImage, UIStackView(arrangedSubviews: [ titleLabel.apply { $0.setContentHuggingPriority(.defaultHigh, for: .vertical) }, summaryLabel ]).apply { $0.axis = .vertical $0.spacing = 5 }, favoriteView ]).apply { $0.axis = .horizontal $0.spacing = 16 } let view = ThemedView().apply { $0.addSubview(stackView) } addSubview(view) addSubview(separator) view.edges(to: self) stackView.edges(to: view, insets: UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 18)) featuredImage.aspectRatioSize() favoriteView.widthAnchor.constraint(equalTo: favoriteButton.widthAnchor).isActive = true favoriteButton.widthAnchor.constraint(equalToConstant: 24).isActive = true favoriteButton.center() separator.translatesAutoresizingMaskIntoConstraints = false separator.heightAnchor.constraint(equalToConstant: 1).isActive = true separator.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor, constant: 0).isActive = true separator.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0).isActive = true separator.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0).isActive = true } } // MARK: - Interactions private extension PopularPostCollectionViewCell { @objc func didTapFavoriteButton() { favoriteButton.isSelected.toggle() guard let model = model else { return } delegate?.postsDataView(toggleFavorite: model) } } // MARK: - Delegates extension PopularPostCollectionViewCell: PostsDataViewCell { public func load(_ model: PostsDataViewModel) { self.model = model titleLabel.text = model.title summaryLabel.text = model.summary featuredImage.setImage(from: model.imageURL) favoriteButton.isSelected = model.favorite } public func load(_ model: PostsDataViewModel, delegate: PostsDataViewDelegate?) { self.delegate = delegate load(model) } }
mit
83fe751111b3233d4b72ba9a8671b3d1
30.178295
112
0.628294
4.977723
false
false
false
false
lingen/PandaDBSwift
PandaDBSwfit/TableBuilder.swift
1
3106
// // TableHelper.swift // PandaDBSwfit // // Created by lingen on 2016/9/24. // Copyright © 2016年 lingen.liu. All rights reserved. // import Foundation public class TableBuilder { private var columns:Array<Column> = [] private var primayColumns:Array<Column> = [] private var indexColumns:Array<Column> = [] private var tableName:String init(tableName:String) { self.tableName = tableName } public class func createInstance(tableName:String) -> TableBuilder { return TableBuilder(tableName: tableName); } public func column(name:String,type:ColumnType,nullable:Bool) -> TableBuilder { let column:Column = Column(name: name, type: type, nullable: nullable) columns.append(column) return self } public func primaryColumn(name:String,type:ColumnType) -> TableBuilder { let column:Column = Column(name: name, type: type, nullable: false) columns.append(column) primayColumns.append(column) return self } public func indexColumn(name:String,type:ColumnType) -> TableBuilder { let column:Column = Column(name: name, type: type) columns.append(column) indexColumns.append(column) return self } public func textColumn(name:String) -> TableBuilder { let column:Column = Column(name: name, type: .ColumnText) columns.append(column) return self; } public func textNoNullColumn(name:String) -> TableBuilder { let column:Column = Column(name: name, type: .ColumnText,nullable:false) columns.append(column) return self; } public func intColumn(name:String) -> TableBuilder { let column:Column = Column(name: name, type: .ColumnInt) columns.append(column) return self; } public func intNotNullColumn(name:String) -> TableBuilder { let column:Column = Column(name: name, type: .ColumnInt,nullable:false) columns.append(column) return self; } public func realColumn(name:String) -> TableBuilder { let column:Column = Column(name: name, type: .ColumnReal) columns.append(column) return self; } public func realNotNullColumn(name:String) -> TableBuilder { let column:Column = Column(name: name, type: .ColumnReal,nullable:false) columns.append(column) return self; } public func blobColumn(name:String) -> TableBuilder { let column:Column = Column(name: name, type: .ColumnBlob) columns.append(column) return self; } public func blobNotNullColumn(name:String) -> TableBuilder { let column:Column = Column(name: name, type: .ColumnBlob,nullable:false) columns.append(column) return self; } public func build() -> Table? { let table = Table(tableName: self.tableName, columns: self.columns, primaryColumns: self.primayColumns, indexColumns: self.indexColumns) return table } }
apache-2.0
ea67b68e0b89ce3e61fb3dbc844ec71f
29.126214
144
0.634869
4.137333
false
false
false
false
codingforentrepreneurs/Django-to-iOS
Source/ios/srvup/Notification.swift
1
2044
// // Notification.swift // srvup // // Created by Justin Mitchel on 6/23/15. // Copyright (c) 2015 Coding for Entrepreneurs. All rights reserved. // import UIKit public class Notification: NSObject { func notify(message:String, delay:Double, inSpeed:Double, outSpeed:Double) { let notification = UIView() let notificationText = UITextView() let application = UIApplication.sharedApplication() let window = application.keyWindow! self.fadeIn(notification, speed: inSpeed) notification.frame = CGRectMake(0, 0, window.frame.width, 50) notification.backgroundColor = .redColor() notification.addSubview(notificationText) notificationText.frame = CGRectMake(0, 0, notification.frame.width, 30) notificationText.frame.origin.y = (notification.frame.height - notificationText.frame.height)/2.0 notificationText.text = message notificationText.textAlignment = .Center notificationText.font = UIFont.systemFontOfSize(18.0) notificationText.textColor = .whiteColor() notificationText.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.0) window.addSubview(notification) let seconds = delay let delayNanoSeconds = seconds * Double(NSEC_PER_SEC) let now = DISPATCH_TIME_NOW var theTimeToDispatch = dispatch_time(now, Int64(delayNanoSeconds)) dispatch_after(theTimeToDispatch, dispatch_get_main_queue()) { () -> Void in self.fadeOut(notification, speed:outSpeed) // self.notification.removeFromSuperview() } } func fadeIn(theView:UIView, speed:Double) { theView.alpha = 0 UIView.animateWithDuration(speed, animations: { () -> Void in theView.alpha = 1 }) } func fadeOut(theView:UIView, speed:Double) { UIView.animateWithDuration(speed, animations: { () -> Void in theView.alpha = 0 }) } }
apache-2.0
b6b6b89dbb622218b788912c28539842
33.644068
105
0.641879
4.414687
false
false
false
false
liuxuan30/ios-charts
ChartsDemo-iOS/Swift/Demos/ScatterChartViewController.swift
3
4109
// // ScatterChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // #if canImport(UIKit) import UIKit #endif import Charts class ScatterChartViewController: DemoBaseViewController { @IBOutlet var chartView: ScatterChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Scatter Chart" self.options = [.toggleValues, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData] chartView.delegate = self chartView.chartDescription?.enabled = false chartView.dragEnabled = true chartView.setScaleEnabled(true) chartView.maxVisibleCount = 200 chartView.pinchZoomEnabled = true let l = chartView.legend l.horizontalAlignment = .right l.verticalAlignment = .top l.orientation = .vertical l.drawInside = false l.font = .systemFont(ofSize: 10, weight: .light) l.xOffset = 5 let leftAxis = chartView.leftAxis leftAxis.labelFont = .systemFont(ofSize: 10, weight: .light) leftAxis.axisMinimum = 0 chartView.rightAxis.enabled = false let xAxis = chartView.xAxis xAxis.labelFont = .systemFont(ofSize: 10, weight: .light) sliderX.value = 45 sliderY.value = 100 slidersValueChanged(nil) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value + 1), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let values1 = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 3) return ChartDataEntry(x: Double(i), y: val) } let values2 = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 3) return ChartDataEntry(x: Double(i) + 0.33, y: val) } let values3 = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 3) return ChartDataEntry(x: Double(i) + 0.66, y: val) } let set1 = ScatterChartDataSet(entries: values1, label: "DS 1") set1.setScatterShape(.square) set1.setColor(ChartColorTemplates.colorful()[0]) set1.scatterShapeSize = 8 let set2 = ScatterChartDataSet(entries: values2, label: "DS 2") set2.setScatterShape(.circle) set2.scatterShapeHoleColor = ChartColorTemplates.colorful()[3] set2.scatterShapeHoleRadius = 3.5 set2.setColor(ChartColorTemplates.colorful()[1]) set2.scatterShapeSize = 8 let set3 = ScatterChartDataSet(entries: values3, label: "DS 3") set3.setScatterShape(.cross) set3.setColor(ChartColorTemplates.colorful()[2]) set3.scatterShapeSize = 8 let data = ScatterChartData(dataSets: [set1, set2, set3]) data.setValueFont(.systemFont(ofSize: 7, weight: .light)) chartView.data = data } override func optionTapped(_ option: Option) { super.handleOption(option, forChartView: chartView) } @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } }
apache-2.0
8596a1bf11d56e76eb9ca6572c0c0832
31.603175
79
0.581548
4.716418
false
false
false
false
ubi-naist/SenStick
SenStickSDK/SenStickSDK/SenStickDevice.swift
1
12670
// // SenStickDevice.swift // SenStickSDK // // Created by AkihiroUehara on 2016/03/15. // Copyright © 2016年 AkihiroUehara. All rights reserved. // import Foundation import CoreBluetooth public protocol SenStickDeviceDelegate : class { func didServiceFound(_ sender:SenStickDevice) func didConnected(_ sender:SenStickDevice) func didDisconnected(_ sender:SenStickDevice) } // デバイスを表します。 // // 全てのプロパティは、KVO準拠です。 // // nameはデバイス名を表します。 // identifierは、デバイスの識別子を表します。この識別子は、そのiPhoneからみたデバイスの識別子です。同じBLEデバイスでも、別のiPhoneでは、識別子は異なります。 // // 接続と切断。 // 接続と切断はそれぞれ connect()メソッド, cancelConnect()メソッドで行います。 // 接続状態は isConnectedプロパティ で取得できます。 open class SenStickDevice : NSObject, CBPeripheralDelegate { // MARK: variables open unowned let manager: CBCentralManager open let peripheral: CBPeripheral open weak var delegate: SenStickDeviceDelegate? // MARK: Properties open fileprivate(set) var isConnected: Bool open var name: String open fileprivate(set) var identifier: UUID open fileprivate(set) var deviceInformationService: DeviceInformationService? open fileprivate(set) var batteryLevelService: BatteryService? open fileprivate(set) var controlService: SenStickControlService? open fileprivate(set) var metaDataService: SenStickMetaDataService? open fileprivate(set) var accelerationSensorService: AccelerationSensorService? open fileprivate(set) var gyroSensorService: GyroSensorService? open fileprivate(set) var magneticFieldSensorService: MagneticFieldSensorService? open fileprivate(set) var brightnessSensorService: BrightnessSensorService? open fileprivate(set) var uvSensorService: UVSensorService? open fileprivate(set) var humiditySensorService: HumiditySensorService? open fileprivate(set) var pressureSensorService: PressureSensorService? // MARK: initializer init(manager: CBCentralManager, peripheral:CBPeripheral, name: String?) { self.manager = manager self.peripheral = peripheral self.isConnected = false self.name = name ?? peripheral.name ?? "" self.identifier = peripheral.identifier super.init() self.peripheral.delegate = self if self.peripheral.state == .connected { self.isConnected = true findSensticServices() } } // Internal , device managerが呼び出します internal func onConnected() { self.isConnected = true DispatchQueue.main.async(execute: { self.delegate?.didConnected(self) }) findSensticServices() } internal func onDisConnected() { self.isConnected = false self.deviceInformationService = nil self.batteryLevelService = nil self.controlService = nil self.metaDataService = nil self.accelerationSensorService = nil self.magneticFieldSensorService = nil self.gyroSensorService = nil self.brightnessSensorService = nil self.uvSensorService = nil self.humiditySensorService = nil self.pressureSensorService = nil DispatchQueue.main.async(execute: { self.delegate?.didDisconnected(self) }) } // Private methods func findSensticServices() { // サービスの発見 let serviceUUIDs = Array(SenStickUUIDs.SenStickServiceUUIDs.keys) peripheral.discoverServices(serviceUUIDs) } // MARK: Public methods open func connect() { if peripheral.state == .disconnected || peripheral.state == .disconnecting { manager.connect(peripheral, options:nil) } } open func cancelConnection() { manager.cancelPeripheralConnection(peripheral) } // MARK: CBPeripheralDelegate // サービスの発見、次にキャラクタリスティクスの検索をする open func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { // エラーなきことを確認 if error != nil { debugPrint("Unexpected error in \(#function), \(String(describing: error)).") return } // FIXME サービスが一部なかった場合などは、どのような処理になる? すべてのサービスが発見できなければエラー? for service in peripheral.services! { let characteristicsUUIDs = SenStickUUIDs.SenStickServiceUUIDs[service.uuid] peripheral.discoverCharacteristics(characteristicsUUIDs, for: service) } } // サービスのインスタンスを作る open func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { // エラーなきことを確認 if error != nil { debugPrint("Unexpected error in \(#function), \(String(describing: error)).") return } // FIXME キャラクタリスティクスが発見できないサービスがあった場合、コールバックに通知が来ない。タイムアウトなどで処理する? // debugPrint("\(#function), \(service.UUID).") // すべてのサービスのキャラクタリスティクスが発見できれば、インスタンスを生成 switch service.uuid { case SenStickUUIDs.DeviceInformationServiceUUID: self.deviceInformationService = DeviceInformationService(device:self) case SenStickUUIDs.BatteryServiceUUID: self.batteryLevelService = BatteryService(device:self) case SenStickUUIDs.ControlServiceUUID: self.controlService = SenStickControlService(device: self) case SenStickUUIDs.MetaDataServiceUUID: self.metaDataService = SenStickMetaDataService(device: self) case SenStickUUIDs.accelerationSensorServiceUUID: self.accelerationSensorService = AccelerationSensorService(device: self) case SenStickUUIDs.gyroSensorServiceUUID: self.gyroSensorService = GyroSensorService(device: self) case SenStickUUIDs.magneticFieldSensorServiceUUID: self.magneticFieldSensorService = MagneticFieldSensorService(device: self) case SenStickUUIDs.brightnessSensorServiceUUID: self.brightnessSensorService = BrightnessSensorService(device: self) case SenStickUUIDs.uvSensorServiceUUID: self.uvSensorService = UVSensorService(device: self) case SenStickUUIDs.humiditySensorServiceUUID: self.humiditySensorService = HumiditySensorService(device: self) case SenStickUUIDs.pressureSensorServiceUUID: self.pressureSensorService = PressureSensorService(device: self) default: debugPrint("\(#function):unexpected service is found, \(service)" ) break } DispatchQueue.main.async(execute: { self.delegate?.didServiceFound(self) }) } open func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if error != nil { debugPrint("didUpdate: \(characteristic.uuid) \(String(describing: error))") return } // キャラクタリスティクスから[UInt8]を取り出す。なければreturn。 guard let characteristics_nsdata = characteristic.value else { return } var data = [UInt8](repeating: 0, count: characteristics_nsdata.count) (characteristics_nsdata as NSData).getBytes(&data, length: data.count) //debugPrint("didUpdate: \(characteristic.uuid) \(data)") switch characteristic.service.uuid { case SenStickUUIDs.DeviceInformationServiceUUID: self.deviceInformationService?.didUpdateValue(characteristic, data: data) case SenStickUUIDs.BatteryServiceUUID: self.batteryLevelService?.didUpdateValue(characteristic, data: data) case SenStickUUIDs.ControlServiceUUID: self.controlService?.didUpdateValue(characteristic, data: data) case SenStickUUIDs.MetaDataServiceUUID: self.metaDataService?.didUpdateValue(characteristic, data: data) case SenStickUUIDs.accelerationSensorServiceUUID: self.accelerationSensorService?.didUpdateValue(characteristic, data: data) case SenStickUUIDs.gyroSensorServiceUUID: self.gyroSensorService?.didUpdateValue(characteristic, data: data) case SenStickUUIDs.magneticFieldSensorServiceUUID: self.magneticFieldSensorService?.didUpdateValue(characteristic, data: data) case SenStickUUIDs.brightnessSensorServiceUUID: self.brightnessSensorService?.didUpdateValue(characteristic, data: data) case SenStickUUIDs.uvSensorServiceUUID: self.uvSensorService?.didUpdateValue(characteristic, data: data) case SenStickUUIDs.humiditySensorServiceUUID: self.humiditySensorService?.didUpdateValue(characteristic, data: data) case SenStickUUIDs.pressureSensorServiceUUID: self.pressureSensorService?.didUpdateValue(characteristic, data: data) default: break } } open func peripheralDidUpdateName(_ peripheral: CBPeripheral) { self.name = peripheral.name ?? "(unknown)" } // optional public func peripheral(peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) // optional public func peripheral(peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: NSError?) // optional public func peripheral(peripheral: CBPeripheral, didDiscoverIncludedServicesForService service: CBService, error: NSError?) // optional public func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) // optional public func peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic, error: NSError?) // optional public func peripheral(peripheral: CBPeripheral, didDiscoverDescriptorsForCharacteristic characteristic: CBCharacteristic, error: NSError?) // optional public func peripheral(peripheral: CBPeripheral, didUpdateValueForDescriptor descriptor: CBDescriptor, error: NSError?) // optional public func peripheral(peripheral: CBPeripheral, didWriteValueForDescriptor descriptor: CBDescriptor, error: NSError?) } // サービスなど発見のヘルパーメソッド extension SenStickDevice { // ペリフェラルから指定したUUIDのCBServiceを取得します func findService(_ uuid: CBUUID) -> CBService? { return (self.peripheral.services?.filter{$0.uuid == uuid}.first) } // 指定したUUIDのCharacteristicsを取得します func findCharacteristic(_ service: CBService, uuid: CBUUID) -> CBCharacteristic? { return (service.characteristics?.filter{$0.uuid == uuid}.first) } } // SenstickServiceが呼び出すメソッド extension SenStickDevice { // Notificationを設定します。コールバックはdidUpdateValueの都度呼びだされます。初期値を読みだすために、enabeledがtrueなら初回の読み出しが実行されます。 internal func setNotify(_ characteristic: CBCharacteristic, enabled: Bool) { peripheral.setNotifyValue(enabled, for: characteristic) } // 値読み出しを要求します internal func readValue(_ characteristic: CBCharacteristic) { peripheral.readValue(for: characteristic) } // 値の書き込み internal func writeValue(_ characteristic: CBCharacteristic, value: [UInt8]) { let data = Data(bytes: UnsafePointer<UInt8>(value), count: value.count) // peripheral.writeValue( data, forCharacteristic: characteristic, type: .WithoutResponse) peripheral.writeValue( data, for: characteristic, type: .withResponse) //debugPrint("writeValue: \(characteristic.uuid) \(value)") } }
mit
02782e5a34a77455dfa4c3f6fdd8d3ad
39.681818
162
0.689729
4.635458
false
false
false
false
Romdeau4/16POOPS
Helps_Kitchen_iOS/Help's Kitchen/WaitingViewController.swift
1
2777
// // WaitingViewController.swift // Help's Kitchen // // Created by Stephen Ulmer on 2/13/17. // Copyright © 2017 Stephen Ulmer. All rights reserved. // import UIKit import Firebase class WaitingViewController: UIViewController { let ref = FIRDatabase.database().reference(fromURL: DataAccess.URL) let timeLeftLabel: UILabel = { let tll = UILabel() tll.translatesAutoresizingMaskIntoConstraints = false tll.backgroundColor = UIColor.black tll.textColor = UIColor.white tll.text = "X Minutes Remaining" return tll }() let tempButton: UIButton = { let tb = UIButton() tb.translatesAutoresizingMaskIntoConstraints = false tb.setTitle("Temp", for: .normal) tb.addTarget(self, action: #selector(handleSeated), for: .touchUpInside) tb.backgroundColor = UIColor.black return tb }() func handleSeated() { guard let uid = FIRAuth.auth()?.currentUser?.uid else{ return } ref.child("users").child(uid).child("customerIsSeated").setValue(true) dismiss(animated: true, completion: nil) } func handleCancel(){ guard let uid = FIRAuth.auth()?.currentUser?.uid else{ return } //TODO add reservation functionality ref.child("users").child(uid).child("customerHasReservation").setValue(false) dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white // Do any additional setup after loading the view. navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel)) view.addSubview(timeLeftLabel) view.addSubview(tempButton) setupTimeLeftLabel() setupTempButton() } func setupTimeLeftLabel() { timeLeftLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true timeLeftLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true timeLeftLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true timeLeftLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true } func setupTempButton() { tempButton.topAnchor.constraint(equalTo: timeLeftLabel.bottomAnchor, constant: 50).isActive = true tempButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true tempButton.heightAnchor.constraint(equalToConstant: 50).isActive = true tempButton.widthAnchor.constraint(equalToConstant: 150).isActive = true } }
mit
4a818cd42356d925f8a76943e51b2014
32.445783
137
0.655259
4.939502
false
false
false
false
Baddaboo/EasyLayout
Framework/Core Layout/EasyLayout.swift
1
15436
// // EasyLayout.swift // Example // // Created by Blake Tsuzaki on 7/30/17. // Copyright © 2017 Modoki. All rights reserved. // #if os(iOS) import UIKit public typealias View = UIView public typealias ViewController = UIViewController public typealias LayoutAttribute = NSLayoutAttribute #elseif os(OSX) import AppKit public typealias View = NSView public typealias ViewController = NSViewController public typealias LayoutAttribute = NSLayoutConstraint.Attribute #endif @objc public enum EasyLayoutUpdatePriority: Int { case now, eventually, whenever } public class EasyLayoutToken: NSObject { var attribute: LayoutAttribute? var view: View var multiplier: CGFloat var constant: CGFloat fileprivate static let leftAttributeError = "Left operand layout attribute cannot be nil" convenience init(attribute: LayoutAttribute?, view: View) { self.init(attribute: attribute, view: view, multiplier: 1, constant: 0) } init(attribute: LayoutAttribute?, view: View, multiplier: CGFloat, constant: CGFloat) { self.attribute = attribute self.view = view self.multiplier = multiplier self.constant = constant super.init() } } public extension EasyLayoutToken { @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func equalTo(view: View) -> NSLayoutConstraint { return equalTo(view: view, multiplier: 1, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func equalTo(view: View, multiplier: CGFloat) -> NSLayoutConstraint { return equalTo(view: view, multiplier: multiplier, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func equalTo(view: View, offset: CGFloat) -> NSLayoutConstraint { return equalTo(view: view, multiplier: 1, offset: offset) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func equalTo(view: View, multiplier: CGFloat, offset: CGFloat) -> NSLayoutConstraint { return equalTo(EasyLayoutToken(attribute: attribute, view: view), multiplier: multiplier, offset: offset) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func equalTo(_ token: EasyLayoutToken) -> NSLayoutConstraint { return equalTo(token, multiplier: 1, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func equalTo(_ token: EasyLayoutToken, multiplier: CGFloat) -> NSLayoutConstraint { return equalTo(token, multiplier: multiplier, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func equalTo(_ token: EasyLayoutToken, offset: CGFloat) -> NSLayoutConstraint { return equalTo(token, multiplier: 1, offset: offset) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func equalTo(_ token: EasyLayoutToken, multiplier: CGFloat, offset: CGFloat) -> NSLayoutConstraint { return self == token * multiplier + offset } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func lessThan(view: View) -> NSLayoutConstraint { return lessThan(view: view, multiplier: 1, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func lessThan(view: View, multiplier: CGFloat) -> NSLayoutConstraint { return lessThan(view: view, multiplier: multiplier, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func lessThan(view: View, offset: CGFloat) -> NSLayoutConstraint { return lessThan(view: view, multiplier: 1, offset: offset) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func lessThan(view: View, multiplier: CGFloat, offset: CGFloat) -> NSLayoutConstraint { return lessThan(EasyLayoutToken(attribute: attribute, view: view), multiplier: multiplier, offset: offset) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func lessThan(_ token: EasyLayoutToken) -> NSLayoutConstraint { return lessThan(token, multiplier: 1, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func lessThan(_ token: EasyLayoutToken, multiplier: CGFloat) -> NSLayoutConstraint { return lessThan(token, multiplier: multiplier, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func lessThan(_ token: EasyLayoutToken, offset: CGFloat) -> NSLayoutConstraint { return lessThan(token, multiplier: 1, offset: offset) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func lessThan(_ token: EasyLayoutToken, multiplier: CGFloat, offset: CGFloat) -> NSLayoutConstraint { return self < token * multiplier + offset } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func greaterThan(view: View) -> NSLayoutConstraint { return greaterThan(view: view, multiplier: 1, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func greaterThan(view: View, multiplier: CGFloat) -> NSLayoutConstraint { return greaterThan(view: view, multiplier: multiplier, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func greaterThan(view: View, offset: CGFloat) -> NSLayoutConstraint { return greaterThan(view: view, multiplier: 1, offset: offset) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func greaterThan(view: View, multiplier: CGFloat, offset: CGFloat) -> NSLayoutConstraint { return greaterThan(EasyLayoutToken(attribute: attribute, view: view), multiplier: multiplier, offset: offset) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func greaterThan(_ token: EasyLayoutToken) -> NSLayoutConstraint { return greaterThan(token, multiplier: 1, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func greaterThan(_ token: EasyLayoutToken, multiplier: CGFloat) -> NSLayoutConstraint { return greaterThan(token, multiplier: multiplier, offset: 0) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func greaterThan(_ token: EasyLayoutToken, offset: CGFloat) -> NSLayoutConstraint { return greaterThan(token, multiplier: 1, offset: offset) } @available(swift, deprecated: 0.1, message: "For use in Objective C code only") @objc public func greaterThan(_ token: EasyLayoutToken, multiplier: CGFloat, offset: CGFloat) -> NSLayoutConstraint { return self > token * multiplier + offset } static func == (left: EasyLayoutToken, right: EasyLayoutToken) -> NSLayoutConstraint { guard let leftAttribute = left.attribute else { fatalError(leftAttributeError) } return NSLayoutConstraint(item: left.view, attribute: leftAttribute, relatedBy: .equal, toItem: right.view, attribute: right.attribute ?? leftAttribute, multiplier: left.multiplier * right.multiplier, constant: left.constant + right.constant) } static func == (left: EasyLayoutToken, right: View) -> NSLayoutConstraint { guard let leftAttribute = left.attribute else { fatalError(leftAttributeError) } return NSLayoutConstraint(item: left.view, attribute: leftAttribute, relatedBy: .equal, toItem: right, attribute: leftAttribute, multiplier: left.multiplier, constant: left.constant) } static func == (left: View, right: EasyLayoutToken) -> NSLayoutConstraint { return right == left } static func == (left: EasyLayoutToken, right: CGFloat) -> NSLayoutConstraint { guard let leftAttribute = left.attribute else { fatalError(leftAttributeError) } return NSLayoutConstraint(item: left.view, attribute: leftAttribute, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: left.multiplier, constant: left.constant) } static func == (left: CGFloat, right: EasyLayoutToken) -> NSLayoutConstraint { return right == left } static func < (left: EasyLayoutToken, right: EasyLayoutToken) -> NSLayoutConstraint { guard let leftAttribute = left.attribute else { fatalError(leftAttributeError) } return NSLayoutConstraint(item: left.view, attribute: leftAttribute, relatedBy: .lessThanOrEqual, toItem: right.view, attribute: right.attribute ?? leftAttribute, multiplier: left.multiplier * right.multiplier, constant: left.constant + right.constant) } static func < (left: EasyLayoutToken, right: View) -> NSLayoutConstraint { guard let leftAttribute = left.attribute else { fatalError(leftAttributeError) } return NSLayoutConstraint(item: left.view, attribute: leftAttribute, relatedBy: .lessThanOrEqual, toItem: right, attribute: leftAttribute, multiplier: left.multiplier, constant: left.constant) } static func > (left: View, right: EasyLayoutToken) -> NSLayoutConstraint { return right < left } static func < (left: EasyLayoutToken, right: CGFloat) -> NSLayoutConstraint { guard let leftAttribute = left.attribute else { fatalError(leftAttributeError) } return NSLayoutConstraint(item: left.view, attribute: leftAttribute, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: left.multiplier, constant: left.constant) } static func > (left: CGFloat, right: EasyLayoutToken) -> NSLayoutConstraint { return right < left } static func <= (left: EasyLayoutToken, right: EasyLayoutToken) -> NSLayoutConstraint { return left < right } static func <= (left: EasyLayoutToken, right: View) -> NSLayoutConstraint { return left < right } static func <= (left: EasyLayoutToken, right: CGFloat) -> NSLayoutConstraint { return left < right } static func > (left: EasyLayoutToken, right: EasyLayoutToken) -> NSLayoutConstraint { guard let leftAttribute = left.attribute else { fatalError(leftAttributeError) } return NSLayoutConstraint(item: left.view, attribute: leftAttribute, relatedBy: .greaterThanOrEqual, toItem: right.view, attribute: right.attribute ?? leftAttribute, multiplier: left.multiplier * right.multiplier, constant: left.constant + right.constant) } static func > (left: EasyLayoutToken, right: View) -> NSLayoutConstraint { guard let leftAttribute = left.attribute else { fatalError(leftAttributeError) } return NSLayoutConstraint(item: left.view, attribute: leftAttribute, relatedBy: .greaterThanOrEqual, toItem: right, attribute: leftAttribute, multiplier: left.multiplier, constant: left.constant) } static func < (left: View, right: EasyLayoutToken) -> NSLayoutConstraint { return right > left } static func > (left: EasyLayoutToken, right: CGFloat) -> NSLayoutConstraint { guard let leftAttribute = left.attribute else { fatalError(leftAttributeError) } return NSLayoutConstraint(item: left.view, attribute: leftAttribute, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: left.multiplier, constant: left.constant) } static func < (left: CGFloat, right: EasyLayoutToken) -> NSLayoutConstraint { return right > left } static func >= (left: EasyLayoutToken, right: EasyLayoutToken) -> NSLayoutConstraint { return left > right } static func >= (left: EasyLayoutToken, right: View) -> NSLayoutConstraint { return left > right } static func >= (left: EasyLayoutToken, right: CGFloat) -> NSLayoutConstraint { return left > right } static func * (left: EasyLayoutToken, right: CGFloat) -> EasyLayoutToken { return EasyLayoutToken(attribute: left.attribute, view: left.view, multiplier: right, constant: left.constant) } static func * (left: CGFloat, right: EasyLayoutToken) -> EasyLayoutToken { return right * left } static func / (left: EasyLayoutToken, right: CGFloat) -> EasyLayoutToken { return left * (1 / right) } static func + (left: EasyLayoutToken, right: CGFloat) -> EasyLayoutToken { return EasyLayoutToken(attribute: left.attribute, view: left.view, multiplier: left.multiplier, constant: right) } static func + (left: CGFloat, right: EasyLayoutToken) -> EasyLayoutToken { return right + left } static func - (left: EasyLayoutToken, right: CGFloat) -> EasyLayoutToken { return left + (-right) } static func - (left: CGFloat, right: EasyLayoutToken) -> EasyLayoutToken { return right + (-left) } }
mit
1f385e4b2ab59dc47fc7a28d0b9db4e2
44.131579
121
0.606868
5.080645
false
false
false
false
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Entities/NetworkRequestEntity.swift
2
4041
// // NetworkRequestEntity.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 09/09/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import Foundation //import AlamofireObjectMapper //import ObjectMapper let kNetworkRequestBaseUrlKey = "baseUrl" let kNetworkRequestRelativeUrlKey = "relativeUrl" let kNetworkRequestMethodKey = "method" let kNetworkRequestGroupKey = "group" protocol NetworkRequestEntityProtocol: ParsableEntityProtocol { var baseUrl: String? {get set} var relativeUrl: String! {get set} var method: String! {get set} var group: String? {get set} } class NetworkRequestEntity: NetworkRequestEntityProtocol { // MARK: NetworkRequestEntityProtocol var baseUrl: String? var relativeUrl: String! var method: String! var group: String? /*override init() { super.init() } // This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point convenience required init?(map: Map) { self.init() } // Mappable func mapping(map: Map) { baseUrl <- map[kNetworkRequestBaseUrlKey] relativeUrl <- map[kNetworkRequestRelativeUrlKey] method <- map[kNetworkRequestMethodKey] group <- map[kNetworkRequestGroupKey] }*/ // Custom init(backendEnvironment: BackendEnvironmentType) { // Auto pick environment for app config request switch (backendEnvironment) { case .production: baseUrl = ConstantsBackendEnvironment.production.baseUrl relativeUrl = ConstantsBackendEnvironment.production.relativeUrl method = ConstantsBackendEnvironment.production.method break; case .staging: baseUrl = ConstantsBackendEnvironment.staging.baseUrl relativeUrl = ConstantsBackendEnvironment.staging.relativeUrl method = ConstantsBackendEnvironment.staging.method break; case .development: baseUrl = ConstantsBackendEnvironment.development.baseUrl relativeUrl = ConstantsBackendEnvironment.development.relativeUrl method = ConstantsBackendEnvironment.development.method break; } } required init(dict: Dictionary <String, Any>) { // as! is a forced downcast baseUrl = dict[kNetworkRequestBaseUrlKey] as? String; relativeUrl = dict[kNetworkRequestRelativeUrlKey] as! String; method = dict[kNetworkRequestMethodKey] as! String; group = dict[kNetworkRequestGroupKey] as? String; } func serializedDict()-> Dictionary <String, Any>? { return nil; } }
mit
7eb8dc9ab61a1186e3eb518b1ca289ec
33.521368
110
0.670958
4.961916
false
false
false
false
s4cha/Stevia
Sources/Stevia/Stevia+Hierarchy.swift
2
7533
// // Stevia+Hierarchy.swift // LoginStevia // // Created by Sacha Durand Saint Omer on 01/10/15. // Copyright © 2015 Sacha Durand Saint Omer. All rights reserved. // #if canImport(UIKit) import UIKit @_functionBuilder public struct SubviewsBuilder { public static func buildBlock(_ content: UIView...) -> [UIView] { return content } } public extension UIView { @available(*, deprecated, renamed: "subviews") @discardableResult func sv(_ subViews: UIView...) -> UIView { subviews(subViews) } /** Defines the view hierachy for the view. Esentially, this is just a shortcut to `addSubview` and 'translatesAutoresizingMaskIntoConstraints = false' ``` class MyView: UIView { let email = UITextField() let password = UITextField() let login = UIButton() convenience init() { self.init(frame: CGRect.zero) subviews( email, password, login ) ... } } ``` - Returns: Itself to enable nested layouts. */ @discardableResult func subviews(_ subViews: UIView...) -> UIView { subviews(subViews) } /** Defines the view hierachy for the view. Esentially, this is just a shortcut to `addSubview` and 'translatesAutoresizingMaskIntoConstraints = false' ``` class MyView: UIView { let email = UITextField() let password = UITextField() let login = UIButton() convenience init() { self.init(frame: CGRect.zero) subviews { email password login } ... } } ``` - Returns: Itself to enable nested layouts. */ @discardableResult func subviews(@SubviewsBuilder content: () -> [UIView]) -> UIView { subviews(content()) } /** Defines the view hierachy for the view. Esentially, this is just a shortcut to `addSubview` and 'translatesAutoresizingMaskIntoConstraints = false' ``` class MyView: UIView { let email = UITextField() let password = UITextField() let login = UIButton() convenience init() { self.init(frame: CGRect.zero) subviews { email password login } ... } } ``` - Returns: Itself to enable nested layouts. */ @discardableResult func subviews(@SubviewsBuilder content: () -> UIView) -> UIView { let subview = content() subviews(subview) return self } /** Defines the view hierachy for the view. Esentially, this is just a shortcut to `addSubview` and 'translatesAutoresizingMaskIntoConstraints = false' ``` class MyView: UIView { let email = UITextField() let password = UITextField() let login = UIButton() convenience init() { self.init(frame: CGRect.zero) sv( email, password, login ) ... } } ``` - Returns: Itself to enable nested layouts. */ @objc @available(*, deprecated, renamed: "subviews") @discardableResult func sv(_ subViews: [UIView]) -> UIView { subviews(subViews) } @discardableResult @objc func subviews(_ subViews: [UIView]) -> UIView { for sv in subViews { addSubview(sv) sv.translatesAutoresizingMaskIntoConstraints = false } return self } } public extension UITableViewCell { /** Defines the view hierachy for the view. Esentially, this is just a shortcut to `contentView.addSubview` and 'translatesAutoresizingMaskIntoConstraints = false' ``` class NotificationCell: UITableViewCell { var avatar = UIImageView() var name = UILabel() var followButton = UIButton() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) { sv( avatar, name, followButton ) ... } } ``` - Returns: Itself to enable nested layouts. */ @available(*, deprecated, renamed: "subviews") @discardableResult override func sv(_ subViews: [UIView]) -> UIView { contentView.subviews(subViews) } /** Defines the view hierachy for the view. Esentially, this is just a shortcut to `contentView.addSubview` and 'translatesAutoresizingMaskIntoConstraints = false' ``` class NotificationCell: UITableViewCell { var avatar = UIImageView() var name = UILabel() var followButton = UIButton() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) { subviews( avatar, name, followButton ) ... } } ``` - Returns: Itself to enable nested layouts. */ @discardableResult override func subviews(_ subViews: [UIView]) -> UIView { contentView.subviews(subViews) } } public extension UICollectionViewCell { /** Defines the view hierachy for the view. Esentially, this is just a shortcut to `contentView.addSubview` and 'translatesAutoresizingMaskIntoConstraints = false' ``` class PhotoCollectionViewCell: UICollectionViewCell { var avatar = UIImageView() var name = UILabel() var followButton = UIButton() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) subviews( avatar, name, followButton ) ... } } ``` - Returns: Itself to enable nested layouts. */ @available(*, deprecated, renamed: "subviews") @discardableResult override func sv(_ subViews: [UIView]) -> UIView { contentView.subviews(subViews) } @discardableResult override func subviews(_ subViews: [UIView]) -> UIView { contentView.subviews(subViews) } } public extension UIStackView { @discardableResult func arrangedSubviews(@SubviewsBuilder content: () -> [UIView]) -> UIView { arrangedSubviews(content()) } @discardableResult func arrangedSubviews(@SubviewsBuilder content: () -> UIView) -> UIView { arrangedSubviews([content()]) } @discardableResult private func arrangedSubviews(_ subViews: UIView...) -> UIView { arrangedSubviews(subViews) } @discardableResult func arrangedSubviews(_ subViews: [UIView]) -> UIView { subViews.forEach { addArrangedSubview($0) } return self } } #endif
mit
5afa3dfc0f0c8f84f2b71313eff835dc
21.686747
100
0.55616
5.330502
false
false
false
false
boqian2000/swift-algorithm-club
Merge Sort/MergeSort.swift
1
2697
// // Mergesort.swift // // // Created by Kelvin Lau on 2016-02-03. // // func mergeSort<T: Comparable>(_ array: [T]) -> [T] { guard array.count > 1 else { return array } let middleIndex = array.count / 2 let leftArray = mergeSort(Array(array[0..<middleIndex])) let rightArray = mergeSort(Array(array[middleIndex..<array.count])) return merge(leftPile: leftArray, rightPile: rightArray) } func merge<T: Comparable>(leftPile: [T], rightPile: [T]) -> [T] { var leftIndex = 0 var rightIndex = 0 var orderedPile = [T]() while leftIndex < leftPile.count && rightIndex < rightPile.count { if leftPile[leftIndex] < rightPile[rightIndex] { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 } else if leftPile[leftIndex] > rightPile[rightIndex] { orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } else { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } } while leftIndex < leftPile.count { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 } while rightIndex < rightPile.count { orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } return orderedPile } /* This is an iterative bottom-up implementation. Instead of recursively splitting up the array into smaller sublists, it immediately starts merging the individual array elements. As the algorithm works its way up, it no longer merges individual elements but larger and larger subarrays, until eventually the entire array is merged and sorted. To avoid allocating many temporary array objects, it uses double-buffering with just two arrays. */ func mergeSortBottomUp<T>(_ a: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] { let n = a.count var z = [a, a] // the two working arrays var d = 0 // z[d] is used for reading, z[1 - d] for writing var width = 1 while width < n { var i = 0 while i < n { var j = i var l = i var r = i + width let lmax = min(l + width, n) let rmax = min(r + width, n) while l < lmax && r < rmax { if isOrderedBefore(z[d][l], z[d][r]) { z[1 - d][j] = z[d][l] l += 1 } else { z[1 - d][j] = z[d][r] r += 1 } j += 1 } while l < lmax { z[1 - d][j] = z[d][l] j += 1 l += 1 } while r < rmax { z[1 - d][j] = z[d][r] j += 1 r += 1 } i += width*2 } width *= 2 // in each step, the subarray to merge becomes larger d = 1 - d // swap active array } return z[d] }
mit
a2dfe39667eda43e8a8de8d5e0201eea
23.972222
82
0.58769
3.55336
false
false
false
false
S-Shimotori/Chalcedony
Chalcedony/Chalcedony/CCDSettingTableViewController.swift
1
6220
// // CCDSettingTableViewController.swift // Chalcedony // // Created by S-Shimotori on 6/20/15. // Copyright (c) 2015 S-Shimotori. All rights reserved. // import UIKit class CCDSettingTableViewController: UITableViewController { private let viewTitle = "設定" private let switchCellIdentifier = "switchCell" private let detailCellIdentifier = "detailCell" private var twitterId: String? = CCDSetting.twitterId @IBOutlet private weak var switchToUseLaboLocate: UISwitch! @IBOutlet private weak var switchToUseTwitter: UISwitch! @IBOutlet private weak var labelToShowTwitterId: UILabel! @IBOutlet private weak var labelForMessageToTweetLaboin: UILabel! @IBOutlet private weak var labelForMessageToTweetLaborida: UILabel! @IBOutlet private weak var labelForMessageToTweetKaeritai: UILabel! @IBOutlet private weak var switchToUseLaboridaChallenge: UISwitch! @IBOutlet private weak var labelForNameToTweet: UILabel! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = viewTitle switchToUseLaboLocate.on = CCDSetting.useLaboLocate switchToUseTwitter.on = CCDSetting.useTwitter switchToUseLaboridaChallenge.on = CCDSetting.useLaboridaChallenge switchToUseLaboLocate.addTarget(self, action: "valueChangedSwitch:", forControlEvents: .ValueChanged) switchToUseTwitter.addTarget(self, action: "valueChangedSwitch:", forControlEvents: .ValueChanged) switchToUseLaboridaChallenge.addTarget(self, action: "valueChangedSwitch:", forControlEvents: .ValueChanged) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let twitterModel = CCDTwitterModel() if let userName = twitterModel.userName { labelToShowTwitterId.text = "@\(userName)" } else { labelToShowTwitterId.text = "未ログイン" } labelForMessageToTweetLaboin.text = CCDSetting.messageToTweetLaboin labelForMessageToTweetLaborida.text = CCDSetting.messageToTweetLaborida labelForMessageToTweetKaeritai.text = CCDSetting.messageToTweetKaeritai } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if CCDSetting.useTwitter { return 3 } else { return 2 } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: if !CCDSetting.useLaboLocate { return 1 } case 1: if !CCDSetting.useTwitter { return 1 } case 2: if !CCDSetting.useLaboridaChallenge { return 1 } default: break } return CCDSettingTableList.numberOfRowsInSection[section] } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) cell.selectionStyle = .None switch (indexPath.section, indexPath.row) { case (1, 1): let twitterModel = CCDTwitterModel() if twitterModel.userName != nil { cell.accessoryType = UITableViewCellAccessoryType.None } default: break } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch (indexPath.section, indexPath.row) { case (0, 2): break case (0, 3): break case (0, 4): break case (1, 1): let twitterModel = CCDTwitterModel() twitterModel.login() break case (2, 1): break default: break } } func valueChangedSwitch(sender: UISwitch) { tableView.beginUpdates() switch sender.tag { case 0: if sender.on != CCDSetting.useLaboLocate { CCDSetting.useLaboLocate = sender.on var indexPaths = [NSIndexPath]() for i in 1 ..< CCDSettingTableList.numberOfRowsInSection[0] { indexPaths.append(NSIndexPath(forRow: 1, inSection: 0)) } if sender.on == true { tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Fade) } else { tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Fade) } } case 1: if sender.on != CCDSetting.useTwitter { CCDSetting.useTwitter = sender.on var indexPaths = [NSIndexPath]() for i in 1 ..< CCDSettingTableList.numberOfRowsInSection[1] { indexPaths.append(NSIndexPath(forRow: i, inSection: 1)) } if sender.on == true { tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Fade) tableView.insertSections(NSIndexSet(index: 2), withRowAnimation: .Fade) } else { tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Fade) tableView.deleteSections(NSIndexSet(index: 2), withRowAnimation: .Fade) } } case 2: if sender.on != CCDSetting.useLaboridaChallenge { CCDSetting.useLaboridaChallenge = sender.on var indexPaths = [NSIndexPath]() for i in 1 ..< CCDSettingTableList.numberOfRowsInSection[2] { indexPaths.append(NSIndexPath(forRow: i, inSection: 2)) } if sender.on == true { tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Fade) } else { tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Fade) } } default: break } tableView.endUpdates() } }
mit
0558e11002e036c99fa87702d19de437
37.07362
152
0.609249
5.167361
false
false
false
false
mohitathwani/swift-corelibs-foundation
TestFoundation/TestNSURLSession.swift
1
18904
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestURLSession : XCTestCase { var serverPort: Int = -1 static var allTests: [(String, (TestURLSession) -> () throws -> Void)] { return [ ("test_dataTaskWithURL", test_dataTaskWithURL), ("test_dataTaskWithURLRequest", test_dataTaskWithURLRequest), ("test_dataTaskWithURLCompletionHandler", test_dataTaskWithURLCompletionHandler), ("test_dataTaskWithURLRequestCompletionHandler", test_dataTaskWithURLRequestCompletionHandler), ("test_downloadTaskWithURL", test_downloadTaskWithURL), ("test_downloadTaskWithURLRequest", test_downloadTaskWithURLRequest), ("test_downloadTaskWithRequestAndHandler", test_downloadTaskWithRequestAndHandler), ("test_downloadTaskWithURLAndHandler", test_downloadTaskWithURLAndHandler), ("test_finishTaskAndInvalidate", test_finishTasksAndInvalidate), ("test_taskError", test_taskError), ("test_taskCopy", test_taskCopy), ("test_cancelTask", test_cancelTask), ("test_taskTimeout", test_taskTimeout), ("test_verifyRequestHeaders", test_verifyRequestHeaders), ] } private func runServer(with condition: ServerSemaphore, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws { let start = 21961 for port in start...(start+100) { //we must find at least one port to bind do { serverPort = port let test = try TestURLSessionServer(port: UInt16(port), startDelay: startDelay, sendDelay: sendDelay, bodyChunks: bodyChunks) try test.start(started: condition) try test.readAndRespond() test.stop() } catch let e as ServerError { if e.operation == "bind" { continue } throw e } } } func test_dataTaskWithURL() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() let urlString = "http://127.0.0.1:\(serverPort)/Nepal" let url = URL(string: urlString)! let d = DataTask(with: expectation(description: "data task")) d.run(with: url) waitForExpectations(timeout: 12) if !d.error { XCTAssertEqual(d.capital, "Kathmandu", "test_dataTaskWithURLRequest returned an unexpected result") } } func test_dataTaskWithURLCompletionHandler() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() let urlString = "http://127.0.0.1:\(serverPort)/USA" let url = URL(string: urlString)! let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 8 let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) let expect = expectation(description: "URL test with completion handler") var expectedResult = "unknown" let task = session.dataTask(with: url) { data, response, error in if let e = error as? URLError { XCTAssertEqual(e.code, .timedOut, "Unexpected error code") expect.fulfill() return } let httpResponse = response as! HTTPURLResponse? XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200") expectedResult = String(data: data!, encoding: String.Encoding.utf8)! XCTAssertEqual("Washington, D.C.", expectedResult, "Did not receive expected value") expect.fulfill() } task.resume() waitForExpectations(timeout: 12) } func test_dataTaskWithURLRequest() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() let urlString = "http://127.0.0.1:\(serverPort)/Peru" let urlRequest = URLRequest(url: URL(string: urlString)!) let d = DataTask(with: expectation(description: "data task")) d.run(with: urlRequest) waitForExpectations(timeout: 12) if !d.error { XCTAssertEqual(d.capital, "Lima", "test_dataTaskWithURLRequest returned an unexpected result") } } func test_dataTaskWithURLRequestCompletionHandler() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() let urlString = "http://127.0.0.1:\(serverPort)/Italy" let urlRequest = URLRequest(url: URL(string: urlString)!) let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 8 let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) let expect = expectation(description: "URL test with completion handler") var expectedResult = "unknown" let task = session.dataTask(with: urlRequest) { data, response, error in if let e = error as? URLError { XCTAssertEqual(e.code, .timedOut, "Unexpected error code") expect.fulfill() return } let httpResponse = response as! HTTPURLResponse? XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200") expectedResult = String(data: data!, encoding: String.Encoding.utf8)! XCTAssertEqual("Rome", expectedResult, "Did not receive expected value") expect.fulfill() } task.resume() waitForExpectations(timeout: 12) } func test_downloadTaskWithURL() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() let urlString = "http://127.0.0.1:\(serverPort)/country.txt" let url = URL(string: urlString)! let d = DownloadTask(with: expectation(description: "download task with delegate")) d.run(with: url) waitForExpectations(timeout: 12) } func test_downloadTaskWithURLRequest() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() let urlString = "http://127.0.0.1:\(serverPort)/country.txt" let urlRequest = URLRequest(url: URL(string: urlString)!) let d = DownloadTask(with: expectation(description: "download task with delegate")) d.run(with: urlRequest) waitForExpectations(timeout: 12) } func test_downloadTaskWithRequestAndHandler() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 8 let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) let expect = expectation(description: "download task with handler") let req = URLRequest(url: URL(string: "http://127.0.0.1:\(serverPort)/country.txt")!) let task = session.downloadTask(with: req) { (_, _, error) -> Void in if let e = error as? URLError { XCTAssertEqual(e.code, .timedOut, "Unexpected error code") } expect.fulfill() } task.resume() waitForExpectations(timeout: 12) } func test_downloadTaskWithURLAndHandler() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 8 let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) let expect = expectation(description: "download task with handler") let req = URLRequest(url: URL(string: "http://127.0.0.1:\(serverPort)/country.txt")!) let task = session.downloadTask(with: req) { (_, _, error) -> Void in if let e = error as? URLError { XCTAssertEqual(e.code, .timedOut, "Unexpected error code") } expect.fulfill() } task.resume() waitForExpectations(timeout: 12) } func test_finishTasksAndInvalidate() { let invalidateExpectation = expectation(description: "URLSession wasn't invalidated") let delegate = SessionDelegate(invalidateExpectation: invalidateExpectation) let url = URL(string: "http://127.0.0.1:\(serverPort)/Nepal")! let session = URLSession(configuration: URLSessionConfiguration.default, delegate: delegate, delegateQueue: nil) let completionExpectation = expectation(description: "dataTask completion block wasn't called") let task = session.dataTask(with: url) { _ in completionExpectation.fulfill() } task.resume() session.finishTasksAndInvalidate() waitForExpectations(timeout: 12) } func test_taskError() { let url = URL(string: "http://127.0.0.1:\(serverPort)/Nepal")! let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil) let completionExpectation = expectation(description: "dataTask completion block wasn't called") let task = session.dataTask(with: url) { result in let error = result.2 as? URLError XCTAssertNotNil(error) XCTAssertEqual(error?.code, .badURL) completionExpectation.fulfill() } //should result in Bad URL error task.resume() waitForExpectations(timeout: 5) { error in XCTAssertNil(error) XCTAssertNotNil(task.error) XCTAssertEqual((task.error as? URLError)?.code, .badURL) } } func test_taskCopy() { let url = URL(string: "http://127.0.0.1:\(serverPort)/Nepal")! let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil) let task = session.dataTask(with: url) XCTAssert(task.isEqual(task.copy())) } func test_cancelTask() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() let url = URL(string: "http://127.0.0.1:\(serverPort)/Peru")! let d = DataTask(with: expectation(description: "Task to be canceled")) d.cancelExpectation = expectation(description: "URLSessionTask wasn't canceled") d.run(with: url) d.cancel() waitForExpectations(timeout: 12) } func test_verifyRequestHeaders() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 5 let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) var expect = expectation(description: "download task with handler") var req = URLRequest(url: URL(string: "http://127.0.0.1:\(serverPort)/requestHeaders")!) let headers = ["header1": "value1"] req.httpMethod = "POST" req.allHTTPHeaderFields = headers var task = session.dataTask(with: req) { (data, _, error) -> Void in defer { expect.fulfill() } let headers = String(data: data!, encoding: String.Encoding.utf8)! XCTAssertNotNil(headers.range(of: "header1: value1")) } task.resume() waitForExpectations(timeout: 30) } func test_taskTimeout() { let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try self.runServer(with: serverReady, startDelay: 3, sendDelay: 3, bodyChunks: 3) } catch { XCTAssertTrue(true) return } } serverReady.wait() let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 5 let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) var expect = expectation(description: "download task with handler") let req = URLRequest(url: URL(string: "http://127.0.0.1:\(serverPort)/Peru")!) var task = session.dataTask(with: req) { (data, _, error) -> Void in defer { expect.fulfill() } XCTAssertNil(error) } task.resume() waitForExpectations(timeout: 30) } } class SessionDelegate: NSObject, URLSessionDelegate { let invalidateExpectation: XCTestExpectation init(invalidateExpectation: XCTestExpectation){ self.invalidateExpectation = invalidateExpectation } func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { invalidateExpectation.fulfill() } } class DataTask : NSObject { let dataTaskExpectation: XCTestExpectation! var capital = "unknown" var session: URLSession! = nil var task: URLSessionDataTask! = nil var cancelExpectation: XCTestExpectation? public var error = false init(with expectation: XCTestExpectation) { dataTaskExpectation = expectation } func run(with request: URLRequest) { let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 8 session = URLSession(configuration: config, delegate: self, delegateQueue: nil) task = session.dataTask(with: request) task.resume() } func run(with url: URL) { let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 8 session = URLSession(configuration: config, delegate: self, delegateQueue: nil) task = session.dataTask(with: url) task.resume() } func cancel() { task.cancel() } } extension DataTask : URLSessionDataDelegate { public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { capital = String(data: data, encoding: String.Encoding.utf8)! dataTaskExpectation.fulfill() } } extension DataTask : URLSessionTaskDelegate { public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let e = error as? URLError else { return } dataTaskExpectation.fulfill() if let cancellation = cancelExpectation { cancellation.fulfill() } self.error = true } } class DownloadTask : NSObject { var totalBytesWritten: Int64 = 0 let dwdExpectation: XCTestExpectation! var session: URLSession! = nil var task: URLSessionDownloadTask! = nil init(with expectation: XCTestExpectation) { dwdExpectation = expectation } func run(with url: URL) { let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 8 session = URLSession(configuration: config, delegate: self, delegateQueue: nil) task = session.downloadTask(with: url) task.resume() } func run(with urlRequest: URLRequest) { let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 8 session = URLSession(configuration: config, delegate: self, delegateQueue: nil) task = session.downloadTask(with: urlRequest) task.resume() } } extension DownloadTask : URLSessionDownloadDelegate { public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void { self.totalBytesWritten = totalBytesWritten } public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { do { let attr = try FileManager.default.attributesOfItem(atPath: location.path) XCTAssertEqual((attr[.size]! as? NSNumber)!.int64Value, totalBytesWritten, "Size of downloaded file not equal to total bytes downloaded") } catch { XCTFail("Unable to calculate size of the downloaded file") } dwdExpectation.fulfill() } } extension DownloadTask : URLSessionTaskDelegate { public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let e = error as? URLError else { return } XCTAssertEqual(e.code, .timedOut, "Unexpected error code") dwdExpectation.fulfill() } }
apache-2.0
455ff9e12954a6aefd5bf4a4fcfe69a6
37.501018
157
0.612357
5.051844
false
true
false
false
kevinsumios/KSiShuHui
Project/AppDelegate.swift
1
5196
// // AppDelegate.swift // Project // // Created by Kevin Sum on 8/6/2017. // Copyright © 2017 Kevin Sum. All rights reserved. // import UIKit import CoreData import IQKeyboardManagerSwift import Siren import SwiftyBeaver import MagicalRecord @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // SwiftyBeaver log setup let console = ConsoleDestination() log.addDestination(console) log.info(Helper.documentDirectory) // Siren setup Siren.shared.checkVersion(checkType: .daily) // IQKeyboardManager IQKeyboardManager.sharedManager().enable = true // MagicalRecord MagicalRecord.setLoggingLevel(.off) MagicalRecord.setupCoreDataStack() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. // Siren setup Siren.shared.checkVersion(checkType: .daily) } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. MagicalRecord.cleanUp() // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Project") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
978f7782627e15a63ceb611f472e23d0
43.401709
285
0.676612
5.910125
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Components/Currency/Money/Money+Components+Font.swift
1
6591
// // Xcore // Copyright © 2017 Xcore // MIT license, see LICENSE file for details // import UIKit extension Money.Components { /// A structure representing fonts used to display money components. public struct Font: Hashable { /// The font to be used in displaying major unit of the amount. /// /// ```swift /// let amount = Decimal(120.30) /// // 120 - major unit /// // 30 - minor unit /// ``` public let majorUnit: UIFont? /// The font to be used in displaying minor unit of the amount. /// /// ```swift /// let amount = Decimal(120.30) /// // 120 - major unit /// // 30 - minor unit /// ``` public let minorUnit: UIFont? /// The offset applied to the minor unit of the amount. /// /// ```swift /// let amount = Decimal(120.30) /// // 120 - major unit /// // 30 - minor unit /// ``` public let minorUnitOffset: Int? public init(majorUnit: UIFont?, minorUnit: UIFont?, minorUnitOffset: Int?) { self.majorUnit = majorUnit self.minorUnit = minorUnit self.minorUnitOffset = minorUnitOffset } public init(_ style: UIFont.TextStyle) { self.init(.app(style)) } public init(_ font: UIFont?) { self.majorUnit = font self.minorUnit = font self.minorUnitOffset = nil } } } // MARK: - Convenience extension Money.Components.Font { /// Superscript based layout derived from the given major unit size. /// /// - Note: Consider using the pre-existing styles instead of using this method /// directly. If an existing style doesn't fit your need create an alias here /// like `.body` to ensure consistency. public static func superscript(_ style: UIFont.TextStyle) -> Self { superscript(.app(style)) } /// Superscript based layout derived from the given major unit size. /// /// - Note: Consider using the pre-existing styles instead of using this method /// directly. If an existing style doesn't fit your need create an alias here /// like `.body` to ensure consistency. public static func superscript(_ font: UIFont) -> Self { let majorUnitSize = font.pointSize let φ = AppConstants.φ var minorUnitSize = (majorUnitSize * φ).rounded() // Add buffer if the given size is small. This helps with readability. if majorUnitSize <= 20 { minorUnitSize += (minorUnitSize * φ * φ * φ).rounded() } let minorUnitWeight: UIFont.Weight = minorUnitSize <= 10 ? .medium : .regular let minorUnitOffset = Int((majorUnitSize - minorUnitSize).rounded()) return .init( majorUnit: font, minorUnit: .app(size: minorUnitSize, weight: minorUnitWeight), minorUnitOffset: minorUnitOffset ) } } // MARK: - Built-in extension Money.Components.Font { /// A font with the large title text style. public static var largeTitle: Self { largeTitle(superscript: false) } /// A font with the title text style. public static var title: Self { title(superscript: false) } /// Create a font for second level hierarchical headings. public static var title2: Self { title2(superscript: false) } /// Create a font for third level hierarchical headings. public static var title3: Self { title3(superscript: false) } /// A font with the headline text style. public static var headline: Self { headline(superscript: false) } /// A font with the subheadline text style. public static var subheadline: Self { subheadline(superscript: false) } /// A font with the body text style. public static var body: Self { body(superscript: false) } /// A font with the callout text style. public static var callout: Self { callout(superscript: false) } /// A font with the footnote text style. public static var footnote: Self { footnote(superscript: false) } /// A font with the caption text style. public static var caption: Self { caption(superscript: false) } /// Create a font with the alternate caption text style. public static var caption2: Self { caption2(superscript: false) } } extension Money.Components.Font { /// A font with the large title text style. public static func largeTitle(superscript: Bool) -> Self { superscript ? .superscript(.largeTitle) : .init(.largeTitle) } /// A font with the title text style. public static func title(superscript: Bool) -> Self { superscript ? .superscript(.title1) : .init(.title1) } /// Create a font for second level hierarchical headings. public static func title2(superscript: Bool) -> Self { superscript ? .superscript(.title2) : .init(.title2) } /// Create a font for third level hierarchical headings. public static func title3(superscript: Bool) -> Self { superscript ? .superscript(.title3) : .init(.title3) } /// A font with the headline text style. public static func headline(superscript: Bool) -> Self { superscript ? .superscript(.headline) : .init(.headline) } /// A font with the subheadline text style. public static func subheadline(superscript: Bool) -> Self { superscript ? .superscript(.subheadline) : .init(.subheadline) } /// A font with the body text style. public static func body(superscript: Bool) -> Self { superscript ? .superscript(.body) : .init(.body) } /// A font with the callout text style. public static func callout(superscript: Bool) -> Self { superscript ? .superscript(.callout) : .init(.callout) } /// A font with the footnote text style. public static func footnote(superscript: Bool) -> Self { superscript ? .superscript(.footnote) : .init(.footnote) } /// A font with the caption text style. public static func caption(superscript: Bool) -> Self { superscript ? .superscript(.caption1) : .init(.caption1) } /// Create a font with the alternate caption text style. public static func caption2(superscript: Bool) -> Self { superscript ? .superscript(.caption2) : .init(.caption2) } public static var none: Self { .init(nil) } }
mit
86b8da48f649c02214b2692c7b1002be
29.766355
85
0.611179
4.294847
false
false
false
false
JaSpa/swift
stdlib/public/SDK/Intents/INRequestRideIntent.swift
1
1626
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Intents import Foundation #if os(iOS) || os(watchOS) @available(iOS 10.0, watchOS 3.2, *) extension INRequestRideIntent { @nonobjc public convenience init( pickupLocation: CLPlacemark? = nil, dropOffLocation: CLPlacemark? = nil, rideOptionName: INSpeakableString? = nil, partySize: Int? = nil, paymentMethod: INPaymentMethod? = nil, scheduledPickupTime: INDateComponentsRange? = nil ) { if #available(iOS 10.3, watchOS 3.2, *) { self.init(__pickupLocation: pickupLocation, dropOffLocation: dropOffLocation, rideOptionName: rideOptionName, partySize: partySize.map { NSNumber(value: $0) }, paymentMethod: paymentMethod, scheduledPickupTime: scheduledPickupTime) } else { self.init(__pickupLocation: pickupLocation, dropOffLocation: dropOffLocation, rideOptionName: rideOptionName, partySize: partySize.map { NSNumber(value: $0) }, paymentMethod: paymentMethod) } } @nonobjc public final var partySize: Int? { return __partySize?.intValue } } #endif
apache-2.0
e839f6918fb129bd7f7127d758f7468e
32.183673
80
0.626076
4.442623
false
false
false
false
biohazardlover/ROer
Roer/SkillsDataSource.swift
1
1901
import Foundation import CoreData class SkillsDataSource: NSObject, DatabaseRecordsViewControllerDataSource { func entityName() -> String { return "Skill" } func title() -> String { return "Skills".localized } func filter() -> Filter { return Filter(contentsOfURL: Bundle.main.url(forResource: "SkillsFilter", withExtension: "plist")!) } func resultsWithFilter(_ filter: Filter, inContext context: NSManagedObjectContext) -> [AnyObject]? { let predicate: NSPredicate? = filter.predicates.count > 0 ? NSPredicate(format: filter.predicates.joined(separator: " && ")) : nil if predicate == nil { let fetchRequest = NSFetchRequest<Skill>(entityName: "Skill") fetchRequest.sortDescriptors = filter.sortDescriptors return try? context.fetch(fetchRequest) } else { let fetchRequest = NSFetchRequest<SkillPrerequisite>(entityName: "SkillPrerequisite") fetchRequest.predicate = predicate fetchRequest.sortDescriptors = filter.sortDescriptors.map({ (sortDescriptor) -> NSSortDescriptor in return NSSortDescriptor(key: "skill." + sortDescriptor.key!, ascending: sortDescriptor.ascending) }) let skillPrerequisites = try? context.fetch(fetchRequest) return skillPrerequisites } } func includeDatabaseRecord(_ databaseRecord: DatabaseRecord, forSearchText searchText: String) -> Bool { let skill = databaseRecord as! Skill if skill.id?.stringValue == searchText || skill.description_?.localizedCaseInsensitiveContains(searchText) == true { return true } else { return false } } func titleForEmptyDataSet() -> String { return "NoSkills".localized } }
mit
b81b94c08559f592f342cf3420c83f05
35.557692
138
0.634403
5.542274
false
false
false
false
saturnboy/learning_spritekit_swift
LearningSpriteKit/LearningSpriteKit/GameScene3.swift
1
2072
// // GameScene3.swift // LearningSpriteKit // // Created by Justin on 12/1/14. // Copyright (c) 2014 SaturnBoy. All rights reserved. // import SpriteKit class GameScene3: SKScene { let alien = SKSpriteNode(imageNamed: "alien1") let hit = SKAction.playSoundFileNamed("fire.caf", waitForCompletion: false) let miss = SKAction.playSoundFileNamed("miss.caf", waitForCompletion: false) override func didMoveToView(view: SKView) { println("GameScene3: \(view.frame.size)") self.backgroundColor = UIColor(red: 0.3, green: 0.1, blue: 0.1, alpha: 1.0) self.alien.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame)) self.addChild(self.alien) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { if let touch: AnyObject = touches.anyObject() { let loc = touch.locationInNode(self) println("touch: \(loc)") if self.alien.containsPoint(loc) { println("HIT!") self.runAction(self.hit) //compute the new position let center = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame)) let newPos = CGPoint(x: center.x + CGFloat(arc4random_uniform(201)) - 100.0, y: center.y + CGFloat(arc4random_uniform(201)) - 100.0) //1. Instead of the above, how could you adjust positioning for iPhone vs iPad let fadeOut = SKAction.fadeOutWithDuration(0.2) let fadeIn = SKAction.fadeInWithDuration(0.2) let move = SKAction.moveTo(newPos, duration:0.2) self.alien.runAction(SKAction.sequence([fadeOut, move, fadeIn])) } else { println("miss") self.runAction(self.miss) } } } override func update(currentTime: CFTimeInterval) { //pass } }
mit
8f36cb610b0957d10a4d84c087c67a74
35.350877
97
0.567085
4.533917
false
false
false
false
lucaslt89/simpsonizados
simpsonizados/Pods/Alamofire/Source/Download.swift
51
9914
// Download.swift // // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension Manager { private enum Downloadable { case Request(NSURLRequest) case ResumeData(NSData) } private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request { var downloadTask: NSURLSessionDownloadTask! switch downloadable { case .Request(let request): dispatch_sync(queue) { downloadTask = self.session.downloadTaskWithRequest(request) } case .ResumeData(let resumeData): dispatch_sync(queue) { downloadTask = self.session.downloadTaskWithResumeData(resumeData) } } let request = Request(session: session, task: downloadTask) if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate { downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in return destination(URL, downloadTask.response as! NSHTTPURLResponse) } } delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: Request /** Creates a download request for the specified method, URL string, parameters, parameter encoding, headers and destination. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil, destination: Request.DownloadFileDestination) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 return download(encodedURLRequest, destination: destination) } /** Creates a request for downloading from the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { return download(.Request(URLRequest.URLRequest), destination: destination) } // MARK: Resume Data /** Creates a request for downloading from the resume data produced from a previous request cancellation. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request { return download(.ResumeData(resumeData), destination: destination) } } // MARK: - extension Request { /** A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved. */ public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL /** Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask. - parameter directory: The search path directory. `.DocumentDirectory` by default. - parameter domain: The search path domain mask. `.UserDomainMask` by default. - returns: A download file destination closure. */ public class func suggestedDownloadDestination( directory directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination { return { temporaryURL, response -> NSURL in let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain) if !directoryURLs.isEmpty { return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!) } return temporaryURL } } /// The resume data of the underlying download task if available after a failure. public var resumeData: NSData? { var data: NSData? if let delegate = delegate as? DownloadTaskDelegate { data = delegate.resumeData } return data } // MARK: - DownloadTaskDelegate class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate { var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask } var downloadProgress: ((Int64, Int64, Int64) -> Void)? var resumeData: NSData? override var data: NSData? { return resumeData } // MARK: - NSURLSessionDownloadDelegate // MARK: Override Closures var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)? var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: Delegate Methods func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { do { let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination) } catch { self.error = error as NSError } } } func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData( session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite ) } else { progress.totalUnitCount = totalBytesExpectedToWrite progress.completedUnitCount = totalBytesWritten downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } } func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else { progress.totalUnitCount = expectedTotalBytes progress.completedUnitCount = fileOffset } } } }
mit
32eb28df9c94624d60e4a03e452cc366
39.622951
121
0.66596
6.032867
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Venue
iOS/Venue/Controllers/PersonDetailsViewController.swift
1
5471
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /// ViewController to display details of a person class PersonDetailsViewController: UIViewController { var viewModel: PersonDetailsViewModel? @IBOutlet weak var initialsLabel: UILabel! @IBOutlet weak var profilePicture: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var phoneButton: UIButton! @IBOutlet weak var messageButton: UIButton! @IBOutlet weak var croppedMapImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let user = viewModel?.person { initialsLabel.text = user.initials nameLabel.text = user.name profilePicture.image = UIImage(named: user.pictureUrl) phoneButton.setTitle(user.phoneNumber, forState: UIControlState.Normal) } // Add gesture recognizer to map view to take you back to Map page let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "mapSelected") self.croppedMapImageView.addGestureRecognizer(tapGestureRecognizer) self.croppedMapImageView.userInteractionEnabled = true // Setup nav bar navigationController?.setNavigationBarHidden(false, animated: true) navigationController?.navigationBar.setBackgroundImage(nil,forBarMetrics: UIBarMetrics.Default) navigationController?.navigationBar.tintColor = UIColor.whiteColor() navigationController?.navigationBar.barTintColor = UIColor.venueLightBlue() navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] // Setup back button as just an arrow let backButton = UIBarButtonItem(image: UIImage(named: "back"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("backButtonPressed")) self.navigationItem.leftBarButtonItem = nil self.navigationItem.leftBarButtonItem = backButton // Setup Reactive bindings self.setupBindings() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() messageButton.layer.cornerRadius = messageButton.frame.height/2 initialsLabel.layer.cornerRadius = initialsLabel.frame.height/2 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if croppedMapImageView.image == nil { // Add cropped image and drop the pin on the map dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let croppedImage = self.viewModel!.croppedMapImage(self.croppedMapImageView.width, height: self.croppedMapImageView.height) dispatch_async(dispatch_get_main_queue()) { self.croppedMapImageView.image = croppedImage // Get the pin to add to the correct point let pinX = (self.croppedMapImageView.frame.size.width / 2) let pinY = (self.croppedMapImageView.frame.size.height / 2) var pinOffset = CGPoint(x: pinX, y: pinY) pinOffset = self.viewModel!.applyPinOffset(pinOffset) let personPin = MyPeopleAnnotation(user: self.viewModel!.person, location: pinOffset, zoomScale: 1.0) personPin.userInteractionEnabled = false self.croppedMapImageView.addSubview(personPin) } } } } func setupBindings() { messageButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { [weak self] _ in if let weakSelf = self { if let user = weakSelf.viewModel?.person { let phoneString = user.phoneNumber UIApplication.sharedApplication().openURL(NSURL(string: "sms:\(phoneString)")!) } } } phoneButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { [weak self] _ in if let weakSelf = self { if let user = weakSelf.viewModel?.person { let phoneString = user.phoneNumber UIApplication.sharedApplication().openURL(NSURL(string: "tel://\(phoneString)")!) } } } } func mapSelected(){ guard let tabBarController = self.tabBarController as? TabBarViewController else { return } tabBarController.selectMapTab(poi: nil, user: self.viewModel!.person) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func backButtonPressed() { self.navigationController?.popViewControllerAnimated(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. } */ }
epl-1.0
44541bd36c4127d953674304160ee08a
40.439394
158
0.644059
5.639175
false
false
false
false
ledwards/ios-twitter
Pods/AlamofireImage/Source/UIImageView+AlamofireImage.swift
5
16801
// UIImageView+AlamofireImage.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation import UIKit extension UIImageView { // MARK: - ImageTransition /// Used to wrap all `UIView` animation transition options alongside a duration. public enum ImageTransition { case None case CrossDissolve(NSTimeInterval) case CurlDown(NSTimeInterval) case CurlUp(NSTimeInterval) case FlipFromBottom(NSTimeInterval) case FlipFromLeft(NSTimeInterval) case FlipFromRight(NSTimeInterval) case FlipFromTop(NSTimeInterval) case Custom( duration: NSTimeInterval, animationOptions: UIViewAnimationOptions, animations: (UIImageView, Image) -> Void, completion: (Bool -> Void)? ) /// The duration of the image transition in seconds. public var duration: NSTimeInterval { switch self { case None: return 0.0 case CrossDissolve(let duration): return duration case CurlDown(let duration): return duration case CurlUp(let duration): return duration case FlipFromBottom(let duration): return duration case FlipFromLeft(let duration): return duration case FlipFromRight(let duration): return duration case FlipFromTop(let duration): return duration case Custom(let duration, _, _, _): return duration } } /// The animation options of the image transition. public var animationOptions: UIViewAnimationOptions { switch self { case None: return .TransitionNone case CrossDissolve: return .TransitionCrossDissolve case CurlDown: return .TransitionCurlDown case CurlUp: return .TransitionCurlUp case FlipFromBottom: return .TransitionFlipFromBottom case FlipFromLeft: return .TransitionFlipFromLeft case FlipFromRight: return .TransitionFlipFromRight case FlipFromTop: return .TransitionFlipFromTop case Custom(_, let animationOptions, _, _): return animationOptions } } /// The animation options of the image transition. public var animations: ((UIImageView, Image) -> Void) { switch self { case Custom(_, _, let animations, _): return animations default: return { $0.image = $1 } } } /// The completion closure associated with the image transition. public var completion: (Bool -> Void)? { switch self { case Custom(_, _, _, let completion): return completion default: return nil } } } // MARK: - Private - AssociatedKeys private struct AssociatedKeys { static var ImageDownloaderKey = "af_UIImageView.ImageDownloader" static var SharedImageDownloaderKey = "af_UIImageView.SharedImageDownloader" static var ActiveRequestReceiptKey = "af_UIImageView.ActiveRequestReceipt" } // MARK: - Associated Properties /// The instance image downloader used to download all images. If this property is `nil`, the `UIImageView` will /// fallback on the `af_sharedImageDownloader` for all downloads. The most common use case for needing to use a /// custom instance image downloader is when images are behind different basic auth credentials. public var af_imageDownloader: ImageDownloader? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ImageDownloaderKey) as? ImageDownloader } set(downloader) { objc_setAssociatedObject(self, &AssociatedKeys.ImageDownloaderKey, downloader, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// The shared image downloader used to download all images. By default, this is the default `ImageDownloader` /// instance backed with an `AutoPurgingImageCache` which automatically evicts images from the cache when the memory /// capacity is reached or memory warning notifications occur. The shared image downloader is only used if the /// `af_imageDownloader` is `nil`. public class var af_sharedImageDownloader: ImageDownloader { get { if let downloader = objc_getAssociatedObject(self, &AssociatedKeys.SharedImageDownloaderKey) as? ImageDownloader { return downloader } else { return ImageDownloader.defaultInstance } } set { objc_setAssociatedObject(self, &AssociatedKeys.SharedImageDownloaderKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var af_activeRequestReceipt: RequestReceipt? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ActiveRequestReceiptKey) as? RequestReceipt } set { objc_setAssociatedObject(self, &AssociatedKeys.ActiveRequestReceiptKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Image Download /** Asynchronously downloads an image from the specified URL, applies the specified image filter to the downloaded image and sets it once finished while executing the image transition. If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be set immediately, and then the remote image will be set once the image request is finished. The `completion` closure is called after the image download and filtering are complete, but before the start of the image transition. Please note it is no longer the responsibility of the `completion` closure to set the image. It will be set automatically. If you require a second notification after the image transition completes, use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when the image transition is finished. - parameter URL: The URL used for the image request. - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the image view will not change its image until the image request finishes. Defaults to `nil`. - parameter filter: The image filter applied to the image after the image request is finished. Defaults to `nil`. - parameter imageTransition: The image transition animation applied to the image when set. Defaults to `.None`. - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults to `false`. - parameter completion: A closure to be executed when the image request finishes. The closure has no return value and takes three arguments: the original request, the response from the server and the result containing either the image or the error that occurred. If the image was returned from the image cache, the response will be `nil`. Defaults to `nil`. */ public func af_setImageWithURL( URL: NSURL, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, imageTransition: ImageTransition = .None, runImageTransitionIfCached: Bool = false, completion: (Response<UIImage, NSError> -> Void)? = nil) { af_setImageWithURLRequest( URLRequestWithURL(URL), placeholderImage: placeholderImage, filter: filter, imageTransition: imageTransition, runImageTransitionIfCached: runImageTransitionIfCached, completion: completion ) } /** Asynchronously downloads an image from the specified URL Request, applies the specified image filter to the downloaded image and sets it once finished while executing the image transition. If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be set immediately, and then the remote image will be set once the image request is finished. The `completion` closure is called after the image download and filtering are complete, but before the start of the image transition. Please note it is no longer the responsibility of the `completion` closure to set the image. It will be set automatically. If you require a second notification after the image transition completes, use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when the image transition is finished. - parameter URLRequest: The URL request. - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the image view will not change its image until the image request finishes. Defaults to `nil`. - parameter filter: The image filter applied to the image after the image request is finished. Defaults to `nil`. - parameter imageTransition: The image transition animation applied to the image when set. Defaults to `.None`. - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults to `false`. - parameter completion: A closure to be executed when the image request finishes. The closure has no return value and takes three arguments: the original request, the response from the server and the result containing either the image or the error that occurred. If the image was returned from the image cache, the response will be `nil`. Defaults to `nil`. */ public func af_setImageWithURLRequest( URLRequest: URLRequestConvertible, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, imageTransition: ImageTransition = .None, runImageTransitionIfCached: Bool = false, completion: (Response<UIImage, NSError> -> Void)? = nil) { guard !isURLRequestURLEqualToActiveRequestURL(URLRequest) else { return } af_cancelImageRequest() let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader let imageCache = imageDownloader.imageCache // Use the image from the image cache if it exists if let image = imageCache?.imageForRequest(URLRequest.URLRequest, withAdditionalIdentifier: filter?.identifier) { let response = Response<UIImage, NSError>( request: URLRequest.URLRequest, response: nil, data: nil, result: .Success(image) ) completion?(response) if runImageTransitionIfCached { let tinyDelay = dispatch_time(DISPATCH_TIME_NOW, Int64(0.001 * Float(NSEC_PER_SEC))) // Need to let the runloop cycle for the placeholder image to take affect dispatch_after(tinyDelay, dispatch_get_main_queue()) { self.runImageTransition(imageTransition, withImage: image) } } else { self.image = image } return } // Set the placeholder since we're going to have to download if let placeholderImage = placeholderImage { self.image = placeholderImage } // Generate a unique download id to check whether the active request has changed while downloading let downloadID = NSUUID().UUIDString // Download the image, then run the image transition or completion handler let requestReceipt = imageDownloader.downloadImage( URLRequest: URLRequest, receiptID: downloadID, filter: filter, completion: { [weak self] response in guard let strongSelf = self else { return } completion?(response) guard strongSelf.isURLRequestURLEqualToActiveRequestURL(response.request) && strongSelf.af_activeRequestReceipt?.receiptID == downloadID else { return } if let image = response.result.value { strongSelf.runImageTransition(imageTransition, withImage: image) } strongSelf.af_activeRequestReceipt = nil } ) af_activeRequestReceipt = requestReceipt } // MARK: - Image Download Cancellation /** Cancels the active download request, if one exists. */ public func af_cancelImageRequest() { guard let activeRequestReceipt = af_activeRequestReceipt else { return } let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader imageDownloader.cancelRequestForRequestReceipt(activeRequestReceipt) af_activeRequestReceipt = nil } // MARK: - Image Transition /** Runs the image transition on the image view with the specified image. - parameter imageTransition: The image transition to ran on the image view. - parameter image: The image to use for the image transition. */ public func runImageTransition(imageTransition: ImageTransition, withImage image: Image) { UIView.transitionWithView( self, duration: imageTransition.duration, options: imageTransition.animationOptions, animations: { imageTransition.animations(self, image) }, completion: imageTransition.completion ) } // MARK: - Private - URL Request Helper Methods private func URLRequestWithURL(URL: NSURL) -> NSURLRequest { let mutableURLRequest = NSMutableURLRequest(URL: URL) for mimeType in Request.acceptableImageContentTypes { mutableURLRequest.addValue(mimeType, forHTTPHeaderField: "Accept") } return mutableURLRequest } private func isURLRequestURLEqualToActiveRequestURL(URLRequest: URLRequestConvertible?) -> Bool { if let currentRequest = af_activeRequestReceipt?.request.task.originalRequest where currentRequest.URLString == URLRequest?.URLRequest.URLString { return true } return false } }
mit
90e5e5f63dad834256c112ec5372a827
44.042895
130
0.618416
6.002501
false
false
false
false
ashfurrow/FunctionalReactiveAwesome
Pods/RxCocoa/RxCocoa/RxCocoa/Common/KVOObservable.swift
1
2732
// // KVOObservable.swift // RxCocoa // // Created by Krunoslav Zaher on 2/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift protocol KVOObservableProtocol { var object: NSObject { get } var path: String { get } var options: NSKeyValueObservingOptions { get } } class KVOObserver : NSObject, Disposable { typealias Callback = (AnyObject?) -> Void let parent: KVOObservableProtocol let callback: Callback var retainSelf: KVOObserver? = nil var context: UInt8 = 0 init(parent: KVOObservableProtocol, callback: Callback) { self.parent = parent self.callback = callback super.init() self.retainSelf = self self.parent.object.addObserver(self, forKeyPath: self.parent.path, options: self.parent.options, context: &context) #if TRACE_RESOURCES OSAtomicIncrement32(&resourceCount) #endif } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { let newValue: AnyObject? = change[NSKeyValueChangeNewKey] if let newValue: AnyObject = newValue { self.callback(newValue) } } func dispose() { self.parent.object.removeObserver(self, forKeyPath: self.parent.path) self.retainSelf = nil } deinit { #if TRACE_RESOURCES OSAtomicDecrement32(&resourceCount) #endif } } class KVOObservable<Element> : Observable<Element?>, KVOObservableProtocol { var object: NSObject var path: String var options: NSKeyValueObservingOptions convenience init(object: NSObject, path: String) { self.init(object: object, path: path, options: .Initial | .New) } init(object: NSObject, path: String, options: NSKeyValueObservingOptions) { self.object = object self.path = path self.options = options } override func subscribe<O : ObserverType where O.Element == Element?>(observer: O) -> Disposable { let observer = KVOObserver(parent: self) { (value) in sendNext(observer, value as? Element) } return AnonymousDisposable { () in observer.dispose() } } } extension NSObject { public func rx_observe<Element>(path: String) -> Observable<Element?> { return KVOObservable(object: self, path: path) } public func rx_observe<Element>(path: String, options: NSKeyValueObservingOptions) -> Observable<Element?> { return KVOObservable(object: self, path: path, options: options) } }
mit
de8abe46e85946cca215318b64799c67
26.887755
156
0.644217
4.71848
false
false
false
false
ello/ello-ios
Specs/Extensions/StringExtensionSpec.swift
1
7997
//// /// StringExtensionSpec.swift // @testable import Ello import Quick import Nimble class StringExtensionSpec: QuickSpec { override func spec() { describe("String") { describe("encoding URL strings") { it("should encode 'asdf' to 'asdf'") { let str = "asdf" expect(str.urlEncoded()).to(equal("asdf")) } it("should encode 'a&/=' to 'a%26%2F%3D'") { let str = "a&/=" expect(str.urlEncoded()).to(equal("a%26%2F%3D")) } it("should encode '…' to '%E2%80%A6'") { let str = "…" expect(str.urlEncoded()).to(equal("%E2%80%A6")) } } describe("decoding URL strings") { it("should decode 'asdf' to 'asdf'") { let str = "asdf" expect(str.urlDecoded()).to(equal("asdf")) } it("should decode 'a%26%2F%3D' to 'a&/='") { let str = "a%26%2F%3D" expect(str.urlDecoded()).to(equal("a&/=")) } it("should decode '%E2%80%A6' to '…'") { let str = "%E2%80%A6" expect(str.urlDecoded()).to(equal("…")) } } describe("stripping HTML src attribute") { it("should replace the src= attribute with double quotes") { let str = "<img src=\"foo\" />" expect(str.stripHtmlImgSrc()).to(beginWith("<img src=\"")) expect(str.stripHtmlImgSrc()).to(endWith("\" />")) expect(str.stripHtmlImgSrc()).notTo(contain("foo")) expect(str.stripHtmlImgSrc().count) > str.count } it("should replace the src= attribute with single quotes") { let str = "<img src='foo' />" expect(str.stripHtmlImgSrc()).to(beginWith("<img src=\"")) expect(str.stripHtmlImgSrc()).to(endWith("\" />")) expect(str.stripHtmlImgSrc()).notTo(contain("foo")) expect(str.stripHtmlImgSrc().count) > str.count } } describe("adding entities") { it("should handle 1-char length strings") { let str = "&" expect(str.entitiesEncoded()).to(equal("&amp;")) } it("should handle longer length strings") { let str = "black & blue" expect(str.entitiesEncoded()).to(equal("black &amp; blue")) } it("should handle many entities") { let str = "&\"<>'" expect(str.entitiesEncoded()).to(equal("&amp;&quot;&lt;&gt;&#039;")) } it("should handle many entities with strings") { let str = "a & < c > == d" expect(str.entitiesEncoded()).to(equal("a &amp; &lt; c &gt; == d")) } } describe("removing entities") { it("should handle 1-char length strings") { let str = "&amp;" expect(str.entitiesDecoded()).to(equal("&")) } it("should handle longer length strings") { let str = "black &amp; blue" expect(str.entitiesDecoded()).to(equal("black & blue")) } it("should handle many entities") { let str = "&amp; &lt;&gt; &pi;" expect(str.entitiesDecoded()).to(equal("& <> π")) } it("should handle many entities with strings") { let str = "a &amp; &lt; c &gt; &pi; == pi" expect(str.entitiesDecoded()).to(equal("a & < c > π == pi")) } } describe("salted sha1 hashing") { it("hashes the string using the sha1 algorithm with a prefixed salt value") { let str = "test" expect(str.saltedSHA1String) == "5bb3e61a51e40b8074716d2a30549c5b7b55cf63" } } describe("sha1 hashing") { it("hashes the string using the sha1 algorithm") { let str = "test" expect(str.SHA1String) == "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3" } } describe("split") { it("splits a string") { let str = "a,b,cc,ddd" expect(str.split(",")) == ["a", "b", "cc", "ddd"] } it("ignores a string with no splits") { let str = "abccddd" expect(str.split(",")) == ["abccddd"] } } describe("trimmed") { it("trims leading whitespace") { let strs = [ " string", "\t\tstring", " \t\nstring", ] for str in strs { expect(str.trimmed()) == "string" } } it("trims trailing whitespace") { let strs = [ "string ", "string\t\t", "string\n\t ", ] for str in strs { expect(str.trimmed()) == "string" } } it("trims leading and trailing whitespace") { let strs = [ " string ", "\t\tstring\t\t", "\n \tstring\t\n ", ] for str in strs { expect(str.trimmed()) == "string" } } it("ignores embedded whitespace") { let strs = [ "str ing", " str ing", "\t\tstr ing", "\n\nstr ing", "str ing ", "str ing\t\t", "str ing\n\n", " str ing ", "\t\tstr ing\t\t", "\n\nstr ing\n\n", ] for str in strs { expect(str.trimmed()) == "str ing" } } } describe("camelCase") { it("converts a string from snake case to camel case") { let snake = "hhhhh_sssss" expect(snake.camelCase) == "hhhhhSssss" } } describe("snakeCase") { it("converts a string from camel case to snake case") { let camel = "hhhhhSssss" expect(camel.snakeCase) == "hhhhh_sssss" } } describe("jsonQuoted") { let expectations: [(String, String)] = [ ("", "\"\""), ("test", "\"test\""), ("newline\ntest", "\"newline\\ntest\""), ("carriage\rtest", "\"carriage\\rtest\""), ("quote\"test", "\"quote\\\"test\""), ("quote'test", "\"quote'test\""), ("日本語 test", "\"日本語 test\""), ] for (input, expected) in expectations { it("should quote \(input)") { expect(input.jsonQuoted) == expected } } } } } }
mit
65516e286c32b0a43ebfda7ddf6aca89
40.108247
94
0.376176
4.741379
false
true
false
false
open-telemetry/opentelemetry-swift
Sources/OpenTelemetryApi/Trace/TraceState.swift
1
3983
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation /// Carries tracing-system specific context in a list of key-value pairs. TraceState allows different /// vendors propagate additional information and inter-operate with their legacy Id formats. /// Implementation is optimized for a small list of key-value pairs. /// Key is opaque string up to 256 characters printable. It MUST begin with a lowercase letter, /// and can only contain lowercase letters a-z, digits 0-9, underscores _, dashes -, asterisks *, and /// forward slashes /. /// Value is opaque string up to 256 characters printable ASCII RFC0020 characters (i.e., the /// range 0x20 to 0x7E) except comma , and =. public struct TraceState: Equatable, Codable { private static let maxKeyValuePairs = 32 public private(set) var entries = [Entry]() /// Returns the default with no entries. public init() {} public init?(entries: [Entry]) { guard entries.count <= TraceState.maxKeyValuePairs else { return nil } self.entries = entries } /// Returns the value to which the specified key is mapped, or nil if this map contains no mapping /// for the key /// - Parameter key: key with which the specified value is to be associated public func get(key: String) -> String? { return entries.first(where: { $0.key == key })?.value } /// Adds or updates the Entry that has the given key if it is present. The new Entry will always /// be added in the front of the list of entries. /// - Parameters: /// - key: the key for the Entry to be added. /// - value: the value for the Entry to be added. internal mutating func set(key: String, value: String) { // Initially create the Entry to validate input. guard let entry = Entry(key: key, value: value) else { return } if entries.contains(where: { $0.key == entry.key }) { remove(key: entry.key) } entries.append(entry) } /// Returns a copy the traceState by appending the Entry that has the given key if it is present. /// The new Entry will always be added in the front of the existing list of entries. /// - Parameters: /// - key: the key for the Entry to be added. /// - value: the value for the Entry to be added. public func setting(key: String, value: String) -> Self { // Initially create the Entry to validate input. var newTraceState = self newTraceState.set(key: key, value: value) return newTraceState } /// Removes the Entry that has the given key if it is present. /// - Parameter key: the key for the Entry to be removed. internal mutating func remove(key: String) { if let index = entries.firstIndex(where: { $0.key == key }) { entries.remove(at: index) } } /// Returns a copy the traceState by removinf the Entry that has the given key if it is present. /// - Parameter key: the key for the Entry to be removed. public func removing(key: String) -> TraceState { // Initially create the Entry to validate input. var newTraceState = self newTraceState.remove(key: key) return newTraceState } /// Immutable key-value pair for TraceState public struct Entry: Equatable, Codable { /// The key of the Entry public private(set) var key: String /// The value of the Entry public private(set) var value: String /// Creates a new Entry for the TraceState. /// - Parameters: /// - key: the Entry's key. /// - value: the Entry's value. public init?(key: String, value: String) { if TraceStateUtils.validateKey(key: key), TraceStateUtils.validateValue(value: value) { self.key = key self.value = value return } return nil } } }
apache-2.0
886097a021c13d34c37e39d8cdd47df1
38.435644
102
0.636957
4.343511
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/Exporters/OpenTelemetryProtocol/common/CommonAdapter.swift
1
2289
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetryApi import OpenTelemetrySdk struct CommonAdapter { static func toProtoAttribute(key: String, attributeValue: AttributeValue) -> Opentelemetry_Proto_Common_V1_KeyValue { var keyValue = Opentelemetry_Proto_Common_V1_KeyValue() keyValue.key = key switch attributeValue { case let .string(value): keyValue.value.stringValue = value case let .bool(value): keyValue.value.boolValue = value case let .int(value): keyValue.value.intValue = Int64(value) case let .double(value): keyValue.value.doubleValue = value case let .stringArray(value): keyValue.value.arrayValue.values = value.map { var anyValue = Opentelemetry_Proto_Common_V1_AnyValue() anyValue.stringValue = $0 return anyValue } case let .boolArray(value): keyValue.value.arrayValue.values = value.map { var anyValue = Opentelemetry_Proto_Common_V1_AnyValue() anyValue.boolValue = $0 return anyValue } case let .intArray(value): keyValue.value.arrayValue.values = value.map { var anyValue = Opentelemetry_Proto_Common_V1_AnyValue() anyValue.intValue = Int64($0) return anyValue } case let .doubleArray(value): keyValue.value.arrayValue.values = value.map { var anyValue = Opentelemetry_Proto_Common_V1_AnyValue() anyValue.doubleValue = $0 return anyValue } } return keyValue } static func toProtoInstrumentationScope(instrumentationScopeInfo: InstrumentationScopeInfo) -> Opentelemetry_Proto_Common_V1_InstrumentationScope { var instrumentationScope = Opentelemetry_Proto_Common_V1_InstrumentationScope() instrumentationScope.name = instrumentationScopeInfo.name if let version = instrumentationScopeInfo.version { instrumentationScope.version = version } return instrumentationScope } }
apache-2.0
d2c8eed88ad81771d637da2b74df8b16
36.52459
151
0.619921
5.190476
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Pods/RxSwift/RxSwift/Traits/Maybe.swift
4
12978
// // Maybe.swift // RxSwift // // Created by sergdort on 19/08/2017. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // #if DEBUG import Foundation #endif /// Sequence containing 0 or 1 elements public enum MaybeTrait { } /// Represents a push style sequence containing 0 or 1 element. public typealias Maybe<Element> = PrimitiveSequence<MaybeTrait, Element> public enum MaybeEvent<Element> { /// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`) case success(Element) /// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`) case error(Swift.Error) /// Sequence completed successfully. case completed } extension PrimitiveSequenceType where TraitType == MaybeTrait { public typealias MaybeObserver = (MaybeEvent<ElementType>) -> Void /** Creates an observable sequence from a specified subscribe method implementation. - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. - returns: The observable sequence with the specified implementation for the `subscribe` method. */ public static func create(subscribe: @escaping (@escaping MaybeObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> { let source = Observable<ElementType>.create { observer in return subscribe { event in switch event { case .success(let element): observer.on(.next(element)) observer.on(.completed) case .error(let error): observer.on(.error(error)) case .completed: observer.on(.completed) } } } return PrimitiveSequence(raw: source) } /** Subscribes `observer` to receive events for this sequence. - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. */ public func subscribe(_ observer: @escaping (MaybeEvent<ElementType>) -> Void) -> Disposable { var stopped = false return self.primitiveSequence.asObservable().subscribe { event in if stopped { return } stopped = true switch event { case .next(let element): observer(.success(element)) case .error(let error): observer(.error(error)) case .completed: observer(.completed) } } } /** Subscribes a success handler, an error handler, and a completion handler for this sequence. - parameter onSuccess: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribe(onSuccess: ((ElementType) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil) -> Disposable { #if DEBUG let callStack = Hooks.recordCallStackOnError ? Thread.callStackSymbols : [] #else let callStack = [String]() #endif return self.primitiveSequence.subscribe { event in switch event { case .success(let element): onSuccess?(element) case .error(let error): if let onError = onError { onError(error) } else { Hooks.defaultErrorHandler(callStack, error) } case .completed: onCompleted?() } } } } extension PrimitiveSequenceType where TraitType == MaybeTrait { /** Returns an observable sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting observable sequence. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: ElementType) -> Maybe<ElementType> { return Maybe(raw: Observable.just(element)) } /** Returns an observable sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting observable sequence. - parameter scheduler: Scheduler to send the single element on. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: ElementType, scheduler: ImmediateSchedulerType) -> Maybe<ElementType> { return Maybe(raw: Observable.just(element, scheduler: scheduler)) } /** Returns an observable sequence that terminates with an `error`. - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: The observable sequence that terminates with specified error. */ public static func error(_ error: Swift.Error) -> Maybe<ElementType> { return PrimitiveSequence(raw: Observable.error(error)) } /** Returns a non-terminating observable sequence, which can be used to denote an infinite duration. - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An observable sequence whose observers will never get called. */ public static func never() -> Maybe<ElementType> { return PrimitiveSequence(raw: Observable.never()) } /** Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An observable sequence with no elements. */ public static func empty() -> Maybe<ElementType> { return Maybe(raw: Observable.empty()) } } extension PrimitiveSequenceType where TraitType == MaybeTrait { /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. - returns: The source sequence with the side-effecting behavior applied. */ public func `do`(onNext: ((ElementType) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Maybe<ElementType> { return Maybe(raw: self.primitiveSequence.source.do( onNext: onNext, onError: onError, onCompleted: onCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) ) } /** Filters the elements of an observable sequence based on a predicate. - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. */ public func filter(_ predicate: @escaping (ElementType) throws -> Bool) -> Maybe<ElementType> { return Maybe(raw: self.primitiveSequence.source.filter(predicate)) } /** Projects each element of an observable sequence into a new form. - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) - parameter transform: A transform function to apply to each source element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. */ public func map<R>(_ transform: @escaping (ElementType) throws -> R) -> Maybe<R> { return Maybe(raw: self.primitiveSequence.source.map(transform)) } /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. */ public func flatMap<R>(_ selector: @escaping (ElementType) throws -> Maybe<R>) -> Maybe<R> { return Maybe<R>(raw: self.primitiveSequence.source.flatMap(selector)) } /** Emits elements from the source observable sequence, or a default element if the source observable sequence is empty. - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) - parameter default: Default element to be sent if the source does not emit any elements - returns: An observable sequence which emits default element end completes in case the original sequence is empty */ public func ifEmpty(default: ElementType) -> Single<ElementType> { return Single(raw: self.primitiveSequence.source.ifEmpty(default: `default`)) } /** Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) - parameter switchTo: Observable sequence being returned when source sequence is empty. - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. */ public func ifEmpty(switchTo other: Maybe<ElementType>) -> Maybe<ElementType> { return Maybe(raw: self.primitiveSequence.source.ifEmpty(switchTo: other.primitiveSequence.source)) } /** Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) - parameter switchTo: Observable sequence being returned when source sequence is empty. - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. */ public func ifEmpty(switchTo other: Single<ElementType>) -> Single<ElementType> { return Single(raw: self.primitiveSequence.source.ifEmpty(switchTo: other.primitiveSequence.source)) } /** Continues an observable sequence that is terminated by an error with a single element. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) - parameter element: Last element in an observable sequence in case error occurs. - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. */ public func catchErrorJustReturn(_ element: ElementType) -> PrimitiveSequence<TraitType, ElementType> { return PrimitiveSequence(raw: self.primitiveSequence.source.catchErrorJustReturn(element)) } }
apache-2.0
c899284f5eb22434f72c4a64ec75cddd
43.290102
220
0.671033
5.15779
false
false
false
false
craiggrummitt/ActionSwift3
ActionSwift3/display/Graphics.swift
1
2868
// // Graphics.swift // ActionSwiftSK // // Created by Craig on 6/05/2015. // Copyright (c) 2015 Interactive Coconut. All rights reserved. // import SpriteKit /** A Graphics class can be used to display shapes. First call `beginFill` if you want a fill color and call `lineStyle` to set the line style. Then you can draw a circle, elipse, rectangle or triangle. */ open class Graphics: Object { var node = SKNode() var fillColor = UIColor.black var lineColor = UIColor.black var thickness:CGFloat = 1 weak var owner:Sprite? var shapes:[GraphicsNode] = [] var userInteractionEnabled:Bool = true { didSet { for shape in shapes { shape.isUserInteractionEnabled = userInteractionEnabled } } } func makeOwner(_ owner:Sprite) { self.owner = owner } open func beginFill(_ color:UIColor) { fillColor = color } open func lineStyle(_ thickness:CGFloat,lineColor:UIColor) { self.thickness = thickness self.lineColor = lineColor } open func clear() { if let graphicsParent = node.parent { node.removeFromParent() node = SKNode() graphicsParent.addChild(node) shapes = [] } } open func drawCircle(_ x:CGFloat,_ y:CGFloat,_ radius:CGFloat) { let shapeNode = GraphicsNode(circleOfRadius: radius) shapeNode.position = CGPoint(x: x, y: Stage.size.height - (y)) drawShape(shapeNode) } open func drawEllipse(_ x:CGFloat,_ y:CGFloat,_ width:CGFloat,_ height:CGFloat) { let shapeNode = GraphicsNode(ellipseOf: CGSize(width: width, height: height)) shapeNode.position = CGPoint(x: x, y: Stage.size.height - (y)) drawShape(shapeNode) } open func drawRect(_ x:CGFloat,_ y:CGFloat,_ width:CGFloat,_ height:CGFloat) { let shapeNode = GraphicsNode(rect: CGRect(x: x, y: Stage.size.height - (y + height), width: width, height: height)) drawShape(shapeNode) } open func drawTriangle(_ x1:CGFloat,_ y1:CGFloat,_ x2:CGFloat,_ y2:CGFloat,_ x3:CGFloat,_ y3:CGFloat) { let path = CGMutablePath() path.move(to: CGPoint(x:x1, y:Stage.size.height - y1)) path.addLine(to: CGPoint(x: x2, y: Stage.size.height - y2)) path.addLine(to: CGPoint(x: x3, y: Stage.size.height - y3)) path.closeSubpath() let shapeNode = GraphicsNode(path: path) drawShape(shapeNode) } fileprivate func drawShape(_ shapeNode:GraphicsNode) { shapeNode.fillColor = fillColor shapeNode.strokeColor = lineColor shapeNode.lineWidth = thickness shapeNode.owner = owner shapeNode.isUserInteractionEnabled = userInteractionEnabled shapes.push(shapeNode) self.node.addChild(shapeNode) } }
mit
fafe0e37062b0a4a55abdb93b0cee5d9
33.97561
139
0.631102
4.12069
false
false
false
false
manavgabhawala/swift
test/DebugInfo/typearg.swift
1
1674
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s protocol AProtocol { func f() -> String } class AClass : AProtocol { func f() -> String { return "A" } } // CHECK: define hidden {{.*}}void @{{.*}}aFunction // CHECK: call void @llvm.dbg.declare(metadata %swift.type** %{{.*}}, metadata ![[TYPEARG:.*]], metadata !{{[0-9]+}}), // CHECK: ![[TYPEARG]] = !DILocalVariable(name: "$swift.type.T" // CHECK-SAME: type: ![[SWIFTMETATYPE:[^,)]+]] // CHECK-SAME: flags: DIFlagArtificial // CHECK: ![[SWIFTMETATYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$swift.type", // CHECK-SAME: baseType: ![[VOIDPTR:[0-9]+]] // CHECK: ![[VOIDPTR]] = !DIDerivedType(tag: DW_TAG_pointer_type, name: "_TtBp", baseType: null func aFunction<T : AProtocol>(_ x: T) { print("I am in aFunction: \(x.f())") } aFunction(AClass()) // Verify that we also emit a swift.type for a generic self. class Foo<Bar> { func one() { } func two<Baz>(_ x: Baz) { // TODO: leave breadcrumbs for how to dynamically derive T in the debugger // CHECK- FIXME: !DILocalVariable(name: "$swift.type.Bar" // CHECK: !DILocalVariable(name: "$swift.type.Baz" } } // Verify that the backend doesn't elide the debug intrinsics. // RUN: %target-swift-frontend %s -c -g -o %t.o // RUN: %llvm-dwarfdump %t.o | %FileCheck %s --check-prefix=CHECK-LLVM // CHECK-LLVM-DAG: .debug_str[{{.*}}] = "x" // CHECK-LLVM-DAG: .debug_str[{{.*}}] = "$swift.type.T" // CHECK- FIXME -LLVM-DAG: .debug_str[{{.*}}] = "$swift.type.Bar" // CHECK-LLVM-DAG: .debug_str[{{.*}}] = "$swift.type.Baz"
apache-2.0
625a2e6d8193c3419b955d321afaab66
38.857143
119
0.580048
3.206897
false
false
false
false
material-motion/material-motion-components-swift
src/transitions/fab-masked-reveal/FABMaskedRevealTransition.swift
1
16075
/* Copyright 2017-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import MaterialMotion /** A floating action button (FAB) masked reveal transition will use a mask effect to reveal the presented view controller as it slides into position. During dismissal, this transition falls back to a VerticalSheetTransition. */ public final class FABMaskedRevealTransition: TransitionWithPresentation, TransitionWithTermination, TransitionWithFallback { public init(fabView: UIView) { self.fabView = fabView } /** This optional block can be used to customize the frame of the presented view controller. If no block is provided, then the presented view controller will consume the entire container view's bounds. The first argument is the **presenting** view controller. The second argument is the **presented** view controller. */ public var calculateFrameOfPresentedViewInContainerView: CalculateFrame? public func defaultModalPresentationStyle() -> UIModalPresentationStyle? { if calculateFrameOfPresentedViewInContainerView != nil { return .custom } return nil } public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { if let calculateFrameOfPresentedViewInContainerView = calculateFrameOfPresentedViewInContainerView { isUsingPresentationController = true return DimmingPresentationController(presentedViewController: presented, presenting: presenting, calculateFrameOfPresentedViewInContainerView: calculateFrameOfPresentedViewInContainerView) } isUsingPresentationController = false return nil } private var motion: Motion! public func fallbackTansition(withContext ctx: TransitionContext) -> Transition { self.motion = motion(withContext: ctx) if motion == nil { return VerticalSheetTransition() } return self } public func didEndTransition(withContext ctx: TransitionContext, runtime: MotionRuntime) { if !isUsingPresentationController { scrimView.removeFromSuperview() scrimView = nil } originalParentView.addSubview(ctx.fore.view) ctx.fore.view.frame.origin = originalOrigin maskedContainerView.removeFromSuperview() maskedContainerView = nil originalParentView = nil originalOrigin = nil } public func willBeginTransition(withContext ctx: TransitionContext, runtime: MotionRuntime) -> [Stateful] { var interactions: [Stateful] = [] if !isUsingPresentationController { scrimView = UIView(frame: ctx.containerView().bounds) scrimView.backgroundColor = UIColor(white: 0, alpha: 0.3) ctx.containerView().addSubview(scrimView) } originalParentView = ctx.fore.view.superview originalOrigin = ctx.fore.view.frame.origin let originalFrame = ctx.fore.view.frame maskedContainerView = UIView(frame: ctx.fore.view.frame) maskedContainerView.clipsToBounds = true ctx.containerView().addSubview(maskedContainerView) let floodFillView = UIView() floodFillView.backgroundColor = fabView.backgroundColor floodFillView.frame = ctx.fore.view.bounds // TODO(featherless): Profile whether it's more performant to fade the flood fill out or to // fade the fore view in (what we're currently doing). maskedContainerView.addSubview(floodFillView) maskedContainerView.addSubview(ctx.fore.view) ctx.fore.view.frame.origin = .zero // Fade out the label, if any. if let button = fabView as? UIButton, let titleLabel = button.titleLabel, let text = titleLabel.text, !text.isEmpty { if let tween = motion.tween(for: motion.labelFade, values: [CGFloat(1), 0]) { let label = ctx.replicator.replicate(view: titleLabel) runtime.add(tween, to: runtime.get(label.layer).opacity) interactions.append(tween) } } let fabFrameInContainer = fabView.convert(fabView.bounds, to: ctx.containerView()) let startingFrame: CGRect let vecToEdge: CGVector switch motion.contentPositioning { case .centered: startingFrame = CGRect(x: fabFrameInContainer.midX - ctx.fore.view.bounds.width / 2, y: fabFrameInContainer.midY - ctx.fore.view.bounds.height / 2, width: ctx.fore.view.bounds.width, height: ctx.fore.view.bounds.height) vecToEdge = CGVector(dx: fabFrameInContainer.midX - startingFrame.maxX, dy: fabFrameInContainer.midY - startingFrame.maxY) case .alignedNearTop: startingFrame = CGRect(x: ctx.fore.view.frame.minX, y: fabFrameInContainer.minY - 20, width: ctx.fore.view.bounds.width, height: ctx.fore.view.bounds.height) if fabFrameInContainer.midX < startingFrame.midX { vecToEdge = CGVector(dx: fabFrameInContainer.midX - startingFrame.maxX, dy: fabFrameInContainer.midY - startingFrame.midY) } else { vecToEdge = CGVector(dx: fabFrameInContainer.midX - startingFrame.minX, dy: fabFrameInContainer.midY - startingFrame.midY) } } maskedContainerView.frame = startingFrame let fabFrameInContent = maskedContainerView.convert(fabFrameInContainer, from: ctx.containerView()) let endingFrame = originalFrame let fabMaskLayer = CAShapeLayer() fabMaskLayer.path = UIBezierPath(rect: maskedContainerView.bounds).cgPath maskedContainerView.layer.mask = fabMaskLayer if let tween = motion.tween(for: motion.contentFade, values: [CGFloat(0), 1]) { runtime.add(tween, to: runtime.get(ctx.fore.view).layer.opacity) interactions.append(tween) } let foreColor = ctx.fore.view.backgroundColor ?? .white if let tween = motion.tween(for: motion.fabBackgroundColor, values: [floodFillView.backgroundColor!.cgColor, foreColor.cgColor]) { runtime.add(tween, to: runtime.get(floodFillView).layer.backgroundColor) interactions.append(tween) } // This is a guestimate answer to "when will the circle completely fill the visible content?" let targetRadius = CGFloat(sqrt(vecToEdge.dx * vecToEdge.dx + vecToEdge.dy * vecToEdge.dy)) let foreMaskBounds = CGRect(x: fabFrameInContent.midX - targetRadius, y: fabFrameInContent.midY - targetRadius, width: targetRadius * 2, height: targetRadius * 2) if let tween = motion.tween(for: motion.maskTransformation, values: [UIBezierPath(ovalIn: fabFrameInContent).cgPath, UIBezierPath(ovalIn: foreMaskBounds).cgPath]) { runtime.add(tween, to: runtime.get(fabMaskLayer).path) interactions.append(tween) if motion.shouldReverseValues { fabMaskLayer.path = UIBezierPath(ovalIn: fabFrameInContent).cgPath } else { fabMaskLayer.path = UIBezierPath(rect: maskedContainerView.bounds).cgPath } } if let tween = motion.tween(for: motion.verticalMovement, values: [startingFrame.midY, endingFrame.midY]) { runtime.add(tween, to: runtime.get(maskedContainerView.layer).positionY) interactions.append(tween) } if let tween = motion.tween(for: motion.horizontalMovement, values: [startingFrame.midX, endingFrame.midX]) { runtime.add(tween, to: runtime.get(maskedContainerView.layer).positionX) interactions.append(tween) } if !isUsingPresentationController { if let tween = motion.tween(for: motion.scrimFade, values: [CGFloat(0), 1]) { runtime.add(tween, to: runtime.get(scrimView).layer.opacity) interactions.append(tween) } } runtime.add(Hidden(), to: fabView) return interactions } // Our motion router is based on context. We inspect the desired size of the content and adjust // the motion accordingly. private func motion(withContext ctx: TransitionContext) -> Motion? { let motion: Motion? if ctx.fore.view.frame == ctx.containerView().bounds { if ctx.direction.value == .forward { motion = fullscreenExpansion } else { motion = nil } } else if ctx.fore.view.frame.width == ctx.containerView().bounds.width && ctx.fore.view.frame.maxY == ctx.containerView().bounds.maxY { if ctx.fore.view.frame.height > 100 { if ctx.direction.value == .forward { motion = bottomSheetExpansion } else { motion = nil } } else { if ctx.direction.value == .forward { motion = toolbarExpansion } else { motion = toolbarCollapse } } } else if ctx.fore.view.frame.width < ctx.containerView().bounds.width && ctx.fore.view.frame.midY >= ctx.containerView().bounds.midY { if ctx.direction.value == .forward { motion = bottomCardExpansion } else { motion = bottomCardCollapse } } else { assertionFailure("Unhandled case.") motion = nil } return motion } private let fabView: UIView private var scrimView: UIView! private var maskedContainerView: UIView! private var originalParentView: UIView! private var originalOrigin: CGPoint! private var isUsingPresentationController = false } // TODO: The need here is we want to hide a given view will the transition is active. This // implementation does not register a stream with the runtime. private class Hidden: Interaction { deinit { for view in hiddenViews { view.isHidden = false } } func add(to view: UIView, withRuntime runtime: MotionRuntime, constraints: NoConstraints) { view.isHidden = true hiddenViews.insert(view) } var hiddenViews = Set<UIView>() } private let eightyForty: [Float] = [0.4, 0.0, 0.2, 1.0] private let fortyOut: [Float] = [0.4, 0.0, 1.0, 1.0] private let eightyIn: [Float] = [0.0, 0.0, 0.2, 1.0] private struct Motion { struct Timing { let delay: CGFloat let duration: CGFloat let controlPoints: [Float] } let labelFade: Timing let contentFade: Timing let fabBackgroundColor: Timing let maskTransformation: Timing let horizontalMovement: Timing? let verticalMovement: Timing let scrimFade: Timing enum ContentPositioning { case alignedNearTop case centered } let contentPositioning: ContentPositioning let shouldReverseValues: Bool func tween<T>(for timing: Motion.Timing?, values: [T]) -> Tween<T>? { guard let timing = timing else { return nil } let tween = Tween(duration: timing.duration, values: shouldReverseValues ? values.reversed() : values) tween.delay.value = timing.delay let timingFunction = CAMediaTimingFunction(controlPoints: timing.controlPoints[0], timing.controlPoints[1], timing.controlPoints[2], timing.controlPoints[3]) tween.timingFunctions.value = [timingFunction] return tween } } private let fullscreenExpansion = Motion( labelFade: .init(delay: 0, duration: 0.075, controlPoints: eightyForty), contentFade: .init(delay: 0.150, duration: 0.225, controlPoints: eightyForty), fabBackgroundColor: .init(delay: 0, duration: 0.075, controlPoints: eightyForty), maskTransformation: .init(delay: 0, duration: 0.105, controlPoints: fortyOut), horizontalMovement: nil, verticalMovement: .init(delay: 0.045, duration: 0.330, controlPoints: eightyForty), scrimFade: .init(delay: 0, duration: 0.150, controlPoints: eightyForty), contentPositioning: .alignedNearTop, shouldReverseValues: false ) private let bottomSheetExpansion = Motion( labelFade: .init(delay: 0, duration: 0.075, controlPoints: eightyForty), contentFade: .init(delay: 0.100, duration: 0.200, controlPoints: eightyForty), // No spec for this fabBackgroundColor: .init(delay: 0, duration: 0.075, controlPoints: eightyForty), maskTransformation: .init(delay: 0, duration: 0.105, controlPoints: fortyOut), horizontalMovement: nil, verticalMovement: .init(delay: 0.045, duration: 0.300, controlPoints: eightyForty), scrimFade: .init(delay: 0, duration: 0.150, controlPoints: eightyForty), contentPositioning: .alignedNearTop, shouldReverseValues: false ) private let bottomCardExpansion = Motion( labelFade: .init(delay: 0, duration: 0.120, controlPoints: eightyForty), contentFade: .init(delay: 0.150, duration: 0.150, controlPoints: eightyForty), fabBackgroundColor: .init(delay: 0.075, duration: 0.075, controlPoints: eightyForty), maskTransformation: .init(delay: 0.045, duration: 0.225, controlPoints: fortyOut), horizontalMovement: .init(delay: 0, duration: 0.150, controlPoints: eightyForty), verticalMovement: .init(delay: 0, duration: 0.345, controlPoints: eightyForty), scrimFade: .init(delay: 0.075, duration: 0.150, controlPoints: eightyForty), contentPositioning: .centered, shouldReverseValues: false ) private let bottomCardCollapse = Motion( labelFade: .init(delay: 0.150, duration: 0.150, controlPoints: eightyForty), contentFade: .init(delay: 0, duration: 0.075, controlPoints: fortyOut), fabBackgroundColor: .init(delay: 0.060, duration: 0.150, controlPoints: eightyForty), maskTransformation: .init(delay: 0, duration: 0.180, controlPoints: eightyIn), horizontalMovement: .init(delay: 0.045, duration: 0.255, controlPoints: eightyForty), verticalMovement: .init(delay: 0, duration: 0.255, controlPoints: eightyForty), scrimFade: .init(delay: 0, duration: 0.150, controlPoints: eightyForty), contentPositioning: .centered, shouldReverseValues: true ) private let toolbarExpansion = Motion( labelFade: .init(delay: 0, duration: 0.120, controlPoints: eightyForty), contentFade: .init(delay: 0.150, duration: 0.150, controlPoints: eightyForty), fabBackgroundColor: .init(delay: 0.075, duration: 0.075, controlPoints: eightyForty), maskTransformation: .init(delay: 0.045, duration: 0.225, controlPoints: fortyOut), horizontalMovement: .init(delay: 0, duration: 0.300, controlPoints: eightyForty), verticalMovement: .init(delay: 0, duration: 0.120, controlPoints: eightyForty), scrimFade: .init(delay: 0.075, duration: 0.150, controlPoints: eightyForty), contentPositioning: .centered, shouldReverseValues: false ) private let toolbarCollapse = Motion( labelFade: .init(delay: 0.150, duration: 0.150, controlPoints: eightyForty), contentFade: .init(delay: 0, duration: 0.075, controlPoints: fortyOut), fabBackgroundColor: .init(delay: 0.060, duration: 0.150, controlPoints: eightyForty), maskTransformation: .init(delay: 0, duration: 0.180, controlPoints: eightyIn), horizontalMovement: .init(delay: 0.105, duration: 0.195, controlPoints: eightyForty), verticalMovement: .init(delay: 0, duration: 0.255, controlPoints: eightyForty), scrimFade: .init(delay: 0, duration: 0.150, controlPoints: eightyForty), contentPositioning: .centered, shouldReverseValues: true )
apache-2.0
60f2f846fc434b026cc140125e95209e
40.217949
140
0.689642
4.389678
false
false
false
false
nkirby/Humber
Humber/_src/Table View Cells/AccountFollowedUserCell.swift
1
1557
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import HMCore import HMGithub // ======================================================= class AccountFollowedUserCell: UITableViewCell { @IBOutlet var iconImageView: UIImageView! @IBOutlet var usernameLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func layoutSubviews() { super.layoutSubviews() self.iconImageView.layer.masksToBounds = true self.iconImageView.layer.cornerRadius = self.iconImageView.frame.size.width / 2.0 } override func prepareForReuse() { super.prepareForReuse() self.iconImageView.image = nil self.usernameLabel.text = "" } // ======================================================= internal func render(model model: GithubUserModel) { self.backgroundColor = Theme.color(type: .CellBackgroundColor) let attrString = NSAttributedString(string: model.login, attributes: [ NSForegroundColorAttributeName: Theme.color(type: .PrimaryTextColor), NSFontAttributeName: Theme.font(type: .Bold(12.0)) ]) self.usernameLabel.attributedText = attrString ImageCache.sharedImageCache.image(image: Image(userID: model.userID)) {[weak self] success, image in self?.iconImageView.image = image } } }
mit
4a64b45b7a6112d9baff7655d97e7e2f
28.942308
108
0.557482
5.831461
false
false
false
false
YolandaYang/theescaperoom
wp-content/themes/jupiter/Projects/swiftris-master/Swiftris/Block.swift
1
1476
// // Block.swift // Swiftris // // Created by Stan Idesis on 7/18/14. // Copyright (c) 2014 Bloc. All rights reserved. // import SpriteKit let NumberOfColors: UInt32 = 6 enum BlockColor: Int, Printable { case Blue = 0, Orange, Purple, Red, Teal, Yellow var spriteName: String { switch self { case .Blue: return "blue" case .Orange: return "orange" case .Purple: return "purple" case .Red: return "red" case .Teal: return "teal" case .Yellow: return "yellow" } } var description: String { return self.spriteName } static func random() -> BlockColor { return BlockColor.fromRaw(Int(arc4random_uniform(NumberOfColors)))! } } class Block: Hashable, Printable { // Constants let color: BlockColor // Variables var column: Int var row: Int // Lazy loading var sprite: SKSpriteNode? var spriteName: String { return color.description } var hashValue: Int { return self.column ^ self.row } var description: String { return "\(color) (\(column), \(row))" } init(column:Int, row:Int, color:BlockColor) { self.column = column self.row = row self.color = color } } func ==(lhs: Block, rhs: Block) -> Bool { return lhs.column == rhs.column && lhs.row == rhs.row && lhs.color.toRaw() == rhs.color.toRaw() }
gpl-2.0
dc04258bb399d0e9041580638fc12807
18.68
99
0.571138
3.874016
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Scenes/Open a scene (portal item)/OpenSceneViewController.swift
1
1445
// Copyright 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class OpenSceneViewController: UIViewController { @IBOutlet weak var sceneView: AGSSceneView! override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["OpenSceneViewController"] // Initialize portal with AGOL. let portal = AGSPortal.arcGISOnline(withLoginRequired: false) // Get the portal item, a scene featuring Berlin, Germany. let portalItem = AGSPortalItem(portal: portal, itemID: "31874da8a16d45bfbc1273422f772270") // Create a scene from the portal item. let scene = AGSScene(item: portalItem) // Set the scene to the scene view. sceneView.scene = scene } }
apache-2.0
68ea00b848414ea619635810b927a5fa
37.026316
112
0.70173
4.473684
false
false
false
false
mmisesin/github_client
Pods/OAuthSwift/Sources/OAuth1Swift.swift
5
7184
// // OAuth1Swift.swift // OAuthSwift // // Created by Dongri Jin on 6/22/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation open class OAuth1Swift: OAuthSwift { // If your oauth provider doesn't provide `oauth_verifier` // set this value to true (default: false) open var allowMissingOAuthVerifier: Bool = false var consumerKey: String var consumerSecret: String var requestTokenUrl: String var authorizeUrl: String var accessTokenUrl: String // MARK: init public init(consumerKey: String, consumerSecret: String, requestTokenUrl: String, authorizeUrl: String, accessTokenUrl: String){ self.consumerKey = consumerKey self.consumerSecret = consumerSecret self.requestTokenUrl = requestTokenUrl self.authorizeUrl = authorizeUrl self.accessTokenUrl = accessTokenUrl super.init(consumerKey: consumerKey, consumerSecret: consumerSecret) self.client.credential.version = .oauth1 } public convenience init?(parameters: ConfigParameters){ guard let consumerKey = parameters["consumerKey"], let consumerSecret = parameters["consumerSecret"], let requestTokenUrl = parameters["requestTokenUrl"], let authorizeUrl = parameters["authorizeUrl"], let accessTokenUrl = parameters["accessTokenUrl"] else { return nil } self.init(consumerKey:consumerKey, consumerSecret: consumerSecret, requestTokenUrl: requestTokenUrl, authorizeUrl: authorizeUrl, accessTokenUrl: accessTokenUrl) } open var parameters: ConfigParameters { return [ "consumerKey": consumerKey, "consumerSecret": consumerSecret, "requestTokenUrl": requestTokenUrl, "authorizeUrl": authorizeUrl, "accessTokenUrl": accessTokenUrl ] } // MARK: functions // 0. Start @discardableResult open func authorize(withCallbackURL callbackURL: URL, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? { self.postOAuthRequestToken(callbackURL: callbackURL, success: { [unowned self] credential, response, _ in self.observeCallback { [weak self] url in guard let this = self else { OAuthSwift.retainError(failure); return } var responseParameters = [String: String]() if let query = url.query { responseParameters += query.parametersFromQueryString } if let fragment = url.fragment , !fragment.isEmpty { responseParameters += fragment.parametersFromQueryString } if let token = responseParameters["token"] { responseParameters["oauth_token"] = token } if let token = responseParameters["oauth_token"] { this.client.credential.oauthToken = token.safeStringByRemovingPercentEncoding if let oauth_verifier = responseParameters["oauth_verifier"] { this.client.credential.oauthVerifier = oauth_verifier.safeStringByRemovingPercentEncoding } else { if !this.allowMissingOAuthVerifier { failure?(OAuthSwiftError.configurationError(message: "Missing oauth_verifier. Maybe use allowMissingOAuthVerifier=true")) return } } this.postOAuthAccessTokenWithRequestToken(success: success, failure: failure) } else { failure?(OAuthSwiftError.missingToken) return } } // 2. Authorize let urlString = self.authorizeUrl + (self.authorizeUrl.contains("?") ? "&" : "?") if let token = credential.oauthToken.urlQueryEncoded, let queryURL = URL(string: urlString + "oauth_token=\(token)") { self.authorizeURLHandler.handle(queryURL) } else { failure?(OAuthSwiftError.encodingError(urlString: urlString)) } }, failure: failure) return self } @discardableResult open func authorize(withCallbackURL urlString: String, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? { guard let url = URL(string: urlString) else { failure?(OAuthSwiftError.encodingError(urlString: urlString)) return nil } return authorize(withCallbackURL: url, success: success, failure: failure) } // 1. Request token func postOAuthRequestToken(callbackURL: URL, success: @escaping TokenSuccessHandler, failure: FailureHandler?) { var parameters = Dictionary<String, Any>() parameters["oauth_callback"] = callbackURL.absoluteString if let handle = self.client.post( self.requestTokenUrl, parameters: parameters, success: { [weak self] response in guard let this = self else { OAuthSwift.retainError(failure); return } let parameters = response.string?.parametersFromQueryString ?? [:] if let oauthToken = parameters["oauth_token"] { this.client.credential.oauthToken = oauthToken.safeStringByRemovingPercentEncoding } if let oauthTokenSecret=parameters["oauth_token_secret"] { this.client.credential.oauthTokenSecret = oauthTokenSecret.safeStringByRemovingPercentEncoding } success(this.client.credential, response, parameters) }, failure: failure ) { self.putHandle(handle, withKey: UUID().uuidString) } } // 3. Get Access token func postOAuthAccessTokenWithRequestToken(success: @escaping TokenSuccessHandler, failure: FailureHandler?) { var parameters = Dictionary<String, Any>() parameters["oauth_token"] = self.client.credential.oauthToken parameters["oauth_verifier"] = self.client.credential.oauthVerifier if let handle = self.client.post( self.accessTokenUrl, parameters: parameters, success: { [weak self] response in guard let this = self else { OAuthSwift.retainError(failure); return } let parameters = response.string?.parametersFromQueryString ?? [:] if let oauthToken = parameters["oauth_token"] { this.client.credential.oauthToken = oauthToken.safeStringByRemovingPercentEncoding } if let oauthTokenSecret = parameters["oauth_token_secret"] { this.client.credential.oauthTokenSecret = oauthTokenSecret.safeStringByRemovingPercentEncoding } success(this.client.credential, response, parameters) }, failure: failure ) { self.putHandle(handle, withKey: UUID().uuidString) } } }
mit
1089d53050ea15a3ba58f97b3bdc0c04
43.345679
168
0.61985
5.82644
false
false
false
false
LunarLincoln/nodekit-darwin-lite
src/nodekit/NKScripting/util/NKArchive/NKArchiveReader.swift
1
4059
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright (c) 2013 GitHub, Inc. under MIT License * Portions Copyright (c) 2015 lazyapps. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation public struct NKArchiveReader { var _cacheCDirs: NSCache<NSString, NKArchive> var _cacheArchiveData: NSCache<NSString, NSData> } public extension NKArchiveReader { static func create() -> NKArchiveReader { let cacheArchiveData2 = NSCache<NSString, NSData>() cacheArchiveData2.countLimit = 10 return NKArchiveReader( _cacheCDirs: NSCache(), _cacheArchiveData: cacheArchiveData2) } mutating func dataForFile(_ archive: String, filename: String) -> Data? { if let nkArchive = _cacheCDirs.object(forKey: archive as NSString) { if let data = _cacheArchiveData.object(forKey: archive as NSString) as? Data { return nkArchive[filename, withArchiveData: data] } else { return nkArchive[filename] as Data? } } else { guard let (nkArchive, data) = NKArchive.createFromPath(archive) else { return nil } _cacheCDirs.setObject(nkArchive, forKey: archive as NSString) _cacheArchiveData.setObject(data as NSData, forKey: archive as NSString) return nkArchive[filename, withArchiveData: data] } } mutating func exists(_ archive: String, filename: String) -> Bool { if let nkArchive = _cacheCDirs.object(forKey: archive as NSString) { return nkArchive.exists(filename) } else { guard let (nkArchive, data) = NKArchive.createFromPath(archive) else { return false } _cacheCDirs.setObject(nkArchive, forKey: archive as NSString) _cacheArchiveData.setObject(data as NSData, forKey: archive as NSString) return nkArchive.exists(filename) } } mutating func stat(_ archive: String, filename: String) -> Dictionary<String, AnyObject> { if let nkArchive = _cacheCDirs.object(forKey: archive as NSString) { return nkArchive.stat(filename) } else { guard let (nkArchive, data) = NKArchive.createFromPath(archive) else { return Dictionary<String, AnyObject>() } _cacheCDirs.setObject(nkArchive, forKey: archive as NSString) _cacheArchiveData.setObject(data as NSData, forKey: archive as NSString) return nkArchive.stat(filename) } } mutating func getDirectory(_ archive: String, foldername: String) -> [String] { if let nkArchive = _cacheCDirs.object(forKey: archive as NSString) { return nkArchive.getDirectory(foldername) } else { guard let (nkArchive, data) = NKArchive.createFromPath(archive) else { return [String]() } _cacheCDirs.setObject(nkArchive, forKey: archive as NSString) _cacheArchiveData.setObject(data as NSData, forKey: archive as NSString) return nkArchive.getDirectory(foldername) } } }
apache-2.0
d56bdbe05d4ad6063e4e7bd74c24ca13
33.109244
123
0.599655
4.902174
false
false
false
false
proversity-org/edx-app-ios
Source/SubjectsDiscovery/PopularSubjectsViewController.swift
1
3335
// // PopularSubjectsViewController.swift // edX // // Created by Zeeshan Arif on 5/24/18. // Copyright © 2018 edX. All rights reserved. // import UIKit protocol PopularSubjectsViewControllerDelegate: class { func popularSubjectsViewController(_ controller: PopularSubjectsViewController, didSelect subject: Subject) func didSelectViewAllSubjects(_ controller: PopularSubjectsViewController) } class PopularSubjectsViewController: UIViewController, SubjectsCollectionViewDelegate { private lazy var titleLabel: UILabel = { let label = UILabel() label.accessibilityIdentifier = "PopularSubjectsViewController:title-label" label.numberOfLines = 0 let titleStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralDark()) label.attributedText = titleStyle.attributedString(withText: Strings.Discovery.browseBySubject) return label }() fileprivate lazy var collectionView: PopularSubjectsCollectionView = { let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() let defaultMargin = SubjectCollectionViewCell.defaultMargin layout.sectionInset = UIEdgeInsets(top: defaultMargin, left: defaultMargin, bottom: defaultMargin, right: defaultMargin) layout.itemSize = CGSize(width: SubjectCollectionViewCell.defaultWidth, height: SubjectCollectionViewCell.defaultHeight) layout.scrollDirection = .horizontal let collectionView = PopularSubjectsCollectionView(with: SubjectDataModel().popularSubjects, collectionViewLayout: layout) collectionView.accessibilityIdentifier = "PopularSubjectsViewController:collection-view" collectionView.subjectsDelegate = self return collectionView }() weak var delegate: PopularSubjectsViewControllerDelegate? init() { super.init(nibName: nil, bundle: nil) addSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() } // MARK: Setup Subviews private func addSubviews(){ view.addSubview(titleLabel) view.addSubview(collectionView) setConstraints() } private func setConstraints() { titleLabel.snp.makeConstraints { make in make.leading.equalTo(view) make.trailing.equalTo(view) make.top.equalTo(view).offset(StandardVerticalMargin) } collectionView.snp.makeConstraints { make in make.leading.equalTo(titleLabel).offset(-SubjectCollectionViewCell.defaultMargin) make.trailing.equalTo(titleLabel) make.top.equalTo(titleLabel.snp.bottom) make.height.equalTo(SubjectCollectionViewCell.defaultHeight + 2 * SubjectCollectionViewCell.defaultMargin) make.bottom.equalTo(view) } } // MARK: SubjectsCollectionViewDelegate func subjectsCollectionView(_ collectionView: SubjectsCollectionView, didSelect subject: Subject) { delegate?.popularSubjectsViewController(self, didSelect: subject) } func didSelectViewAllSubjects(_ collectionView: SubjectsCollectionView) { delegate?.didSelectViewAllSubjects(self) } }
apache-2.0
c11af0c94cf2b835bded4432b8329f7f
38.690476
130
0.714157
5.547421
false
false
false
false
SteveBarnegren/TweenKit
TweenKit/TweenKit/ActionGroup.swift
1
5452
// // GroupAction.swift // TweenKit // // Created by Steve Barnegren on 19/03/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import Foundation /** Runs several actions in parallel */ public class ActionGroup: FiniteTimeAction, SchedulableAction { // MARK: - Public /** Create with a set of actions - Parameter actions: The actions the group should contain */ public convenience init(actions: FiniteTimeAction...) { self.init(actions: actions) } /** Create with a set of actions - Parameter actions: Array of actions the group should contain */ public init(actions: [FiniteTimeAction]) { actions.forEach{ add(action: $0) } } /** Create with a set of actions, all run with an offset - Parameter actions: Array of actions the group should contain - Parameter offset: The time offset of each action from the previous */ public init(staggered actions: [FiniteTimeAction], offset: Double) { for (index, action) in actions.enumerated() { if index == 0 { add(action: action) } else{ let delay = DelayAction(duration: offset * Double(index)) let sequence = ActionSequence(actions: delay, action) add(action: sequence) } } } public var onBecomeActive: () -> () = {} public var onBecomeInactive: () -> () = {} public var reverse = false { didSet { wrappedActions = wrappedActions.map{ wrapped in wrapped.action.reverse = reverse return wrapped } } } // MARK: - Private Properties public internal(set) var duration = Double(0) private var triggerActions = [TriggerAction]() private var wrappedActions = [GroupActionWrapper]() private var lastUpdateT = 0.0 // MARK: - Private methods private func add(action: FiniteTimeAction) { let allActions = wrappedActions.map{ $0.action } + (triggerActions as [FiniteTimeAction]) for existingAction in allActions { if existingAction === action { fatalError("You cannot the same action to a group multiple times!") } } if let trigger = action as? TriggerAction { triggerActions.append(trigger) } else{ let wrappedAction = GroupActionWrapper(action: action) wrappedActions.append(wrappedAction) calculateDuration() } } private func calculateDuration() { duration = wrappedActions.reduce(0){ max($0, $1.action.duration) } } public func willBecomeActive() { onBecomeActive() } public func didBecomeInactive() { onBecomeInactive() } public func willBegin() { // Set the last elapsed time lastUpdateT = reverse ? 1.0 : 0.0 // Invoke trigger actions if reverse == false { triggerActions.forEach{ $0.trigger() } } // Set actions in progress if !self.reverse { wrappedActions.forEach{ $0.state = .inProgress } } } public func didFinish() { // Finish actions for wrapper in wrappedActions { if wrapper.state == .notStarted { wrapper.state = .inProgress } if wrapper.state == .inProgress { wrapper.state = .finished } } // If we're being called in reverse, now we should call the trigger actions if reverse == true { triggerActions.forEach{ $0.trigger() } } } public func update(t: CFTimeInterval) { let elapsedTime = t * duration let lastElapsedTime = lastUpdateT * duration for wrapper in wrappedActions { // Update the action if it is in progress if elapsedTime <= wrapper.action.duration { wrapper.state = .inProgress wrapper.action.update(t: elapsedTime / wrapper.action.duration) } // Finish the action? else if !reverse, lastElapsedTime < wrapper.action.duration, elapsedTime > wrapper.action.duration { wrapper.state = .finished } } lastUpdateT = t } } class GroupActionWrapper { enum State { case notStarted case inProgress case finished } init(action: FiniteTimeAction) { self.action = action } var action: FiniteTimeAction var state = State.notStarted { didSet{ if state == oldValue { return } switch state { case .inProgress: action.willBecomeActive() action.willBegin() case .finished: action.didFinish() action.didBecomeInactive() case .notStarted: break } } } }
mit
48c3d2f397c914238b2af434323010cc
25.333333
112
0.522473
5.22627
false
false
false
false
salesforce-ux/design-system-ios
Demo-Swift/slds-sample-app/demo/controls/ActionBar.swift
1
4478
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit struct ActionItem { var label : String! var iconId : SLDSActionIconType! } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– class ActionBar: ItemBar { var actionItemsHidden: Bool = false //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var firstPosition : NSLayoutConstraint? { guard let first = self.items.first else { return nil } for constraint in self.constraints { if first.isEqual(constraint.firstItem) && constraint.firstAttribute == .bottom { return constraint } } return nil } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func draw(_ rect: CGRect) { let aPath = UIBezierPath() aPath.move(to: CGPoint(x:0, y:0)) aPath.addLine(to: CGPoint(x:self.frame.width, y:0)) aPath.close() aPath.lineWidth = 1.0 UIColor.sldsBorderColor(.colorBorderSeparatorAlt2).set() aPath.stroke() } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func addActionBarButton(_ actionButton : ActionBarButton) { super.addItem(item: actionButton) if self.items.count == 1 { self.firstPosition?.constant = self.actionItemsHidden ? self.frame.height : 0 } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func showActionBarButtons(_ animated : Bool=true, completion: ( (Void) -> (Void) )?=nil ) { self.actionItemsHidden = false animateActionBarButtons(animated, completion: completion) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func hideActionBarButtons(_ animated : Bool=true, completion: ( (Void) -> (Void) )?=nil ) { self.actionItemsHidden = true animateActionBarButtons(animated, completion: completion) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– private func animateActionBarButtons(_ animated : Bool=true, completion: ( (Void) -> (Void) )?=nil ) { let ease = self.actionItemsHidden ? UIViewAnimationOptions.curveEaseIn : UIViewAnimationOptions.curveEaseOut self.firstPosition?.constant = self.actionItemsHidden ? 56 : 0 guard animated else { self.layoutIfNeeded() if completion != nil { completion!() } return } UIView.animate(withDuration: 0.3, delay: 0, options: ease, animations: { self.layoutIfNeeded() }, completion: { (Bool) in if completion != nil { completion!() } }) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– }
bsd-3-clause
a67b5d81499be39c4d4c70ea52356bd8
31.959184
116
0.444272
5.840868
false
false
false
false
bsorrentino/slidesOnTV
slides/FavoriteViewCell.swift
1
1247
// // FavoriteViewCell.swift // slides // // Created by softphone on 28/06/2017. // Copyright © 2017 soulsoftware. All rights reserved. // import Foundation class UIFavoriteCell : UITableViewCell { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if let selectedView = self.selectedBackgroundView as? FavoritesCommandView, let progressView = selectedView.downloadProgressView { progressView.progress = 0.0 } } // MARK: FOCUS MANAGEMENT /* override func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool { print( "\(String(describing: type(of: self))).shouldUpdateFocus: \(describing(context.focusHeading))" ) if context.focusHeading == .left || context.focusHeading == .right { if context.nextFocusedView == self { // GAIN FOCUS } else if context.previouslyFocusedView == self { // LOST FOCUS } } return true } */ }
mit
0e556e4c9a4016bc860706c2a1214d55
23.92
111
0.580257
4.848249
false
false
false
false
benoit-pereira-da-silva/SwiftDynamicForms
Sources/TextViewCell.swift
2
2584
// // TextViewCell.swift // SCMBImages // // Created by Benoit Pereira da Silva on 22/04/2015. // Copyright (c) 2015 Azurgate. All rights reserved. // // MARK : - SingleObjectReferenceCellDelegate public protocol TextViewCellDelegate{ } open class TextViewCellConfigurator:CellConfigurator{ open var delegate:TextViewCellDelegate open var valueGetter:()->String open var valueHasChanged:(_ newValue:String, _ cellReference:TextViewCell)->() open var placeHolderText:String="" open var headerText:String="" open var footerText:String="" open var numberMaxOfChar:Int=Int.max public init(delegate:TextViewCellDelegate,valueGetter:@escaping ()->String, valueHasChanged:@escaping (_ newValue:String, _ cellReference:TextViewCell)->()){ self.delegate=delegate self.valueGetter=valueGetter self.valueHasChanged=valueHasChanged } } open class TextViewCell:UITableViewCell,Configurable, UITextViewDelegate { @IBOutlet weak open var textView: UITextView! @IBOutlet weak open var placeHolderLabel: UILabel? @IBOutlet weak open var headerLabel: UILabel? @IBOutlet weak open var footerLabel: UILabel? open var configurator:TextViewCellConfigurator? open func configureWith(_ configurator:Configurator){ if let configuratorInstance = configurator as? TextViewCellConfigurator { self.configurator = configuratorInstance self.headerLabel?.text = configuratorInstance.headerText self.textView.text = configuratorInstance.valueGetter() self.textView.delegate=self self.placeHolderLabel?.text = configuratorInstance.placeHolderText self.footerLabel?.text = configuratorInstance.footerText }else{ self.textView.text="TextViewCellConfigurator required" } } open func textViewDidChange(_ textView: UITextView) { if let newText=self.textView.text { self.placeHolderLabel?.isHidden = (newText.characters.count > 0) self.configurator?.valueHasChanged(newText,self) } } open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if let nbMax=self.configurator?.numberMaxOfChar { return (textView.text.characters.count < nbMax) || text=="" } return true } open func textViewShouldEndEditing(_ textView: UITextView) -> Bool { textView.resignFirstResponder() return true } }
lgpl-2.1
899687e7e250bcaf37b888fe6691e076
32.558442
161
0.690015
5.14741
false
true
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Setting/YellowPage/ClientItem.swift
1
1056
// // ClientItem.swift // YellowPage // // Created by Halcao on 2017/2/22. // Copyright © 2017年 Halcao. All rights reserved. // import Foundation class ClientItem: NSObject, NSCoding { var name = "" var phone = "" var isFavorite = false var owner: String = "" init(with name: String, phone: String, owner: String) { self.name = name self.phone = phone self.owner = owner } required init?(coder aDecoder: NSCoder) { name = aDecoder.decodeObjectForKey("yp_name") as! String phone = aDecoder.decodeObjectForKey("yp_phone") as! String isFavorite = aDecoder.decodeObjectForKey("yp_isFavorite") as! Bool owner = aDecoder.decodeObjectForKey("yp_owner") as! String } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "yp_name") aCoder.encodeObject(phone, forKey: "yp_phone") aCoder.encodeObject(isFavorite, forKey: "yp_isFavorite") aCoder.encodeObject(owner, forKey: "yp_owner") } }
mit
981d46be667de740e18b7863ca2f12e7
27.459459
74
0.632479
4.097276
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Classes/Reusable/UI/Toast/ToastView.swift
1
3600
// // ToastView.swift // byuSuite // // Created by Erik Brady on 8/14/18. // Copyright © 2018 Brigham Young University. All rights reserved. // class ToastView: UIView { private struct UI { static let maxWidth: CGFloat = 345 static let widthRatio: CGFloat = 0.9 static let hideHeight: CGFloat = 180 static let verticalMargin: CGFloat = 10 static let dismissDuration = 0.1 static let showDuration = 0.3 static let springDamping: CGFloat = 0.63 static let initialSpringVelocity: CGFloat = 0.1 static let cornerRadius: CGFloat = 5 static let shadowRadius: CGFloat = 5 static let shadowOpacity: Float = 0.25 } enum ToastType { case success case error case info var backgroundColor: UIColor { switch self { case .success: return .byuGreen case .error: return .byuRed default: return .lightGray } } } //MARK: IBOutlets @IBOutlet private weak var messageLabel: UILabel! //MARK: Private Properties private var bottomConstraint: NSLayoutConstraint! private var completion: () -> () = {} required init?(coder aDecoder:NSCoder) { super.init(coder: aDecoder) } static func show(in superView: UIView, message: String, type: ToastType = .success, dismissDelay: TimeInterval = 3.5, completion: @escaping () -> () = {}) { //Inflate from the Nib let toast = UINib(nibName: "ToastView", bundle: nil).instantiate(withOwner: nil).first as! ToastView toast.translatesAutoresizingMaskIntoConstraints = false //Save all internal variables toast.messageLabel.text = message toast.backgroundColor = type.backgroundColor toast.completion = completion toast.setupLayer() toast.setupGestureRecognizers() //Set up Timer Timer.scheduledTimer(timeInterval: dismissDelay, target: toast, selector: #selector(dismissNotification), userInfo: nil, repeats: false) //Add to SuperView superView.addSubview(toast) //Set up Constraints toast.bottomConstraint = toast.bottomAnchor.constraint(equalTo: superView.bottomAnchor, constant: UI.hideHeight) NSLayoutConstraint.activate([ toast.widthAnchor.constraint(equalTo: superView.widthAnchor, multiplier: UI.widthRatio, priority: 999), toast.widthAnchor.constraint(lessThanOrEqualToConstant: UI.maxWidth), toast.centerXAnchor.constraint(equalTo: superView.centerXAnchor), toast.bottomConstraint ]) superView.layoutIfNeeded() //Animate display toast.showNotification() } private func setupLayer() { layer.cornerRadius = UI.cornerRadius layer.shadowRadius = UI.shadowRadius layer.shadowOpacity = UI.shadowOpacity layer.shadowColor = UIColor.lightGray.cgColor } private func setupGestureRecognizers() { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissNotification)) let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.dismissNotification)) swipeRecognizer.direction = .down addGestureRecognizer(tapRecognizer) addGestureRecognizer(swipeRecognizer) } func showNotification() { bottomConstraint.constant = -UI.verticalMargin UIView.animate(withDuration: UI.showDuration, delay: 0.0, usingSpringWithDamping: UI.springDamping, initialSpringVelocity: UI.initialSpringVelocity, options: UIViewAnimationOptions(), animations: { self.superview?.layoutIfNeeded() }) } @objc func dismissNotification() { bottomConstraint.constant = UI.hideHeight UIView.animate(withDuration: UI.dismissDuration, animations: { self.superview?.layoutIfNeeded() }) { (_) in self.completion() self.removeFromSuperview() } } }
apache-2.0
fdb5ffd481892a4fecd43cd77013d7a9
29.243697
199
0.744929
4.155889
false
false
false
false
moshbit/Kotlift
test-dest/10_when.swift
2
502
/** * See https://kotlinlang.org/docs/reference/control-flow.html */ func main(args: [String]) { cases(1) cases(2) cases(3) cases(4) } func cases(x: Int32) { switch x { case 1: print("x == 1") case 2: print("x == 2") default: // Note the block print("x is neither 1 nor 2") print("x might be something more") } switch x { case 0, 1: print("x == 0 or x == 1") default: print("otherwise") } } main([])
apache-2.0
f4dd648c10b1531e144a0eb2747a1df0
17.592593
62
0.5
3.25974
false
false
false
false
adrfer/swift
test/Sema/diag_self_assign.swift
24
2817
// RUN: %target-parse-verify-swift var sa1_global: Int sa1_global = sa1_global // expected-error {{assigning a variable to itself}} class SA1 { var foo: Int = 0 init(fooi: Int) { var foo = fooi foo = foo // expected-error {{assigning a variable to itself}} self.foo = self.foo // expected-error {{assigning a property to itself}} foo = self.foo // no-error self.foo = foo // no-error } func f(fooi: Int) { var foo = fooi foo = foo // expected-error {{assigning a variable to itself}} self.foo = self.foo // expected-error {{assigning a property to itself}} foo = self.foo // no-error self.foo = foo // no-error } } class SA2 { var foo: Int { get { return 0 } set {} } init(fooi: Int) { var foo = fooi foo = foo // expected-error {{assigning a variable to itself}} self.foo = self.foo // expected-error {{assigning a property to itself}} foo = self.foo // no-error self.foo = foo // no-error } func f(fooi: Int) { var foo = fooi foo = foo // expected-error {{assigning a variable to itself}} self.foo = self.foo // expected-error {{assigning a property to itself}} foo = self.foo // no-error self.foo = foo // no-error } } class SA3 { var foo: Int { get { return foo // expected-warning {{attempting to access 'foo' within its own getter}} expected-note{{access 'self' explicitly to silence this warning}} {{14-14=self.}} } set { foo = foo // expected-error {{assigning a property to itself}} expected-warning {{attempting to modify 'foo' within its own setter}} expected-note{{access 'self' explicitly to silence this warning}} {{7-7=self.}} self.foo = self.foo // expected-error {{assigning a property to itself}} foo = self.foo // expected-error {{assigning a property to itself}} expected-warning {{attempting to modify 'foo' within its own setter}} expected-note{{access 'self' explicitly to silence this warning}} {{7-7=self.}} self.foo = foo // expected-error {{assigning a property to itself}} } } } class SA4 { var foo: Int { get { return foo // expected-warning {{attempting to access 'foo' within its own getter}} expected-note{{access 'self' explicitly to silence this warning}} {{14-14=self.}} } set(value) { value = value // expected-error {{cannot assign to value: 'value' is a 'let' constant}} } } } class SA5 { var foo: Int = 0 } func SA5_test(a: SA4, b: SA4) { a.foo = a.foo // expected-error {{assigning a property to itself}} a.foo = b.foo } class SA_Deep1 { class Foo { var aThing = String() } class Bar { var aFoo = Foo() } var aFoo = Foo() func test() { let aBar = Bar() aBar.aFoo = Foo() aBar.aFoo.aThing = self.aFoo.aThing // no-error } }
apache-2.0
315189903c7c244b825c62abc96f0060
28.041237
223
0.623358
3.43956
false
false
false
false
caicai0/ios_demo
load/Carthage/Checkouts/SwiftSoup/Example/Pods/SwiftSoup/Sources/Attribute.swift
1
4330
// // Attribute.swift // SwifSoup // // Created by Nabil Chatbi on 29/09/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation open class Attribute { /// The element type of a dictionary: a tuple containing an individual /// key-value pair. static let booleanAttributes: [String] = [ "allowfullscreen", "async", "autofocus", "checked", "compact", "declare", "default", "defer", "disabled", "formnovalidate", "hidden", "inert", "ismap", "itemscope", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "readonly", "required", "reversed", "seamless", "selected", "sortable", "truespeed", "typemustmatch" ] var key: String var value: String public init(key: String, value: String) throws { try Validate.notEmpty(string: key) self.key = key.trim() self.value = value } /** Get the attribute key. @return the attribute key */ open func getKey() -> String { return key } /** Set the attribute key; case is preserved. @param key the new key; must not be null */ open func setKey(key: String) throws { try Validate.notEmpty(string: key) self.key = key.trim() } /** Get the attribute value. @return the attribute value */ open func getValue() -> String { return value } /** Set the attribute value. @param value the new attribute value; must not be null */ @discardableResult open func setValue(value: String) -> String { let old = self.value self.value = value return old } /** Get the HTML representation of this attribute; e.g. {@code href="index.html"}. @return HTML */ public func html() -> String { let accum = StringBuilder() html(accum: accum, out: (Document("")).outputSettings()) return accum.toString() } public func html(accum: StringBuilder, out: OutputSettings ) { accum.append(key) if (!shouldCollapseAttribute(out: out)) { accum.append("=\"") Entities.escape(accum, value, out, true, false, false) accum.append("\"") } } /** Get the string representation of this attribute, implemented as {@link #html()}. @return string */ open func toString() -> String { return html() } /** * Create a new Attribute from an unencoded key and a HTML attribute encoded value. * @param unencodedKey assumes the key is not encoded, as can be only run of simple \w chars. * @param encodedValue HTML attribute encoded value * @return attribute */ open static func createFromEncoded(unencodedKey: String, encodedValue: String) throws ->Attribute { let value = try Entities.unescape(string: encodedValue, strict: true) return try Attribute(key: unencodedKey, value: value) } public func isDataAttribute() -> Bool { return key.startsWith(Attributes.dataPrefix) && key.characters.count > Attributes.dataPrefix.characters.count } /** * Collapsible if it's a boolean attribute and value is empty or same as name * * @param out Outputsettings * @return Returns whether collapsible or not */ public final func shouldCollapseAttribute(out: OutputSettings) -> Bool { return ("" == value || value.equalsIgnoreCase(string: key)) && out.syntax() == OutputSettings.Syntax.html && isBooleanAttribute() } public func isBooleanAttribute() -> Bool { return (Attribute.booleanAttributes.binarySearch(Attribute.booleanAttributes, key) != -1) } public func hashCode() -> Int { var result = key.hashValue result = 31 * result + value.hashValue return result } public func clone() -> Attribute { do { return try Attribute(key: key, value: value) } catch Exception.Error( _, let msg) { print(msg) } catch { } return try! Attribute(key: "", value: "") } } extension Attribute : Equatable { static public func == (lhs: Attribute, rhs: Attribute) -> Bool { return lhs.value == rhs.value && lhs.key == rhs.key } }
mit
13cd73e1f1a20c58c54b5f56fc319e08
28.25
117
0.603835
4.281899
false
false
false
false
VoIPGRID/vialer-ios
Vialer/Push/VoIPPushPayloadTransformer.swift
1
1256
// // Created by Jeremy Norman on 27/06/2020. // Copyright (c) 2020 VoIPGRID. All rights reserved. // import Foundation import PushKit class VoIPPushPayloadTransformer { /** Transforms the PushKit payload into a standard structure we can work with easily. */ func transform(payload: PKPushPayload) -> VoIPPushPayload? { let dictionaryPayload = payload.dictionaryPayload if let phoneNumber = dictionaryPayload[PayloadLookup.phoneNumber] as? String, let uuid = NSUUID.uuidFixer(uuidString: dictionaryPayload[PayloadLookup.uniqueKey] as! String) as UUID?, let responseUrl = dictionaryPayload[PayloadLookup.responseUrl] as? String { return VoIPPushPayload( phoneNumber: phoneNumber, uuid: uuid, responseUrl: responseUrl, callerId: dictionaryPayload[PayloadLookup.callerId] as? String, payload: payload ) } return nil } private struct PayloadLookup { static let uniqueKey = "unique_key" static let phoneNumber = "phonenumber" static let responseUrl = "response_api" static let callerId = "caller_id" } }
gpl-3.0
c6104b21724b53d6cdb7f8edde8cadd9
30.4
115
0.631369
4.812261
false
false
false
false
karstengresch/rw_studies
CoreData/Dog Walk/Dog Walk/ViewController.swift
1
4296
/** * Copyright (c) 2016 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 CoreData class ViewController: UIViewController { // MARK: - Properties lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .medium return formatter }() var managedContext: NSManagedObjectContext! var currentDog: Dog? // MARK: - IBOutlets @IBOutlet var tableView: UITableView! // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") let dogName = "Coscor" let dogFetchRequest: NSFetchRequest<Dog> = Dog.fetchRequest() dogFetchRequest.predicate = NSPredicate(format: "%K == %@", #keyPath(Dog.name), dogName) do { let results = try managedContext.fetch(dogFetchRequest) if results.count > 0 { currentDog = results.first } else { currentDog = Dog(context: managedContext) currentDog?.name = dogName } try managedContext.save() } catch let error as NSError { print("Fetch request failed: \(error) - Error description: \(error.userInfo)") } } } // MARK: - IBActions extension ViewController { @IBAction func add(_ sender: UIBarButtonItem) { let walk = Walk(context: managedContext) walk.date = NSDate() if let dog = currentDog, let walks = dog.walks?.mutableCopy() as? NSMutableOrderedSet { walks.add(walk) dog.walks = walks } do { try managedContext.save() } catch let error as NSError { print("Save request failed: \(error) - Error description: \(error.userInfo)") } tableView.reloadData() } } // MARK: UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let walks = currentDog?.walks else { return 1 } return walks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) guard let walk = currentDog?.walks?[indexPath.row] as? Walk, let walkDate = walk.date as Date? else { return cell } cell.textLabel?.text = dateFormatter.string(from: walkDate) return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "List of Walks" } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { guard let walkToRemove = currentDog?.walks?[indexPath.row] as? Walk, editingStyle == .delete else { return } managedContext.delete(walkToRemove) do { try managedContext.save() tableView.deleteRows(at: [indexPath], with: .automatic) } catch let error as NSError { print("Saving error: \(error), description: \(error.userInfo)") } } }
unlicense
0302b4325f5c0422206fc3f2bed7668e
29.685714
125
0.688315
4.649351
false
false
false
false
tensorflow/swift-apis
Tests/ExperimentalTests/ComplexTests.swift
1
13208
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import _Differentiation @testable import Experimental final class ComplexTests: XCTestCase { func testInitializer() { let complex = Complex<Float>(real: 2, imaginary: 3) XCTAssertEqual(complex.real, 2) XCTAssertEqual(complex.imaginary, 3) } func testStaticImaginary() { let imaginary = Complex<Float>(real: 0, imaginary: 1) XCTAssertEqual(imaginary, Complex.i) } func testIsFinite() { var complex = Complex<Float>(real: 999, imaginary: 0) XCTAssertTrue(complex.isFinite) complex = Complex(real: 1.0 / 0.0, imaginary: 1) XCTAssertFalse(complex.isFinite) complex = Complex(real: 1.0 / 0.0, imaginary: 1.0 / 0.0) XCTAssertFalse(complex.isFinite) } func testIsInfinite() { var complex = Complex<Float>(real: 999, imaginary: 0) XCTAssertFalse(complex.isInfinite) complex = Complex(real: 1.0 / 0.0, imaginary: 1) XCTAssertTrue(complex.isInfinite) complex = Complex(real: 1.0 / 0.0, imaginary: 1.0 / 0.0) XCTAssertTrue(complex.isInfinite) } func testIsNaN() { var complex = Complex<Float>(real: 999, imaginary: 0) XCTAssertFalse(complex.isNaN) complex = Complex(real: 0.0 * 1.0 / 0.0, imaginary: 1) XCTAssertTrue(complex.isNaN) complex = Complex(real: 0.0 * 1.0 / 0.0, imaginary: 0.0 * 1.0 / 0.0) XCTAssertTrue(complex.isNaN) } func testIsZero() { var complex = Complex<Float>(real: 999, imaginary: 0) XCTAssertFalse(complex.isZero) complex = Complex(real: 0.0 * 1.0 / 0.0, imaginary: 0) XCTAssertFalse(complex.isZero) complex = Complex(real: 0.0 * 1.0 / 0.0, imaginary: 0.0 * 1.0 / 0.0) XCTAssertFalse(complex.isZero) complex = Complex(real: 0, imaginary: 0) XCTAssertTrue(complex.isZero) } func testEquals() { var complexA = Complex<Float>(real: 999, imaginary: 0) let complexB = Complex<Float>(real: 999, imaginary: 0) XCTAssertEqual(complexA, complexB) complexA = Complex(real: 5, imaginary: 0) XCTAssertNotEqual(complexA, complexB) } func testPlus() { let input = Complex<Float>(real: 5, imaginary: 1) let expected = Complex<Float>(real: 10, imaginary: 2) XCTAssertEqual(expected, input + input) } func testMinus() { let inputA = Complex<Float>(real: 6, imaginary: 2) let inputB = Complex<Float>(real: 5, imaginary: 1) let expected = Complex<Float>(real: 1, imaginary: 1) XCTAssertEqual(expected, inputA - inputB) } func testTimes() { let inputA = Complex<Float>(real: 6, imaginary: 2) let inputB = Complex<Float>(real: 5, imaginary: 1) let expected = Complex<Float>(real: 28, imaginary: 16) XCTAssertEqual(expected, inputA * inputB) } func testNegate() { var input = Complex<Float>(real: 6, imaginary: 2) let negated = Complex<Float>(real: -6, imaginary: -2) XCTAssertEqual(-input, negated) input.negate() XCTAssertEqual(input, negated) } func testDivide() { let inputA = Complex<Float>(real: 20, imaginary: -4) let inputB = Complex<Float>(real: 3, imaginary: 2) let expected = Complex<Float>(real: 4, imaginary: -4) XCTAssertEqual(expected, inputA / inputB) } func testComplexConjugate() { var input = Complex<Float>(real: 2, imaginary: -4) var expected = Complex<Float>(real: 2, imaginary: 4) XCTAssertEqual(expected, input.complexConjugate()) input = Complex<Float>(real: -2, imaginary: -4) expected = Complex<Float>(real: -2, imaginary: 4) XCTAssertEqual(expected, input.complexConjugate()) input = Complex<Float>(real: 2, imaginary: 4) expected = Complex<Float>(real: 2, imaginary: -4) XCTAssertEqual(expected, input.complexConjugate()) } func testAdding() { var input = Complex<Float>(real: 2, imaginary: -4) var expected = Complex<Float>(real: 3, imaginary: -4) XCTAssertEqual(expected, input.adding(real: 1)) input = Complex<Float>(real: 2, imaginary: -4) expected = Complex<Float>(real: 2, imaginary: -3) XCTAssertEqual(expected, input.adding(imaginary: 1)) } func testSubtracting() { var input = Complex<Float>(real: 2, imaginary: -4) var expected = Complex<Float>(real: 1, imaginary: -4) XCTAssertEqual(expected, input.subtracting(real: 1)) input = Complex<Float>(real: 2, imaginary: -4) expected = Complex<Float>(real: 2, imaginary: -5) XCTAssertEqual(expected, input.subtracting(imaginary: 1)) } func testVjpInit() { var pb = pullback(at: 4, -3) { r, i in return Complex<Float>(real: r, imaginary: i) } var tanTuple = pb(Complex<Float>(real: -1, imaginary: 2)) XCTAssertEqual(-1, tanTuple.0) XCTAssertEqual(2, tanTuple.1) pb = pullback(at: 4, -3) { r, i in return Complex<Float>(real: r * r, imaginary: i + i) } tanTuple = pb(Complex<Float>(real: -1, imaginary: 1)) XCTAssertEqual(-8, tanTuple.0) XCTAssertEqual(2, tanTuple.1) } func testVjpAdd() { let pb: (Complex<Float>) -> Complex<Float> = pullback(at: Complex<Float>(real: 2, imaginary: 3)) { x in return x + Complex<Float>(real: 5, imaginary: 6) } XCTAssertEqual( pb(Complex(real: 1, imaginary: 1)), Complex<Float>(real: 1, imaginary: 1)) } func testVjpSubtract() { let pb: (Complex<Float>) -> Complex<Float> = pullback(at: Complex<Float>(real: 2, imaginary: 3)) { x in return Complex<Float>(real: 5, imaginary: 6) - x } XCTAssertEqual(pb(Complex(real: 1, imaginary: 1)), Complex<Float>(real: -1, imaginary: -1)) } func testVjpMultiply() { let pb: (Complex<Float>) -> Complex<Float> = pullback(at: Complex<Float>(real: 2, imaginary: 3)) { x in return x * x } XCTAssertEqual(pb(Complex(real: 1, imaginary: 0)), Complex<Float>(real: 4, imaginary: 6)) XCTAssertEqual(pb(Complex(real: 0, imaginary: 1)), Complex<Float>(real: -6, imaginary: 4)) XCTAssertEqual(pb(Complex(real: 1, imaginary: 1)), Complex<Float>(real: -2, imaginary: 10)) } func testVjpDivide() { let pb: (Complex<Float>) -> Complex<Float> = pullback(at: Complex<Float>(real: 20, imaginary: -4)) { x in return x / Complex<Float>(real: 2, imaginary: 2) } XCTAssertEqual( pb(Complex(real: 1, imaginary: 0)), Complex<Float>(real: 0.25, imaginary: -0.25)) XCTAssertEqual( pb(Complex(real: 0, imaginary: 1)), Complex<Float>(real: 0.25, imaginary: 0.25)) } func testVjpNegate() { let pb: (Complex<Float>) -> Complex<Float> = pullback(at: Complex<Float>(real: 20, imaginary: -4)) { x in return -x } XCTAssertEqual(pb(Complex(real: 1, imaginary: 0)), Complex<Float>(real: -1, imaginary: 0)) XCTAssertEqual(pb(Complex(real: 0, imaginary: 1)), Complex<Float>(real: 0, imaginary: -1)) XCTAssertEqual(pb(Complex(real: 1, imaginary: 1)), Complex<Float>(real: -1, imaginary: -1)) } func testVjpComplexConjugate() { let pb: (Complex<Float>) -> Complex<Float> = pullback(at: Complex<Float>(real: 20, imaginary: -4)) { x in return x.complexConjugate() } XCTAssertEqual(pb(Complex(real: 1, imaginary: 0)), Complex<Float>(real: 1, imaginary: 0)) XCTAssertEqual(pb(Complex(real: 0, imaginary: 1)), Complex<Float>(real: 0, imaginary: -1)) XCTAssertEqual(pb(Complex(real: -1, imaginary: 1)), Complex<Float>(real: -1, imaginary: -1)) } func testVjpAddingReal() { let pb: (Complex<Float>) -> Complex<Float> = pullback(at: Complex<Float>(real: 20, imaginary: -4)) { x in return x.adding(real: 5) } XCTAssertEqual(pb(Complex(real: 1, imaginary: 0)), Complex<Float>(real: 1, imaginary: 0)) XCTAssertEqual(pb(Complex(real: 0, imaginary: 1)), Complex<Float>(real: 0, imaginary: 1)) XCTAssertEqual(pb(Complex(real: 1, imaginary: 1)), Complex<Float>(real: 1, imaginary: 1)) } func testVjpAddingImaginary() { let pb: (Complex<Float>) -> Complex<Float> = pullback(at: Complex<Float>(real: 20, imaginary: -4)) { x in return x.adding(imaginary: 5) } XCTAssertEqual(pb(Complex(real: 1, imaginary: 0)), Complex<Float>(real: 1, imaginary: 0)) XCTAssertEqual(pb(Complex(real: 0, imaginary: 1)), Complex<Float>(real: 0, imaginary: 1)) XCTAssertEqual(pb(Complex(real: 1, imaginary: 1)), Complex<Float>(real: 1, imaginary: 1)) } func testVjpSubtractingReal() { let pb: (Complex<Float>) -> Complex<Float> = pullback(at: Complex<Float>(real: 20, imaginary: -4)) { x in return x.subtracting(real: 5) } XCTAssertEqual(pb(Complex(real: 1, imaginary: 0)), Complex<Float>(real: 1, imaginary: 0)) XCTAssertEqual(pb(Complex(real: 0, imaginary: 1)), Complex<Float>(real: 0, imaginary: 1)) XCTAssertEqual(pb(Complex(real: 1, imaginary: 1)), Complex<Float>(real: 1, imaginary: 1)) } func testVjpSubtractingImaginary() { let pb: (Complex<Float>) -> Complex<Float> = pullback(at: Complex<Float>(real: 20, imaginary: -4)) { x in return x.subtracting(imaginary: 5) } XCTAssertEqual(pb(Complex(real: 1, imaginary: 0)), Complex<Float>(real: 1, imaginary: 0)) XCTAssertEqual(pb(Complex(real: 0, imaginary: 1)), Complex<Float>(real: 0, imaginary: 1)) XCTAssertEqual(pb(Complex(real: 1, imaginary: 1)), Complex<Float>(real: 1, imaginary: 1)) } func testJvpDotProduct() { struct ComplexVector: Differentiable & AdditiveArithmetic { var w: Complex<Float> var x: Complex<Float> var y: Complex<Float> var z: Complex<Float> init(w: Complex<Float>, x: Complex<Float>, y: Complex<Float>, z: Complex<Float>) { self.w = w self.x = x self.y = y self.z = z } } func dot(lhs: ComplexVector, rhs: ComplexVector) -> Complex<Float> { var result: Complex<Float> = Complex(real: 0, imaginary: 0) result = result + lhs.w.complexConjugate() * rhs.w result = result + lhs.x.complexConjugate() * rhs.x result = result + lhs.y.complexConjugate() * rhs.y result = result + lhs.z.complexConjugate() * rhs.z return result } let atVector = ComplexVector( w: Complex(real: 1, imaginary: 1), x: Complex(real: 1, imaginary: -1), y: Complex(real: -1, imaginary: 1), z: Complex(real: -1, imaginary: -1)) let rhsVector = ComplexVector( w: Complex(real: 3, imaginary: -4), x: Complex(real: 6, imaginary: -2), y: Complex(real: 1, imaginary: 2), z: Complex(real: 4, imaginary: 3)) let expectedVector = ComplexVector( w: Complex(real: 7, imaginary: 1), x: Complex(real: 8, imaginary: -4), y: Complex(real: -1, imaginary: -3), z: Complex(real: 1, imaginary: -7)) let (result, pbComplex) = valueWithPullback(at: atVector) { x in return dot(lhs: x, rhs: rhsVector) } XCTAssertEqual(Complex(real: 1, imaginary: -5), result) XCTAssertEqual(expectedVector, pbComplex(Complex(real: 1, imaginary: 1))) } func testImplicitDifferentiation() { func addRealComponents(lhs: Complex<Float>, rhs: Complex<Float>) -> Float { return lhs.real + rhs.real } let (result, pbComplex) = valueWithPullback(at: Complex(real: 2, imaginary: -3)) { x in return addRealComponents(lhs: x, rhs: Complex(real: -4, imaginary: 1)) } XCTAssertEqual(-2, result) XCTAssertEqual(Complex(real: 1, imaginary: 0), pbComplex(1)) } static var allTests = [ ("testInitializer", testInitializer), ("testStaticImaginary", testStaticImaginary), ("testIsFinite", testIsFinite), ("testIsInfinite", testIsInfinite), ("testIsNaN", testIsNaN), ("testIsZero", testIsZero), ("testEquals", testEquals), ("testPlus", testPlus), ("testMinus", testMinus), ("testTimes", testTimes), ("testNegate", testNegate), ("testDivide", testDivide), ("testComplexConjugate", testComplexConjugate), ("testAdding", testAdding), ("testSubtracting", testSubtracting), ("testVjpInit", testVjpInit), ("testVjpAdd", testVjpAdd), ("testVjpSubtract", testVjpSubtract), ("testVjpMultiply", testVjpMultiply), ("testVjpDivide", testVjpDivide), ("testVjpNegate", testVjpNegate), ("testVjpComplexConjugate", testVjpComplexConjugate), ("testVjpAddingReal", testVjpAddingReal), ("testVjpAddingImaginary", testVjpAddingImaginary), ("testVjpSubtractingReal", testVjpSubtractingReal), ("testVjpSubtractingImaginary", testVjpSubtractingImaginary), ("testJvpDotProduct", testJvpDotProduct), ("testImplicitDifferentiation", testImplicitDifferentiation), ] }
apache-2.0
b26a780da150ea74efd235729f761b48
35.186301
96
0.652786
3.564912
false
true
false
false
minhkiller/iBurn-iOS
iBurn/BRCEventsViewController.swift
2
1796
// // BRCEventsViewController.swift // iBurn // // Created by Christopher Ballinger on 8/18/15. // Copyright (c) 2015 Burning Man Earth. All rights reserved. // import UIKit /** This is for showing a list of events hosted by camp/art */ class BRCEventsViewController: BRCSortedViewController { var relatedObject: BRCDataObject? /** You'll want to pass in the YapDatabaseRelationship extensionName. RelatedObject should be a BRCCampObject or BRCArtObject for event lookup. */ init(style: UITableViewStyle, extensionName ext: String, relatedObject obj: BRCDataObject) { relatedObject = obj super.init(style: style, extensionName: ext) emptyDetailText = "Looks like there's no listed events." } required init!(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } required init(style: UITableViewStyle, extensionName ext: String) { super.init(style: style, extensionName: ext) } internal override func refreshTableItems(completion: dispatch_block_t) { var eventObjects: [BRCEventObject] = [] BRCDatabaseManager.sharedInstance().readConnection.readWithBlock { (transaction: YapDatabaseReadTransaction) -> Void in if let object = self.relatedObject { eventObjects = object.eventsWithTransaction(transaction) as! [BRCEventObject] } } let options = BRCDataSorterOptions() options.showFutureEvents = true options.showExpiredEvents = true BRCDataSorter.sortDataObjects(eventObjects, options: options, completionQueue: dispatch_get_main_queue(), callbackBlock: { (events, art, camps) -> (Void) in self.processSortedData(events, art: art, camps: camps, completion: completion) }) } }
mpl-2.0
1d1c1891e82261e208397188f1f5746b
38.911111
164
0.690423
4.512563
false
false
false
false
DivineDominion/mac-appdev-code
CoreDataOnly/AppDelegate.swift
1
5977
import Cocoa let kErrorDomain = "DDDViewDataExampleErrorDomain" @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var notificationCenter: NotificationCenter { return NotificationCenter.default } lazy var persistentStack: PersistentStack = { let storeURL = self.applicationDocumentsDirectory.appendingPathComponent("ItemModel.sqlite") let modelURL = Bundle.main.url(forResource: kDefaultModelName, withExtension: "momd") let persistentStack = PersistentStack(storeURL: storeURL, modelURL: modelURL!) self.notificationCenter.addObserver(persistentStack, selector: #selector(PersistentStack.objectContextWillSave), name: Notification.Name.NSManagedObjectContextWillSave, object: persistentStack.managedObjectContext) return persistentStack }() lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "de.christiantietze.DDDViewDataExample" in the user's Application Support directory. let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask) let appSupportURL = urls[urls.count - 1] as URL let directory = appSupportURL.appendingPathComponent("de.christiantietze.DDDViewDataExample") self.guardApplicationDocumentsDirectory(directory) return directory }() fileprivate func guardApplicationDocumentsDirectory(_ directory: URL) { do { if try !directoryExists(directory) { try createDirectory(directory) } } catch let error as NSError { NSApplication.shared().presentError(error) abort() } } fileprivate func directoryExists(_ directory: URL) throws -> Bool { let propertiesOpt: [AnyHashable: Any] do { propertiesOpt = try (directory as NSURL).resourceValues(forKeys: [URLResourceKey.isDirectoryKey]) } catch let error as NSError { if error.code == NSFileReadNoSuchFileError { return false } throw error } if let isDirectory = propertiesOpt[URLResourceKey.isDirectoryKey] as? Bool, isDirectory == false { var userInfo = [AnyHashable: Any]() userInfo[NSLocalizedDescriptionKey] = "Failed to initialize the persistent stack" userInfo[NSLocalizedFailureReasonErrorKey] = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)." throw NSError(domain: kErrorDomain, code: 1, userInfo: userInfo) } return true } fileprivate func createDirectory(_ directory: URL) throws { let fileManager = FileManager.default do { try fileManager.createDirectory(atPath: directory.path, withIntermediateDirectories: true, attributes: nil) } catch let fileError as NSError { var userInfo = [AnyHashable: Any]() userInfo[NSLocalizedDescriptionKey] = "Failed to create the application documents directory" userInfo[NSLocalizedFailureReasonErrorKey] = "Creation of \(directory.path) failed." userInfo[NSUnderlyingErrorKey] = fileError throw NSError(domain: kErrorDomain, code: 1, userInfo: userInfo) } } //MARK: - //MARK: NSAppDelegate callbacks lazy var manageBoxesAndItems: ManageBoxesAndItems! = ManageBoxesAndItems() var readErrorCallback: NSObjectProtocol? func applicationDidFinishLaunching(_ aNotification: Notification) { subscribeToCoreDataReadErrors() ServiceLocator.sharedInstance.setManagedObjectContext(persistentStack.managedObjectContext!) manageBoxesAndItems.showBoxManagementWindow() } func subscribeToCoreDataReadErrors() { readErrorCallback = notificationCenter.addObserver(forName: NSNotification.Name(rawValue: kCoreDataReadErrorNotificationName), object: nil, queue: OperationQueue.main) { notification in let question = NSLocalizedString("Could not read data. Report and Quit?", comment: "Read error quit question message") let info = NSLocalizedString("The application cannot read data and thus better not continues to operate. Changes will be saved if possible.", comment: "Read error quit question info") let quitButton = NSLocalizedString("Report and Quit", comment: "Report and Quit button title") let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title") let alert = NSAlert() alert.messageText = question alert.informativeText = info alert.addButton(withTitle: quitButton) alert.addButton(withTitle: cancelButton) let answer = alert.runModal() if answer == NSAlertFirstButtonReturn { //TODO: Add error reporting here return NSApplication.shared().terminate(self) } } } func applicationShouldTerminate(_ sender: NSApplication) -> NSApplicationTerminateReply { return persistentStack.saveToTerminate(sender) } func applicationWillTerminate(_ aNotification: Notification) { if readErrorCallback != nil { notificationCenter.removeObserver(readErrorCallback!) } notificationCenter.removeObserver(persistentStack, name: NSNotification.Name.NSManagedObjectContextWillSave, object: persistentStack.managedObjectContext) } func windowWillReturnUndoManager(_ window: NSWindow) -> UndoManager? { return persistentStack.undoManager() } }
mit
3c10701c9d3489d11649faf1fbd65ecf
41.390071
222
0.664882
6.019134
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/SnapKit/Source/Constraint.swift
17
13691
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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) || os(tvOS) import UIKit #else import AppKit #endif public final class Constraint { internal let sourceLocation: (String, UInt) internal let label: String? private let from: ConstraintItem private let to: ConstraintItem private let relation: ConstraintRelation private let multiplier: ConstraintMultiplierTarget private var constant: ConstraintConstantTarget { didSet { self.updateConstantAndPriorityIfNeeded() } } private var priority: ConstraintPriorityTarget { didSet { self.updateConstantAndPriorityIfNeeded() } } public var layoutConstraints: [LayoutConstraint] public var isActive: Bool { set { if newValue { activate() } else { deactivate() } } get { for layoutConstraint in self.layoutConstraints { if layoutConstraint.isActive { return true } } return false } } // MARK: Initialization internal init(from: ConstraintItem, to: ConstraintItem, relation: ConstraintRelation, sourceLocation: (String, UInt), label: String?, multiplier: ConstraintMultiplierTarget, constant: ConstraintConstantTarget, priority: ConstraintPriorityTarget) { self.from = from self.to = to self.relation = relation self.sourceLocation = sourceLocation self.label = label self.multiplier = multiplier self.constant = constant self.priority = priority self.layoutConstraints = [] // get attributes let layoutFromAttributes = self.from.attributes.layoutAttributes let layoutToAttributes = self.to.attributes.layoutAttributes // get layout from let layoutFrom = self.from.layoutConstraintItem! // get relation let layoutRelation = self.relation.layoutRelation for layoutFromAttribute in layoutFromAttributes { // get layout to attribute let layoutToAttribute: LayoutAttribute #if os(iOS) || os(tvOS) if layoutToAttributes.count > 0 { if self.from.attributes == .edges && self.to.attributes == .margins { switch layoutFromAttribute { case .left: layoutToAttribute = .leftMargin case .right: layoutToAttribute = .rightMargin case .top: layoutToAttribute = .topMargin case .bottom: layoutToAttribute = .bottomMargin default: fatalError() } } else if self.from.attributes == .margins && self.to.attributes == .edges { switch layoutFromAttribute { case .leftMargin: layoutToAttribute = .left case .rightMargin: layoutToAttribute = .right case .topMargin: layoutToAttribute = .top case .bottomMargin: layoutToAttribute = .bottom default: fatalError() } } else if self.from.attributes == .directionalEdges && self.to.attributes == .directionalMargins { switch layoutFromAttribute { case .leading: layoutToAttribute = .leadingMargin case .trailing: layoutToAttribute = .trailingMargin case .top: layoutToAttribute = .topMargin case .bottom: layoutToAttribute = .bottomMargin default: fatalError() } } else if self.from.attributes == .directionalMargins && self.to.attributes == .directionalEdges { switch layoutFromAttribute { case .leadingMargin: layoutToAttribute = .leading case .trailingMargin: layoutToAttribute = .trailing case .topMargin: layoutToAttribute = .top case .bottomMargin: layoutToAttribute = .bottom default: fatalError() } } else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else { layoutToAttribute = layoutToAttributes[0] } } else { if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) { layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top } else { layoutToAttribute = layoutFromAttribute } } #else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else if layoutToAttributes.count > 0 { layoutToAttribute = layoutToAttributes[0] } else { layoutToAttribute = layoutFromAttribute } #endif // get layout constant let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute) // get layout to var layoutTo: AnyObject? = self.to.target // use superview if possible if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height { layoutTo = layoutFrom.superview } // create layout constraint let layoutConstraint = LayoutConstraint( item: layoutFrom, attribute: layoutFromAttribute, relatedBy: layoutRelation, toItem: layoutTo, attribute: layoutToAttribute, multiplier: self.multiplier.constraintMultiplierTargetValue, constant: layoutConstant ) // set label layoutConstraint.label = self.label // set priority layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) // set constraint layoutConstraint.constraint = self // append self.layoutConstraints.append(layoutConstraint) } } // MARK: Public @available(*, deprecated, message:"Use activate().") public func install() { self.activate() } @available(*, deprecated, message:"Use deactivate().") public func uninstall() { self.deactivate() } public func activate() { self.activateIfNeeded() } public func deactivate() { self.deactivateIfNeeded() } @discardableResult public func update(offset: ConstraintOffsetTarget) -> Constraint { self.constant = offset.constraintOffsetTargetValue return self } @discardableResult public func update(inset: ConstraintInsetTarget) -> Constraint { self.constant = inset.constraintInsetTargetValue return self } #if os(iOS) || os(tvOS) @discardableResult @available(iOS 11.0, tvOS 11.0, *) public func update(inset: ConstraintDirectionalInsetTarget) -> Constraint { self.constant = inset.constraintDirectionalInsetTargetValue return self } #endif @discardableResult public func update(priority: ConstraintPriorityTarget) -> Constraint { self.priority = priority.constraintPriorityTargetValue return self } @discardableResult public func update(priority: ConstraintPriority) -> Constraint { self.priority = priority.value return self } @available(*, deprecated, message:"Use update(offset: ConstraintOffsetTarget) instead.") public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) } @available(*, deprecated, message:"Use update(inset: ConstraintInsetTarget) instead.") public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) } @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) } @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityRequired() -> Void {} @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") } @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") } @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") } // MARK: Internal internal func updateConstantAndPriorityIfNeeded() { for layoutConstraint in self.layoutConstraints { let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute) let requiredPriority = ConstraintPriority.required.value if (layoutConstraint.priority.rawValue < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) { layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) } } } internal func activateIfNeeded(updatingExisting: Bool = false) { guard let item = self.from.layoutConstraintItem else { print("WARNING: SnapKit failed to get from item from constraint. Activate will be a no-op.") return } let layoutConstraints = self.layoutConstraints if updatingExisting { var existingLayoutConstraints: [LayoutConstraint] = [] for constraint in item.constraints { existingLayoutConstraints += constraint.layoutConstraints } for layoutConstraint in layoutConstraints { let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint } guard let updateLayoutConstraint = existingLayoutConstraint else { fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)") } let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute) } } else { NSLayoutConstraint.activate(layoutConstraints) item.add(constraints: [self]) } } internal func deactivateIfNeeded() { guard let item = self.from.layoutConstraintItem else { print("WARNING: SnapKit failed to get from item from constraint. Deactivate will be a no-op.") return } let layoutConstraints = self.layoutConstraints NSLayoutConstraint.deactivate(layoutConstraints) item.remove(constraints: [self]) } }
mit
6c2c842eaffda09f5c66c4ee701ad406
39.14956
184
0.595939
6.206256
false
false
false
false
TouchInstinct/LeadKit
TINetworking/Sources/Interceptors/DefaultTokenInterceptor.swift
1
5233
// // Copyright (c) 2022 Touch Instinct // // 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 Alamofire import Foundation import TIFoundationUtils open class DefaultTokenInterceptor<RefreshError: Error>: RequestInterceptor { public typealias ShouldRefreshTokenClosure = (URLRequest?, HTTPURLResponse?, Error?) -> Bool public typealias RefreshTokenClosure = (@escaping (RefreshError?) -> Void) -> Cancellable public typealias RequestModificationClosure = (URLRequest) -> URLRequest let processingQueue = OperationQueue() let shouldRefreshToken: ShouldRefreshTokenClosure let refreshTokenClosure: RefreshTokenClosure public var defaultRetryStrategy: RetryResult = .doNotRetry public var requestModificationClosure: RequestModificationClosure? public init(shouldRefreshTokenClosure: @escaping ShouldRefreshTokenClosure, refreshTokenClosure: @escaping RefreshTokenClosure, requestModificationClosure: RequestModificationClosure? = nil) { self.shouldRefreshToken = shouldRefreshTokenClosure self.refreshTokenClosure = refreshTokenClosure self.requestModificationClosure = requestModificationClosure processingQueue.maxConcurrentOperationCount = 1 } // MARK: - RequestAdapter open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) { let adaptBag = BaseCancellableBag() let adaptCompletion: (Result<URLRequest, RefreshError>) -> Void = { adaptBag.cancellables.removeAll() completion($0.mapError { $0 as Error }) } let modifiedRequest = requestModificationClosure?(urlRequest) ?? urlRequest validateAndRepair(validationClosure: { self.shouldRefreshToken(urlRequest, nil, nil) }, completion: adaptCompletion, defaultCompletionResult: modifiedRequest, recoveredCompletionResult: modifiedRequest) .add(to: adaptBag) } // MARK: - RequestRetrier open func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { let retryBag = BaseCancellableBag() let retryCompletion: (Result<RetryResult, RefreshError>) -> Void = { retryBag.cancellables.removeAll() switch $0 { case let .success(retryResult): completion(retryResult) case let .failure(refreshError): completion(.doNotRetryWithError(refreshError)) } } validateAndRepair(validationClosure: { self.shouldRefreshToken(request.request, request.response, error) }, completion: retryCompletion, defaultCompletionResult: defaultRetryStrategy, recoveredCompletionResult: .retry) .add(to: retryBag) } open func validateAndRepair<T>(validationClosure: @escaping () -> Bool, completion: @escaping (Result<T, RefreshError>) -> Void, defaultCompletionResult: T, recoveredCompletionResult: T) -> Cancellable { let operation = ClosureAsyncOperation<T, RefreshError>(cancellableTaskClosure: { [refreshTokenClosure] operationCompletion in if validationClosure() { return refreshTokenClosure { if let error = $0 { operationCompletion(.failure(error)) } else { operationCompletion(.success(recoveredCompletionResult)) } } } else { operationCompletion(.success(defaultCompletionResult)) return Cancellables.nonCancellable() } }) .observe(onResult: completion, callbackQueue: .global()) operation.add(to: processingQueue) return operation } }
apache-2.0
7a029c889c4b7513ac79910a48bc9f5a
40.204724
133
0.646283
5.543432
false
false
false
false
jamy0801/LGWeChatKit
LGWeChatKit/LGChatKit/conversion/imagePick/LGAssertGridViewCell.swift
1
3953
// // LGAssertGridViewCell.swift // LGChatViewController // // Created by jamy on 10/22/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit class LGAssertGridViewCell: UICollectionViewCell { let buttonWidth: CGFloat = 30 var assetIdentifier: String! var imageView:UIImageView! var playIndicator: UIImageView? var selectIndicator: UIButton var assetModel: LGAssetModel! { didSet { if assetModel.asset.mediaType == .Video { self.playIndicator?.hidden = false } else { self.playIndicator?.hidden = true } } } var buttonSelect: Bool { willSet { if newValue { selectIndicator.selected = true selectIndicator.setImage(UIImage(named: "CellBlueSelected"), forState: .Normal) } else { selectIndicator.selected = false selectIndicator.setImage(UIImage(named: "CellGreySelected"), forState: .Normal) } } } override init(frame: CGRect) { selectIndicator = UIButton(type: .Custom) selectIndicator.tag = 1 buttonSelect = false super.init(frame: frame) imageView = UIImageView(frame: bounds) //imageView.contentMode = .ScaleAspectFit contentView.addSubview(imageView) playIndicator = UIImageView(frame: CGRectMake(0, 0, 60, 60)) playIndicator?.center = contentView.center playIndicator?.image = UIImage(named: "mmplayer_idle") contentView.addSubview(playIndicator!) playIndicator?.hidden = true selectIndicator.frame = CGRectMake(bounds.width - buttonWidth , 0, buttonWidth, buttonWidth) contentView.addSubview(selectIndicator) selectIndicator.setImage(UIImage(named: "CellGreySelected"), forState: .Normal) backgroundColor = UIColor.whiteColor() imageView.translatesAutoresizingMaskIntoConstraints = false contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: 0)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let durationTime = 0.3 func selectButton(button: UIButton) { if button.tag == 1 { button.tag = 0 let groupAnimation = CAAnimationGroup() let animationZoomOut = CABasicAnimation(keyPath: "transform.scale") animationZoomOut.fromValue = 0 animationZoomOut.toValue = 1.2 animationZoomOut.duration = 3/4 * durationTime let animationZoomIn = CABasicAnimation(keyPath: "transform.scale") animationZoomIn.fromValue = 1.2 animationZoomIn.toValue = 1.0 animationZoomIn.beginTime = 3/4 * durationTime animationZoomIn.duration = 1/4 * durationTime groupAnimation.animations = [animationZoomOut, animationZoomIn] buttonSelect = true assetModel.select = true selectIndicator.layer.addAnimation(groupAnimation, forKey: "selectZoom") } else { button.tag = 1 buttonSelect = false assetModel.select = false } } }
mit
c57e9e7dbd2bf2257006cd96a947a96f
38.128713
178
0.635121
5.053708
false
false
false
false
RLovelett/langserver-swift
Tests/LanguageServerProtocolTests/Types/CompletionItemTests.swift
1
2755
// // CompletionItemTests.swift // langserver-swift // // Created by Ryan Lovelett on 12/2/16. // // import Argo import Foundation @testable import LanguageServerProtocol import Runes import XCTest class CompletionItemTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testParseCompletionItems() { let json = loadJSONFromFixture("complete.json", in: "JSON/code-completion") let foo: Decoded<[CompletionItem]> = json["key.results"] switch foo { case .success(let bar): XCTAssertEqual(bar.count, 345) case .failure(let e): XCTFail(e.localizedDescription) } } func testKeywordCompletionItem() { let json = loadJSONFromFixture("import.json", in: "JSON/code-completion") let foo = CompletionItem.decode(json) switch foo { case .success(let item): XCTAssertEqual(item.kind, CompletionItemKind.Keyword) XCTAssertEqual(item.label, "import") XCTAssertEqual(item.detail, "import") XCTAssertNil(item.documentation) case .failure(let e): XCTFail(e.description) } } func testProtocolCompletionItem() { let json = loadJSONFromFixture("integer.json", in: "JSON/code-completion") let foo = CompletionItem.decode(json) switch foo { case .success(let item): XCTAssertEqual(item.kind, CompletionItemKind.Interface) XCTAssertEqual(item.label, "Integer") XCTAssertEqual(item.detail, "Integer") XCTAssertEqual(item.documentation, "A set of common requirements for Swift’s integer types.") case .failure(let e): XCTFail(e.description) } } func testConstructorCompletionItem() { let json = loadJSONFromFixture("constructor.json", in: "JSON/code-completion") let foo = CompletionItem.decode(json) switch foo { case .success(let item): XCTAssertEqual(item.kind, CompletionItemKind.Constructor) XCTAssertEqual(item.label, "(x: Int, y: String)") XCTAssertEqual(item.detail, "Test.Bar (x: Int, y: String)") XCTAssertEqual(item.insertText, "x: ${1:Int}, y: ${2:String})") XCTAssertEqual(item.insertTextFormat, .snippet) XCTAssertNil(item.documentation) case .failure(let e): XCTFail(e.description) } } }
apache-2.0
26812f054db377342442cd9c58cb14cb
32.168675
111
0.626589
4.454693
false
true
false
false
pandazheng/Vu
唯舞/唯舞/LikedViewController.swift
2
7306
// // LikedViewController.swift // 唯舞 // // Created by Eular on 8/26/15. // Copyright © 2015 eular. All rights reserved. // import UIKit import CoreData class LikedViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { @IBOutlet weak var likedVideoTableView: UITableView! @IBOutlet weak var likedSearchBar: UISearchBar! @IBOutlet weak var textLabel: UILabel! let likedVideoCellIdentifier = "likedVideoCell" var likedVideoList = [NSManagedObject]() var curVideo: VideoModel? var nickname: String! var headimgurl: String! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. likedVideoTableView.dataSource = self likedVideoTableView.delegate = self likedSearchBar.delegate = self let info = NSUserDefaults.standardUserDefaults().objectForKey("userInfo")! nickname = info["nickname"] as! String headimgurl = info["headimgurl"] as! String if let result = fetchResultInCoreData("LikedVideo") { likedVideoList = result } if likedVideoList.count == 0 { likedVideoTableView.hidden = true textLabel.hidden = false } else { likedVideoTableView.hidden = false textLabel.hidden = true } // Hide searchBar var contentOffset = likedVideoTableView.contentOffset contentOffset.y += likedSearchBar.frame.size.height likedVideoTableView.contentOffset = contentOffset changeCancelButtonTitle("编辑") } // Change the title of cancel button in searchBar func changeCancelButtonTitle(title: String) { for subView in likedSearchBar.subviews[0].subviews { if subView.isKindOfClass(NSClassFromString("UINavigationButton")!) { let cancelButton = subView as! UIButton cancelButton.setTitle(title, forState: UIControlState.Normal) } } } func getTimeString(timestamp: String) -> String { let ago = NSDate(timeIntervalSince1970: NSTimeInterval(timestamp)!) let now = NSDate() let dt = NSDate(timeIntervalSince1970: NSTimeInterval(String(now.timeIntervalSince1970 - ago.timeIntervalSince1970))!) let formatter = NSDateFormatter() formatter.dateFormat = "dd" formatter.timeZone = NSTimeZone(abbreviation: "UTC") let day = Int(formatter.stringFromDate(dt))! if day == 1 { return "今天" } else if day <= 31 { return "\(day - 1)天前" } else { formatter.dateFormat = "yyyy-MM-dd" return formatter.stringFromDate(dt) } } func fetchResultInCoreData(entityName: String) -> [NSManagedObject]? { // 1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext // 2 let fetchRequest = NSFetchRequest(entityName: entityName) // 3 do { let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject] return fetchedResults?.reverse() } catch {} return nil } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return likedVideoList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(likedVideoCellIdentifier, forIndexPath: indexPath) let row = indexPath.row let video = likedVideoList[row] let title = video.valueForKey("title") as! String let thumbnail = video.valueForKey("thumbnail") as! String let timestamp = video.valueForKey("timestamp") as! String let headUI = cell.viewWithTag(1) as! UIImageView let thumbnailUI = cell.viewWithTag(2) as! UIImageView let nameUI = cell.viewWithTag(3) as! UILabel let titleUI = cell.viewWithTag(4) as! UILabel let timeUI = cell.viewWithTag(5) as! UILabel headUI.imageFromUrl(headimgurl) thumbnailUI.imageFromUrl(thumbnail) nameUI.text = nickname titleUI.text = title timeUI.text = getTimeString(timestamp) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let video = likedVideoList[indexPath.row] let title = video.valueForKey("title") as! String let thumbnail = video.valueForKey("thumbnail") as! String let src = video.valueForKey("src") as! String curVideo = VideoModel(title: title, src: src, thumbnail: thumbnail, views: "-", comments: "-", time: "") self.performSegueWithIdentifier("jumpToVideo", sender: self) } // Edit func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } // Delete func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let row = indexPath.row let video = likedVideoList[row] let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext managedContext.deleteObject(video) do { try managedContext.save() } catch { print("Error: Delete failed") } likedVideoList.removeAtIndex(row) likedVideoTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } // Drag & Move func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { let video = likedVideoList.removeAtIndex(sourceIndexPath.row) likedVideoList.insert(video, atIndex: destinationIndexPath.row) } // Edit Mode override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: true) likedVideoTableView.setEditing(editing, animated: true) } func searchBarCancelButtonClicked(searchBar: UISearchBar) { if editing { changeCancelButtonTitle("编辑") } else { changeCancelButtonTitle("完成") } editing = !editing } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let vc = segue.destinationViewController as! VideoViewController vc.curVideo = curVideo } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
279002475e9720a72b43fba91fc4e5ed
35.772727
148
0.64373
5.405345
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Views/CreateAccountFooterView.swift
1
1636
// // CreateAccountFooterView.swift // breadwallet // // Created by Adrian Corscadden on 2020-03-19. // Copyright © 2020 Breadwinner AG. All rights reserved. // // See the LICENSE file at the project root for license information. // import UIKit class CreateAccountFooterView: UIView { private let currency: Currency private var hasSetup = false private let button = UIButton.rounded(title: "Create Account") var didTapCreate: (() -> Void)? { didSet { button.tap = didTapCreate } } init(currency: Currency) { self.currency = currency super.init(frame: .zero) } override func layoutSubviews() { super.layoutSubviews() guard !hasSetup else { return } setup() hasSetup = true } private func setup() { addViews() addConstraints() setInitialData() } private func addViews() { button.tintColor = .white button.backgroundColor = .transparentWhite addSubview(button) } private func addConstraints() { button.constrain([ button.topAnchor.constraint(equalTo: topAnchor, constant: C.padding[1]), button.centerXAnchor.constraint(equalTo: centerXAnchor), button.heightAnchor.constraint(equalToConstant: 44.0), button.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.66)]) } private func setInitialData() { backgroundColor = currency.colors.1 } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
64a2b1a2966dad4e11762aa75dd22592
25.370968
84
0.622018
4.780702
false
false
false
false
CPRTeam/CCIP-iOS
Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift
3
1917
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // Electronic codebook (ECB) // public struct ECB: BlockMode { public let options: BlockModeOption = .paddingRequired public init() { } public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { ECBModeWorker(blockSize: blockSize, cipherOperation: cipherOperation) } } struct ECBModeWorker: BlockModeWorker { typealias Element = Array<UInt8> let cipherOperation: CipherOperationOnBlock let blockSize: Int let additionalBufferSize: Int = 0 init(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) { self.blockSize = blockSize self.cipherOperation = cipherOperation } mutating func encrypt(block plaintext: ArraySlice<UInt8>) -> Array<UInt8> { guard let ciphertext = cipherOperation(plaintext) else { return Array(plaintext) } return ciphertext } mutating func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> { self.encrypt(block: ciphertext) } }
gpl-3.0
2b4467b0e235580c2d641bb3986caf8e
36.568627
217
0.753132
4.572792
false
false
false
false
diniska/StaticWebsiteGenerator
Sources/StaticWebsiteGenerator/Server/LocalizedServerBuilder.swift
1
1792
// // LocalizedServerBuilder.swift // StaticWebsiteGenerator // // Created by Denis Chaschin on 19.03.16. // Copyright © 2016 diniska. All rights reserved. // import Foundation extension SimpleServerBuilder { public typealias LocalizedResponseGenerator = (Localization) throws -> String public func byAppendingRequest(_ request: LocalizedRequest, withResponse response: @escaping LocalizedResponseGenerator) -> SimpleServerBuilder { byAppendingRequest(request, withResponse: createResponse(request, response: response)) } public mutating func appendRequest(_ request: LocalizedRequest, withResponse response: @escaping LocalizedResponseGenerator) { appendRequest(request, withResponse: createResponse(request, response: response)) } mutating func appendRequests<Sequence: Swift.Sequence>(_ requests: Sequence, withResponse response: @escaping LocalizedResponseGenerator) where Sequence.Iterator.Element == LocalizedRequest { requests.map { (request) -> (LocalizedRequest, Response) in let wrapper = createResponse(request, response: response) return (request, wrapper) }.forEach { appendRequest($0.0, withResponse: $0.1) } } public func byAppendingRequests<Sequence: Swift.Sequence>(_ requests: Sequence, withResponse response: @escaping LocalizedResponseGenerator) -> SimpleServerBuilder where Sequence.Iterator.Element == LocalizedRequest { var res = self res.appendRequests(requests, withResponse: response) return res } } private func createResponse(_ request: LocalizedRequest, response: @escaping SimpleServerBuilder.LocalizedResponseGenerator) -> Response { return GeneratedStringResponse { try response(request.localization) } }
mit
43624b8f35401f6ec9ce0b8cfe2d676f
42.682927
221
0.74316
4.906849
false
false
false
false
Azero123/JW-Broadcasting
JW Broadcasting/ResourceHandling.swift
1
40556
// // ResourceHandling.swift // JW Broadcasting // // Created by Austin Zelenka on 11/15/15. // Copyright © 2015 xquared. All rights reserved. // /* MAIN POINT We need this code for hands on control of our caching system because we have to update multiple places from the same file download. DETAIL The goal of this code is to create a data fetching system that notifies ALL locations of the app when a file is retrieved. Secondly the goal of this is to be able to EVENTUALLY change a single property for language and have the app update itself when not under heavy load or preoccupied like playing a video or large animations. METHODS There are 2 major finished downloading methods: func fetchDataUsingCache(...) (Relatively completed.) func addBranchListener(...)/func checkBranchesFor(...) (not finished.) func fetchDataUsingCache(...) Is a 1 time return event. The next time we have a usable file with the url in fileURL:Sring a response is sent to the downloaded() closure (block for Objective-C users). This can optionally have a variable of usingCache:Bool. If usingCache==true then downloaded() can be run immediately if there is a cached version of this file either in ram memory or in file system/drive space. If this file is not cached or usingCache==false then a request for the file is made and downloaded() is fired on completion. ALSO checkBranchesFor(...) is fired to update branches. (See next paragraph) func addBranchListener(...) Any time instruction:String is changed/updated (see folding) the serverBonded() closure is triggered (block for Objective-C users) allowing the content to be updated. NOTE This code is not yet finished but should ultimately replace MOST fetchDataUsingCache(...) calls. -Why: The point of branches are to have events and properties/variables that are set on a file update or replacement. Instead of using tons of variables all the content can be updated at 1 time even in collection views that can be sporadic. THIS WOULD BE CALLED MANY TIMES. Thus branches would need to be able to be run multiple times in a row without causing crashes or visual errors. WARNING Keep code inside branches very clean and repeatable. Branches can be called at ANYTIME even when backgrounded. -reference: Branches use the text folding format see below. func checkBranchesFor(...) This updates all branches within and including the fold updatedInstruction:String. (see folding) NOTE 1. Likely should not be used outside of this file when finished. 2. Right now any subfold of updatedInstruction:String top fold will be called. This will be corrected to be only folds that have changed. (see folding) func unfold(...) -> AnyObject? This method uses the folding format to parse through JSON/Dictionary files/objects to prevent code repetition and incorrect handling of items. This means you only need to check the item of use and assign it a dynamicType instead of all its hierarchy elements. This method is inline so to speed it up and not process the same files repeatedly, which could have a 0.3~ second delay or more, this method stores processed files for later reuse. Stored dictionaries are in cachedBond:Dictionary<String,AnyObject?>. WARNING This method DOES NOT request new content, it is intended to be used AFTER a fetchDataUsingCache(...) or a branch update to confirm that this file has indeed in memory cache. FOLDING (When finished) This is a string that represents a specific item that can be contained within arrays, dictionaries, NSObjects, URLs, etc. Currently the top item in a fold can only be a file, url, or the item can be a dead-end string exp: "language". The unfold(...) methods parse each sub fold by the character "|" however this may be changed or completely removed up to not be a string at all. NOTE This is not a finished model -Why: There are a lot of JSON files with a lot of vary similar paths or urls with content that is sometimes only updated by one string or added object. Using this system everything is easier to manage, with far less variables and dynamic type handling which is annoying in swift. Lastly the code is a lot safer because unfold(...) can return nil and handle it very well. func dataUsingCache(...) This method uses the caching system to or does an inline request for data so this is intended to be used AFTER a fetchDataUsingCache(...) or a branch update to confirm that this file has indeed been downloaded. However this method will request the remote file if needed. Extension methods func imageUsingCache(...) -> UIImage? Uses the result of dataUsingCache(...) to return a UIImage. func dictionaryOfPath(path: String) -> NSDictionary? Uses the result of dataUsingCache(...) to return a NSDictionary. */ import Foundation import UIKit var cachedFiles:Dictionary<String,NSData>=[:] // All files that have been accessed since app launch var cachedBond:Dictionary<String,AnyObject?>=[:] // All JSON (and later also plist) files after being processed some files have a 0.3~ second interpretation time. var branchListeners:Dictionary<String, Array< () -> Any >>=[:] // All branches (see addBranchListener(...)/checkBranchesFor(...) var fileDownloadedClosures:Dictionary<String, Array< () -> Any >>=[:] // Events to be called by fetchDataUsingCache upon file download func addBranchListener(instruction:String, serverBonded: () -> Void){ /* Adds serverBonded() to the list of closures (blocks in Objective-C) to be called when file is updated. */ let sourceURL=NSURL(string: (instruction.componentsSeparatedByString("|").first!) ) //Get the url of the branch to verify if (branchListeners[instruction] == nil){ // Create an array for the file branchListeners.updateValue([], forKey: instruction) } branchListeners[instruction]?.append(serverBonded) // Add closure to array /* If the file already is in memory then call an initial branch to get some content or data for the app to work with. And check for file updates */ if (cachedFiles[instruction.componentsSeparatedByString("|").first!] != nil){ // if in memory serverBonded() // call update content methods if (sourceURL != nil && sourceURL?.scheme != nil && sourceURL?.host != nil){ // make sure this is a url refreshFileIfNeeded(sourceURL!) // check if the file needs to be updated } } /* The cached files failed to respond so let's see if this is a url at all and if it is fetch some data to update the branch. */ else if (sourceURL != nil && sourceURL?.scheme != nil && sourceURL?.host != nil){ fetchDataUsingCache(instruction, downloaded: nil, usingCache: true) // download file } } func checkBranchesFor(updatedInstruction:String){ /* Update all branches that have been added by addBranchListener(...) NOTE This is not finished it needs to only update content when changed */ let updatedFile=updatedInstruction.componentsSeparatedByString("|").first // get the file that changed for branch in branchListeners.keys { // get all branches if (branch.componentsSeparatedByString("|").first == updatedFile){ // compare the branches to see if it is the same file for responder in branchListeners[branch]! { // if there are things to be done in this branch do them responder() } } } } func refreshFileIfNeeded(trueURL:NSURL){ /* If the file does not exist update the file. Otherwise ask the server for the modification date. If the date is too old then download the new file. */ let storedPath=cacheDirectory!+"/"+trueURL.path!.stringByReplacingOccurrencesOfString("/", withString: "-") // the desired stored file path if (NSFileManager.defaultManager().fileExistsAtPath(storedPath) == false){ // there is no file here fetchDataUsingCache(trueURL.absoluteString, downloaded: nil, usingCache: true) // download the file } else { // there is a file here. let modificationDateRequest=NSMutableURLRequest(URL: trueURL, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: requestTimeout) modificationDateRequest.HTTPMethod="HEAD" // make a request for only the header information to get the modification date let task=NSURLSession.sharedSession().dataTaskWithRequest(modificationDateRequest, completionHandler: { (data:NSData?, response: NSURLResponse?, error:NSError?) -> Void in // return response closure if (response != nil && (response as! NSHTTPURLResponse).allHeaderFields["Last-Modified"] != nil){ // YES! we have a modification date! do { let offlineDate=try NSFileManager.defaultManager().attributesOfItemAtPath(storedPath)[NSFileModificationDate] as! NSDate //The date that we got the file last, let's hope that we don't have any issues here let formatter=NSDateFormatter() formatter.dateFormat = "EEE, d MMM yyyy H:mm:ss v" //This is to make a date interpreter because the format is not familiar to NSDateFormatter let onlineDate=formatter.dateFromString((response as! NSHTTPURLResponse).allHeaderFields["Last-Modified"] as! String) //The date we just recieved from the server if ((onlineDate?.timeIntervalSince1970)!-offlineDate.timeIntervalSince1970>60){ // file is too old fetchDataUsingCache(trueURL.absoluteString, downloaded: nil, usingCache: false) // update file } } catch { // Haven't had a problem with this in testing so far print("[ERROR] Failed to check modification date") } } }) task.resume() // call request above } } func fetchDataUsingCache(fileURL:String, downloaded: (() -> Void)?){ /* Refer to func fetchDataUsingCache(fileURL:String, downloaded: (() -> Void)?, usingCache:Bool). Simply passes in usingCache:Bool as true. */ fetchDataUsingCache(fileURL, downloaded: downloaded, usingCache: true) } func fetchDataUsingCache(fileURL:String, downloaded: (() -> Void)?, usingCache:Bool){ if (simulatedPoorConnection){ if (rand()%2<1){ downloaded!() return } } /* This is the current primary method for collective updating. It makes a list of all things that needs done once the file is downloaded. It ensures the download of the file appropriately with or without using the cache system (depending on usingCache:Bool). Once the file has been downloaded it completes all the tasks that needed that file. */ /* Completion actions Updates all closures that were waiting for file finish. Checks all branches since there is new updated content to let them know of any changes. */ let retrievedAction={ (data:NSData?) in if (data != nil){ // make sure we have some data in the first place if (fileDownloadedClosures[fileURL] != nil){ // If we have closures at all for closure in fileDownloadedClosures[fileURL]! { // cycle through closures closure() // call closure } fileDownloadedClosures[fileURL]?.removeAll() // These closures are only called once so dump them now fileDownloadedClosures.removeValueForKey(fileURL) // These closures are only called once so dump them now } checkBranchesFor(fileURL) // Inform branches } else { print("[ERROR] data is nil") } } if (fileURL != ""){ // If we actually have a file fetch if (logConnections){ print("[Fetcher] \(fileURL)") } /* Add tasks to list to go over once file is downloaded. */ if (fileDownloadedClosures[fileURL] == nil && downloaded != nil){ // If list of closures is not created yet fileDownloadedClosures.updateValue([], forKey: fileURL) // Create new closure list } if (downloaded != nil){ fileDownloadedClosures[fileURL]?.append(downloaded!) // add closure to list } var data:NSData? = nil // data of file let trueURL=NSURL(string: fileURL)! // NSURL version of url let storedPath=cacheDirectory!+"/"+trueURL.path!.stringByReplacingOccurrencesOfString("/", withString: "-") // make this a writable file path if (usingCache){ // If we can use the cache system do so if (logConnections){ print("[Fetcher] Using cache") } if ((cachedFiles[fileURL]) != nil){ // If the file is in memory just use that data=cachedFiles[fileURL]! // use file in memory retrievedAction(data) // now do any tasks that need to be done (Completion actions) } else if (offlineStorage){ // (used in control file for testing) let stored=NSData(contentsOfFile: storedPath) //Try using a local file if (stored != nil){ //Yay! we have a local file cachedFiles[fileURL]=stored // Add local file to memory data=stored // Assign to variable retrievedAction(data) // now do any tasks that need to be done (Completion actions) refreshFileIfNeeded(trueURL) //Check for any updates on the file } else { if (logConnections){ print("[Fetcher] Failed to recover file \(fileURL)") } } } } /* This file has either never been used before or it was deleted. Let's try requesting the data from the web. */ if (data == nil){ // make sure we still don't have the file if (logConnections){ print("[Fetcher] Attempt request") } /* This really doesn't matter because if our cache doesn't have the file apples probably doesn't either but let's try using Apple's cache if we can. */ var cachePolicy=NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData if (usingCache){ cachePolicy=NSURLRequestCachePolicy.ReloadRevalidatingCacheData } /* Make a new request for the file. Control file contain timeout control. */ let request=NSURLRequest(URL: trueURL, cachePolicy: cachePolicy, timeoutInterval: requestTimeout) let task=NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, padawan: NSURLResponse?, error:NSError?) -> Void in if (logConnections){ print("[Fetcher] Successful request") } if (data != nil && simulateOffline == false){ //File successfully downloaded if (offlineStorageSaving){ // Control file determines whether to save files (Mostly for testing) data?.writeToFile(storedPath, atomically: true) } cachedFiles[fileURL]=data //Save file to memory cachedBond[fileURL]=nil //let branch/unfold system have to reprocess this file for changes retrievedAction(data) // now do any tasks that need to be done (Completion actions) return } else { print("[ERROR] Failed to download resource \(fileURL) \(error)") } }) task.resume() // Make above request } } } /*Inline data requests.*/ func unfold(instruction:String)-> AnyObject?{ /* Refer to unfold(from:AnyObject?, var instructions:[AnyObject]) -> AnyObject? This simply prepares a string for use in the real unfold(...) -> AnyObject? method */ let instructions=NSString(string: instruction).componentsSeparatedByString("|") return unfold(nil, instructions: instructions) } func unfoldArray(from:NSArray, instructions:[AnyObject]) -> AnyObject?{ if (testLogSteps){ print("NSArray.objectAtIndex(\(instructions[0]))") } var source:AnyObject?=nil if (instructions[0].isKindOfClass(NSString.self) == true){ let stringval=instructions[0] as! String if (stringval.lowercaseString == "last"){ if (from.count>0){ source=from.objectAtIndex(from.count-1) } else { source=nil } } else if (stringval.lowercaseString == "first"){ if (from.count>0){ source=from.objectAtIndex(0) } else { source=nil } } else if (stringval.lowercaseString == "count"){ source=from.count } else { let i=Int((stringval as NSString).intValue) if (from.count>i&&i>=0){ source=from.objectAtIndex(i) // Unfold the NSArray } } } else if (instructions[0].isKindOfClass(NSNumber.self) == true){ let i=Int((instructions[0] as! NSNumber)) if (from.count>i&&i>=0){ source=from.objectAtIndex(i) // Unfold the NSArray } } else if (instructions[0].isKindOfClass(NSArray.self) == true) { for instruction in instructions[0] as! NSArray { let result=unfoldArray(from, instructions: [instruction]) if (result != nil){ return result } } } else { print("unknown type for unfolding array:\(instructions[0].dynamicType)") } return source } func unfoldDictionary(from:NSDictionary, instructions:[AnyObject]) -> AnyObject? { if (testLogSteps){ print("NSDictionary.objectForKey(\(instructions[0])) \(from.allKeys) \(instructions[0].dynamicType)") } if (from.objectForKey(instructions[0]) != nil){ return from.objectForKey(instructions[0]) } else if (instructions[0].isKindOfClass(NSArray.self) == true) { for instruction in instructions[0] as! NSArray { let result=from.objectForKey(instruction) if (result != nil){ if (testLogSteps){ print("NSDictionary.objectForKey(\(instruction)) success") } return from.objectForKey(instruction) // Unfold the NSDictionary } if ((instruction as! String)==""){ return from.objectForKey(from.allKeys.first!) } if (testLogSteps){ print("NSDictionary.objectForKey(\(instruction)) failed") } } } return nil } func unfold(from:AnyObject?, var instructions:[AnyObject]) -> AnyObject?{ /* This method is designed to make handling multilayered dictionaries, array or other forms of content much easier. This method also speeds up the process by storing to memory previous processing of the same file. Refer to FOLDING it the upper documentation. testLogSteps is a control variable used for logging. Turn on to see the steps made by this method. */ var source:AnyObject?=nil if (from?.isKindOfClass(NSDictionary.self) == true){ //The item to process is known already as an NSDictionary source=unfoldDictionary(from as! NSDictionary, instructions: instructions) } else if (from?.isKindOfClass(NSArray.self) == true) {//The item to process is known already as an NSArray source=unfoldArray(from as! NSArray, instructions: instructions) } else if (from?.isKindOfClass(NSString.self) == true){ if (testLogSteps){ print("from \(instructions[0]) is NSString") } source=(from as! NSString) } else if (from?.isKindOfClass(NSNumber.self) == true){ if (testLogSteps){ print("from \(instructions[0]) is NSNumber") } source=(from as! NSNumber) } else if (from==nil){ // The item to process is empty and we need to discover what the first instruction is and use that as the item for the next unfold if (testLogSteps){ print("from==nil") } let sourceURL=NSURL(string: (instructions[0]) as! String) // Attempt using the first instruction as a url if (cachedBond[instructions[0] as! String] != nil){ // Do we have a cache for this url? if (testLogSteps){ print("cachedbond... \(instructions[0] as! String) \(cachedBond[instructions[0] as! String].dynamicType)") } source=cachedBond[instructions[0] as! String]! // Let's not process this file again we already did that } if (sourceURL != nil && sourceURL?.scheme != nil && sourceURL?.host != nil && (source?.isKindOfClass(NSURL.self) == true || source == nil)){ // Alright so this instruction appears to be a url that we can request but we haven't processed it yet. if (testLogSteps){ print("URL is real \(sourceURL) \(instructions[0] as! String)") } source=sourceURL var sourceData=cachedFiles[instructions[0] as! String] // Use the file from memory cachedBond[instructions[0] as! String]=source // Save this to process bond to not do this again if (sourceData != nil){ // Alright we have some data to process print("try NSKeyUnarchiver") if (testLogSteps){ print("data returned as it should") } source=sourceData do { if (testLogSteps){ print(sourceURL) } let unarchiver=NSKeyedUnarchiver(forReadingWithData: sourceData!) if #available(iOS 9.0, *) { let tempDictionary=try unarchiver.decodeTopLevelObject() unarchiver.finishDecoding() if (tempDictionary != nil){ source=tempDictionary cachedBond[instructions[0] as! String]=source // save this to cache so we don't do it again } } else { // Fallback on earlier versions } } catch { /*log out any errors that might have occured*/ print(error) } } if (sourceData != nil && source?.isKindOfClass(NSDictionary.self) == false){ // Alright we have some data to process print("try NSJSONSerialization") if (testLogSteps){ print("data returned as it should") } source=sourceData do { if (testLogSteps){ print(sourceURL) } var sourceAttributedString = NSMutableAttributedString(string: NSString(data: sourceData!, encoding: NSUTF8StringEncoding) as! String) // Convert it into the proper string to be processed. if (removeEntitiesSystemLevel){ // Control level toggle incase this appears to keep breaking if (sourceAttributedString.string.containsString("&")){ TryCatch.realTry({ // The contained code can fail and swift can't catch it so we need an Objective-C try/catch implementation ontop of our swift try/catch do { let attributedOptions=[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding] sourceAttributedString = try NSMutableAttributedString(data:sourceData!, options:attributedOptions as! [String : AnyObject], documentAttributes:nil) //The data we get contains strings that are not meant to be seen by the user try removing the HTML entities //raises NSInternalInconsistencyException } catch { // System level HTML entity removal failed print("[ERROR] Could not remove HTML entities. \(error)") } }, withCatch: { // System level HTML entity removal failed print("[ERROR] Could not remove HTML entities.") }) } } print("[ERROR] Could not remove HTML entities.") let sourceString=sourceAttributedString.string sourceData=sourceString.dataUsingEncoding(NSUTF8StringEncoding) // Return the string we made for entity removal into data to be JSON processed /* Just double check real quick that the class is truly available */ if (NSClassFromString("NSJSONSerialization") != nil){ /*attempt serialization*/ let object=try NSJSONSerialization.JSONObjectWithData(sourceData!, options: NSJSONReadingOptions.MutableContainers) /*if it returned an actual NSDictionary then return it*/ if (object.isKindOfClass(NSDictionary.self)){ source=object as? NSDictionary cachedBond[instructions[0] as! String]=source // save this to cache so we don't do it again } } } catch { /*log out any errors that might have occured*/ print(error) } } if (sourceData != nil && source?.isKindOfClass(NSDictionary.self) == false){ //NSXMLParser(data: sourceData!).parse() print("xml last resort") //print(NSString(data: sourceData!, encoding: NSUTF8StringEncoding)) //let parser=RSSParser(data: sourceData!) //parser.parse() //print(parser.rootNode) } if ((source?.isKindOfClass(NSDictionary.self)) == true){ print((source as! NSDictionary).allKeys) } } } /* This method failed to return an NSObject but we have to return something and hopefully not cause an error. */ if (source == nil){ if (testLogSteps){ print("source is nil") } if (testLogSteps){ print((from as! NSObject).classForCoder) if ((from?.isKindOfClass(NSDictionary.self)) == true){ print("from \((from as! NSDictionary).allKeys) unfold \(instructions[0]) \(instructions[0].dynamicType)") } if ((from?.isKindOfClass(NSArray.self)) == true){ print("from [\((from as! NSArray).count)] unfold \(instructions[0]) \(instructions[0].dynamicType)") } else { print("from \(from) unfold \(instructions[0]) \(instructions[0].dynamicType)") } } return nil } /*Loop through this method until we are out of instructions*/ instructions.removeFirst() if (instructions.count>0){ return unfold(source, instructions: instructions) } return source } func dataUsingCache(fileURL:String) -> NSData?{ /* Refer to: func dataUsingCache(fileURL:String, usingCache:Bool) -> NSData? Always uses cache if available. */ return dataUsingCache(fileURL, usingCache: true) } func dataUsingCache(fileURL:String, usingCache:Bool) -> NSData?{ if (logConnections){ print("[Fetcher-inline] \(fileURL)") } if (simulatedPoorConnection){ if (rand()%2<1){ return nil } } /* This method is used to speed up reopening the same file using caching if usingCache is true. STEP 1 Check if file is already in memory cache. This will only occure if STEP 2/3 have occured successfully for the same fileURL with usingCache == true STEP 2 Check if file has been stored in cached (Library in simulator) directory. If so save it to active memory and return data. STEP 3 Attempt online fetch of fileURL. The file is repeatedly requested up to 100 (maxAttempts) times just in cases of poor connection. If failed nil is returned */ var data:NSData? = nil let trueURL=NSURL(string: fileURL)! var storedPath=cacheDirectory!+"/"+trueURL.path!.stringByReplacingOccurrencesOfString("/", withString: "-") if (usingCache){ if (logConnections){ print("[Fetcher-inline] attempt using cache") } if ((cachedFiles[fileURL]) != nil){ //STEP 1 data=cachedFiles[fileURL]! } else { //STEP 2 if (offlineStorage){ let stored=NSData(contentsOfFile: storedPath) cachedFiles[fileURL]=stored data=stored let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { dispatch_async(dispatch_get_main_queue()) { checkBranchesFor(fileURL) } } } } } if ((data) != nil){ return data } //STEP 3 var attempts=0 //Amount of attempts to download the file let maxAttempts=100//Amount of possible attempts var badConnection=false while (data == nil){ //If the file is not downloaded download it if (attempts>maxAttempts){ //But if we have tried 100 times then give up print("Failed to download \(fileURL)") return nil //give up } else { do { if (logConnections){ print("[Fetcher-inline] attempt request") } let downloadedData=try NSData(contentsOfURL: trueURL, options: .UncachedRead) //Download if (simulateOffline == false){ //File successfully downloaded if (offlineStorageSaving){ if (logConnections){ print("[dataUsingCache] write to file... \(storedPath)") } //downloadedData.writeToFile(storedPath, atomically: true) //Save file locally for use later data?.writeToFile(storedPath, atomically: true) //Save file locally for use later } cachedFiles[fileURL]=downloadedData //Save file to memory cachedBond[fileURL]=nil data=cachedFiles[fileURL]! //Use as local variable let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { dispatch_async(dispatch_get_main_queue()) { checkBranchesFor(fileURL) } } return data! //Return file } } catch { print(error) } } attempts++ //Count another attempt to download the file if (badConnection==false){ print("Bad connection \(fileURL)") badConnection=true } } storedPath=NSBundle.mainBundle().pathForResource(trueURL.path!.stringByReplacingOccurrencesOfString("/", withString: "-").componentsSeparatedByString(".").first, ofType: trueURL.path!.stringByReplacingOccurrencesOfString("/", withString: "-").componentsSeparatedByString(".").last)! let stored=NSData(contentsOfFile: storedPath) cachedFiles[fileURL]=stored data=stored let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { dispatch_async(dispatch_get_main_queue()) { checkBranchesFor(fileURL) } } return data! //THIS CAN NOT BE CALLED this is just for the compiler } func dictionaryOfPath(path: String) -> NSDictionary?{ /* Refer to func dictionaryOfPath(path: String, usingCache: Bool) -> NSDictionary? WARNING This method is failable depending on what data is passed in. */ return dictionaryOfPath(path, usingCache: true) } func dictionaryOfPath(path: String, usingCache: Bool) -> NSDictionary?{ /* This method breaks down JSON files converting them to NSDictionaries. Firstly grabs data from the path parameter. Second strips away all HTML entities (E.g. &amp; = &) Finally using NSJSONSerialization the data is converted into a usable NSDictionary class. Read comments in: func dataUsingCache(fileURL:String) -> NSData For more details WARNING This method is failable depending on what data is passed in. */ do { var sourceData=dataUsingCache(path, usingCache: usingCache) if (sourceData == nil){ return nil } var sourceAttributedString = NSMutableAttributedString(string: NSString(data: sourceData!, encoding: NSUTF8StringEncoding) as! String) TryCatch.realTry({ if (removeEntitiesSystemLevel){ do { let attributedOptions=[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding] //sourceAttributedString=try NSMutableAttributedString(data:sourceData!, options:attributedOptions as! [String : AnyObject] ,documentAttributes:nil) //print("attributes passed") sourceAttributedString = try NSMutableAttributedString(data:sourceData!, options:attributedOptions as! [String : AnyObject], documentAttributes:nil) //raises NSInternalInconsistencyException } catch { print("[ERROR] Could not remove HTML entities. \(error)") } } }, withCatch: { print("[ERROR] Could not remove HTML entities.") }) let sourceString=sourceAttributedString.string.stringByReplacingOccurrencesOfString("&amp;", withString: "&") sourceData=sourceString.dataUsingEncoding(NSUTF8StringEncoding) /* Just double check real quick that the class is truly available */ if (NSClassFromString("NSJSONSerialization") != nil){ /*attempt serialization*/ let object=try NSJSONSerialization.JSONObjectWithData(sourceData!, options: NSJSONReadingOptions.MutableContainers) /*if it returned an actual NSDictionary then return it*/ if (object.isKindOfClass(NSDictionary.self)){ cachedBond[path]=object return object as? NSDictionary } } } catch { /*log out any errors that might have occured*/ print(error) } return nil } func imageUsingCache(imageURL:String) -> UIImage?{ /* This method opens an image from memory if already loaded otherwise it performs a normal data fetch operation. Read comments in: func dataUsingCache(fileURL:String) -> NSData For more details */ let data=dataUsingCache(imageURL) if (data != nil){ return UIImage(data:data!)! } return nil } class XMLParser:NSXMLParser, NSXMLParserDelegate { override init(data:NSData) { super.init(data: data) self.delegate = self print("init") } func parserDidStartDocument(parser: NSXMLParser) { print("start document") } func parser(parser: NSXMLParser, foundElementDeclarationWithName elementName: String, model: String) { print("element \(elementName)") } func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) { print(parseError) } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { print("<\(elementName)>") } } class RSSParser:NSXMLParser, NSXMLParserDelegate { var rootNode:XMLNode?=nil var buildNode:XMLNode?=nil override init(data:NSData) { super.init(data: data) self.delegate = self print("init") } func parserDidStartDocument(parser: NSXMLParser) { print("start document") } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { let node=XMLNode() node.name=elementName node.attributes=attributeDict buildNode?.inside.append(node) buildNode=node if (rootNode == nil){ rootNode=node } } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { buildNode=buildNode?.parent } func parser(parser: NSXMLParser, foundElementDeclarationWithName elementName: String, model: String) { print("element \(elementName)") } func parser(parser: NSXMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) { print("unparse <\(name)>") } func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) { print(parseError) } func dicionary() -> NSDictionary { var dict = NSMutableDictionary() return dict } } class XMLNode { struct attribute { var name = "" var value = "" } var name="" var attributes:[String : String]=[:] var inside:[AnyObject]=[] var parent:XMLNode?=nil }
mit
fbb31072c4f06251e79af049b01c77d6
36.446907
412
0.586068
5.407333
false
false
false
false
auth0/Lock.swift
Lock/CDNLoaderInteractor.swift
1
9241
// CDNLoaderInteractor.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation typealias JSONObject = [String: Any] typealias JSONArray = [JSONObject] struct CDNLoaderInteractor: RemoteConnectionLoader, Loggable { let url: URL init(baseURL: URL, clientId: String) { self.url = URL(string: "client/\(clientId).js", relativeTo: baseURL)! } func load(_ callback: @escaping (UnrecoverableError?, Connections?) -> Void) { self.logger.info("Loading application info from \(self.url)") let task = URLSession.shared.dataTask(with: self.url, completionHandler: { (data, response, error) in guard error?._code != NSURLErrorTimedOut else { return callback(.connectionTimeout, nil) } guard error == nil else { self.logger.error("Failed to load with error \(error!)") return callback(.requestIssue, nil) } guard let response = response as? HTTPURLResponse else { self.logger.error("Response was not NSHTTURLResponse") return callback(.requestIssue, nil) } let payload: String? if let data = data { payload = String(data: data, encoding: .utf8) } else { payload = nil } guard 200...299 ~= response.statusCode else { self.logger.error("HTTP response was not successful. HTTP \(response.statusCode) <\(payload ?? "No Body")>") guard response.statusCode != 403 else { return callback(.invalidClientOrDomain, nil) } return callback(.requestIssue, nil) } guard var jsonp = payload else { self.logger.error("HTTP response had no jsonp \(payload ?? "No Body")") return callback(.invalidClientOrDomain, nil) } self.logger.verbose("Received jsonp \(jsonp)") if let prefixRange = jsonp.range(of: "Auth0.setClient(") { jsonp.removeSubrange(prefixRange) } if let suffixRange = jsonp.range(of: ");") { jsonp.removeSubrange(suffixRange) } do { var connections = OfflineConnections() let json = try JSONSerialization.jsonObject(with: jsonp.data(using: String.Encoding.utf8)!, options: []) as? JSONObject self.logger.debug("Application configuration is \(json.verbatim())") let info = ClientInfo(json: json) if let auth0 = info.auth0 { auth0.connections.forEach { connection in let requiresUsername = connection.booleanValue(forKey: "requires_username") connections.database(name: connection.name, requiresUsername: requiresUsername, usernameValidator: connection.usernameValidation, passwordValidator: PasswordPolicyValidator(policy: connection.passwordPolicy)) } } info.enterprise.forEach { strategy in strategy.connections.forEach { connection in let domains = connection.json["domain_aliases"] as? [String] ?? [] let template = AuthStyle.style(forStrategy: strategy.name, connectionName: connection.name) let style = AuthStyle(name: domains.first ?? strategy.name, color: template.normalColor, withImage: template.image) connections.enterprise(name: connection.name, domains: domains, style: style) } } info.oauth2.forEach { strategy in strategy.connections.forEach { connections.social(name: $0.name, style: AuthStyle.style(forStrategy: strategy.name, connectionName: $0.name)) } } info.passwordless.forEach { strategy in strategy.connections.forEach { if strategy.name == "email" { connections.email(name: $0.name) } else { connections.sms(name: $0.name) } } } guard !connections.isEmpty else { return callback(.clientWithNoConnections, connections) } callback(nil, connections) } catch let exception { self.logger.error("Failed to parse \(jsonp) with error \(exception)") return callback(.invalidClientOrDomain, nil) } }) task.resume() } } private struct ClientInfo { let json: JSONObject? var strategies: [StrategyInfo] { let list = json?["strategies"] as? JSONArray ?? [] return list .map { StrategyInfo(json: $0) } .filter { $0 != nil } .map { $0! } } var auth0: StrategyInfo? { return strategies.filter({ $0.name == "auth0" }).first } var oauth2: [StrategyInfo] { return strategies.filter { $0.name != "auth0" && !passwordlessStrategyNames.contains($0.name) && !enterpriseStrategyNames.contains($0.name) } } var enterprise: [StrategyInfo] { return strategies.filter { $0.name != "auth0" && !passwordlessStrategyNames.contains($0.name) && enterpriseStrategyNames.contains($0.name) } } var passwordless: [StrategyInfo] { return strategies.filter { passwordlessStrategyNames.contains($0.name) } } let passwordlessStrategyNames = [ "email", "sms" ] let enterpriseStrategyNames = [ "google-apps", "google-openid", "office365", "waad", "adfs", "ad", "samlp", "pingfederate", "ip", "mscrm", "custom", "sharepoint" ] let enterpriseCredentialAuthNames = [ "waad", "adfs", "ad" ] } private struct StrategyInfo { let json: JSONObject let name: String var connections: [ConnectionInfo] { let list = json["connections"] as? JSONArray ?? [] return list .map { ConnectionInfo(json: $0) } .filter { $0 != nil } .map { $0! } } init?(json: JSONObject) { guard let name = json["name"] as? String else { return nil } self.json = json self.name = name } } private struct ConnectionInfo { let json: JSONObject let name: String func booleanValue(forKey key: String, defaultValue: Bool = false) -> Bool { return json[key] as? Bool ?? defaultValue } var usernameValidation: UsernameValidator { let validation = json["validation"] as? JSONObject let username = validation?["username"] as? JSONObject switch (username?["min"], username?["max"]) { case let (min as Int, max as Int): return UsernameValidator(withLength: min...max, characterSet: UsernameValidator.auth0) case let (minString as String, maxString as String): guard let min = Int(minString), let max = Int(maxString) else { return UsernameValidator() } return UsernameValidator(withLength: min...max, characterSet: UsernameValidator.auth0) default: return UsernameValidator() } } var passwordPolicy: PasswordPolicy { let name = (json["passwordPolicy"] as? String) ?? "none" guard let policy = PasswordPolicy.Auth0(rawValue: name) else { return .none() } let options = (json["password_complexity_options"] as? [String: Any]) ?? nil switch policy { case .excellent: return .excellent(withOptions: options) case .good: return .good(withOptions: options) case .fair: return .fair(withOptions: options) case .low: return .low(withOptions: options) case .none: return .none(withOptions: options) } } init?(json: JSONObject) { guard let name = json["name"] as? String else { return nil } self.json = json self.name = name } }
mit
7984c1f2285df9a8798815006738c3cb
38.660944
232
0.592901
4.702799
false
false
false
false
february29/Learning
swift/Fch_Contact/Pods/HandyJSON/Source/Serializer.swift
4
2744
/* * Copyright 1999-2101 Alibaba Group. * * 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. */ // // JSONSerializer.swift // HandyJSON // // Created by zhouzhuo on 9/30/16. // import Foundation public extension HandyJSON { public func toJSON() -> [String: Any]? { if let dict = Self._serializeAny(object: self) as? [String: Any] { return dict } return nil } public func toJSONString(prettyPrint: Bool = false) -> String? { if let anyObject = self.toJSON() { if JSONSerialization.isValidJSONObject(anyObject) { do { let jsonData: Data if prettyPrint { jsonData = try JSONSerialization.data(withJSONObject: anyObject, options: [.prettyPrinted]) } else { jsonData = try JSONSerialization.data(withJSONObject: anyObject, options: []) } return String(data: jsonData, encoding: .utf8) } catch let error { InternalLogger.logError(error) } } else { InternalLogger.logDebug("\(anyObject)) is not a valid JSON Object") } } return nil } } public extension Collection where Iterator.Element: HandyJSON { public func toJSON() -> [[String: Any]?] { return self.map{ $0.toJSON() } } public func toJSONString(prettyPrint: Bool = false) -> String? { let anyArray = self.toJSON() if JSONSerialization.isValidJSONObject(anyArray) { do { let jsonData: Data if prettyPrint { jsonData = try JSONSerialization.data(withJSONObject: anyArray, options: [.prettyPrinted]) } else { jsonData = try JSONSerialization.data(withJSONObject: anyArray, options: []) } return String(data: jsonData, encoding: .utf8) } catch let error { InternalLogger.logError(error) } } else { InternalLogger.logDebug("\(self.toJSON()) is not a valid JSON Object") } return nil } }
mit
1c2fe7e6e83b3fe341016bd75de01b62
31.666667
115
0.575437
4.882562
false
false
false
false
shawnirvin/Terminal-iOS-Swift
Terminal/Supporting Files/AppDelegate.swift
1
3356
// // AppDelegate.swift // Terminal // // Created by Shawn Irvin on 11/25/15. // Copyright © 2015 Shawn Irvin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { let command = shortcutItem.userInfo!["command"] as! String let programString = shortcutItem.userInfo!["program"] as! String let classInst = NSClassFromString("Terminal." + programString) as! NSObject.Type let program = classInst.init() as! Program TerminalViewController.currentInstance.currentProgram = program program.runCommand(Command(rawInput: command)) { response in let hasText = TerminalViewController.currentInstance.terminalTextView.text.characters.count > 0 if let output = response { if hasText { TerminalViewController.currentInstance.terminalTextView.print("\n\n") } TerminalViewController.currentInstance.terminalTextView.print("\t" + output) } if hasText { TerminalViewController.currentInstance.getInput() } completionHandler(true) } } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
f69ea7709822de1d021689bdebea558a
44.958904
285
0.701639
5.715503
false
false
false
false
banxi1988/BXPopover
Example/Pods/BXModel/Pod/Classes/StaticTableViewDataSource.swift
1
1407
// // StaticTableViewDataSource.swift // Pods // // Created by Haizhen Lee on 15/12/1. // // import Foundation public class StaticTableViewDataSource:NSObject,UITableViewDataSource,BXDataSourceContainer{ var cells:[UITableViewCell] = [] public typealias ItemType = UITableViewCell public init(cells:[UITableViewCell] = []){ self.cells = cells } public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } public func cellAtIndexPath(indexPath:NSIndexPath) -> UITableViewCell{ return self.cells[indexPath.row] } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.cells.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ return cells[indexPath.row] } public func append(cell:UITableViewCell){ self.cells.append(cell) } public func appendContentsOf(cells:[UITableViewCell]){ self.cells.appendContentsOf(cells) } public func updateItems<S : SequenceType where S.Generator.Element == ItemType>(items: S) { self.cells.removeAll() self.cells.appendContentsOf(items) } public func appendItems<S : SequenceType where S.Generator.Element == ItemType>(items: S) { self.cells.appendContentsOf(items) } public var numberOfItems:Int{ return cells.count } }
mit
66cf1c4a2c5194f1737a8b4b253af573
24.6
113
0.725657
4.568182
false
false
false
false
soapyigu/LeetCode_Swift
LinkedList/OddEvenLinkedList.swift
1
1116
/** * Question Link: https://leetcode.com/problems/odd-even-linked-list/ * Primary idea: Prev-post two pointers; change the prev and move both at a time * Time Complexity: O(n), Space Complexity: O(1) * * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */ class OddEvenLinkedList { func oddEvenList(_ head: ListNode?) -> ListNode? { guard head != nil && head!.next != nil else { return head } let evenHead = head!.next var p = head var q = evenHead var isEndEven = true while q!.next != nil { let node = q!.next p!.next = node p = q q = node isEndEven = !isEndEven } if isEndEven { p!.next = evenHead } else { p!.next = nil q!.next = evenHead } return head } }
mit
e6cbb4be9b5d0eae517e76efe16ed26d
22.765957
80
0.479391
4.148699
false
false
false
false
neoneye/SwiftyFORM
Example/DatePicker/DatePickerBindingViewController.swift
1
2978
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit import SwiftyFORM class DatePickerBindingViewController: FormViewController { override func populate(_ builder: FormBuilder) { builder.navigationTitle = "DatePicker & Bindings" builder.toolbarMode = .simple builder += SectionHeaderTitleFormItem(title: "Always expanded") builder += datePicker builder += incrementButton builder += decrementButton builder += SectionFormItem() builder += summary builder += SectionFormItem() builder += StaticTextFormItem().title("Collapse & expand") builder += userName builder += toggleDatePicker0 builder += toggleDatePicker1 builder += toggleDatePicker2 updateSummary() } lazy var datePicker: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title = "Date" instance.datePickerMode = .date instance.behavior = .expandedAlways instance.valueDidChangeBlock = { [weak self] _ in self?.updateSummary() } return instance }() lazy var incrementButton: ButtonFormItem = { let instance = ButtonFormItem() instance.title = "Next Day" instance.action = { [weak self] in self?.increment() } return instance }() lazy var decrementButton: ButtonFormItem = { let instance = ButtonFormItem() instance.title = "Previous Day" instance.action = { [weak self] in self?.decrement() } return instance }() lazy var summary: StaticTextFormItem = StaticTextFormItem().title("Date").value("-") func updateSummary() { summary.value = "\(datePicker.value)" } func offsetDate(_ date: Date, days: Int) -> Date { var dateComponents = DateComponents() dateComponents.day = days let calendar = Calendar.current guard let resultDate = calendar.date(byAdding: dateComponents, to: date) else { return date } return resultDate } func increment() { datePicker.setValue(offsetDate(datePicker.value, days: 1), animated: true) updateSummary() } func decrement() { datePicker.setValue(offsetDate(datePicker.value, days: -1), animated: true) updateSummary() } // MARK: Collapse / expand lazy var userName: TextFieldFormItem = { let instance = TextFieldFormItem() instance.title("User Name").placeholder("required") instance.keyboardType = .asciiCapable instance.autocorrectionType = .no return instance }() lazy var toggleDatePicker0: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title = "Toggle 0" instance.datePickerMode = .time instance.behavior = .expanded return instance }() lazy var toggleDatePicker1: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title = "Toggle 1" instance.datePickerMode = .time instance.behavior = .collapsed return instance }() lazy var toggleDatePicker2: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title = "Toggle 2" instance.datePickerMode = .time instance.behavior = .collapsed return instance }() }
mit
fca9064551b8c9e418adbac144ab2478
24.452991
85
0.725319
3.949602
false
false
false
false
MattKiazyk/Operations
framework/OperationsTests/BlockConditionTests.swift
1
1579
// // BlockConditionTests.swift // Operations // // Created by Daniel Thorpe on 20/07/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import XCTest import Operations class BlockConditionTests: OperationTests { func test__operation_with_successful_block_condition_finishes() { let expectation = expectationWithDescription("Test: \(__FUNCTION__)") let operation = TestOperation() operation.addCondition(BlockCondition { true }) operation.addCompletionBlockToTestOperation(operation, withExpectation: expectation) runOperation(operation) waitForExpectationsWithTimeout(3, handler: nil) XCTAssertTrue(operation.finished) } func test__operation_with_unsuccess_block_condition_errors() { let expectation = expectationWithDescription("Test: \(__FUNCTION__)") let operation = TestOperation() operation.addCondition(BlockCondition { false }) var receivedErrors = [ErrorType]() operation.addObserver(BlockObserver(finishHandler: { (op, errors) in receivedErrors = errors expectation.fulfill() })) runOperation(operation) waitForExpectationsWithTimeout(3, handler: nil) XCTAssertFalse(operation.didExecute) XCTAssertTrue(operation.cancelled) if let error = receivedErrors[0] as? BlockCondition.Error { XCTAssertTrue(error == BlockCondition.Error.BlockConditionFailed) } else { XCTFail("No error message was observed") } } }
mit
c54acc4adcebc4a9153102f1bba2bf5e
29.346154
92
0.673638
5.277592
false
true
false
false
richardpiazza/SOSwift
Sources/SOSwift/Time.swift
1
2569
import Foundation public struct Time: RawRepresentable, Equatable, Codable { public typealias RawValue = Date @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public static var iso8601: ISO8601DateFormatter { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withTime, .withTimeZone, .withColonSeparatorInTime, .withColonSeparatorInTimeZone] return formatter } public static var iso8601Simple: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "HH':'mm':'ssZZZZZ" return formatter } public static func makeDate(from string: String) throws -> Date { let _date: Date? if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { _date = iso8601.date(from: string) } else { _date = iso8601Simple.date(from: string) } guard let date = _date else { throw SchemaError.incorrectDateFormat } return date } public static func makeString(from date: Date) -> String { if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { return iso8601.string(from: date) } else { return iso8601Simple.string(from: date) } } public var rawValue: Date public init(rawValue: Date) { self.rawValue = rawValue } public init?(stringValue: String) { let date: Date do { date = try type(of: self).makeDate(from: stringValue) } catch { return nil } rawValue = date } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let value = try container.decode(String.self) rawValue = try type(of: self).makeDate(from: value) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(stringValue) } var stringValue: String { return type(of: self).makeString(from: rawValue) } } public extension Time { var dateComponents: DateComponents { return Calendar.current.dateComponents(in: TimeZone(secondsFromGMT: 0)!, from: rawValue) } var hour: Int? { return dateComponents.hour } var minute: Int? { return dateComponents.minute } var second: Int? { return dateComponents.second } }
mit
feceb7e48ae92b2a0b8b41fe7c2d522b
26.623656
118
0.590891
4.546903
false
false
false
false
zvonler/PasswordElephant
external/github.com/apple/swift-protobuf/Sources/SwiftProtobuf/FieldTypes.swift
9
19803
// Sources/SwiftProtobuf/FieldTypes.swift - Proto data types // // 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/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Serialization/deserialization support for each proto field type. /// /// Note that we cannot just extend the standard Int32, etc, types /// with serialization information since proto language supports /// distinct types (with different codings) that use the same /// in-memory representation. For example, proto "sint32" and /// "sfixed32" both are represented in-memory as Int32. /// /// These types are used generically and also passed into /// various coding/decoding functions to provide type-specific /// information. /// // ----------------------------------------------------------------------------- import Foundation // Note: The protobuf- and JSON-specific methods here are defined // in ProtobufTypeAdditions.swift and JSONTypeAdditions.swift public protocol FieldType { // The Swift type used to store data for this field. For example, // proto "sint32" fields use Swift "Int32" type. associatedtype BaseType: Hashable // The default value for this field type before it has been set. // This is also used, for example, when JSON decodes a "null" // value for a field. static var proto3DefaultValue: BaseType { get } // Generic reflector methods for looking up the correct // encoding/decoding for extension fields, map keys, and map // values. static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws } /// /// Marker protocol for types that can be used as map keys /// public protocol MapKeyType: FieldType { } /// /// Marker Protocol for types that can be used as map values. /// public protocol MapValueType: FieldType { } // // We have a struct for every basic proto field type which provides // serialization/deserialization support as static methods. // /// /// Float traits /// public struct ProtobufFloat: FieldType, MapValueType { public typealias BaseType = Float static public var proto3DefaultValue: Float {return 0.0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularFloatField(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedFloatField(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularFloatField(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedFloatField(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedFloatField(value: value, fieldNumber: fieldNumber) } } /// /// Double /// public struct ProtobufDouble: FieldType, MapValueType { public typealias BaseType = Double static public var proto3DefaultValue: Double {return 0.0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularDoubleField(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedDoubleField(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularDoubleField(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedDoubleField(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedDoubleField(value: value, fieldNumber: fieldNumber) } } /// /// Int32 /// public struct ProtobufInt32: FieldType, MapKeyType, MapValueType { public typealias BaseType = Int32 static public var proto3DefaultValue: Int32 {return 0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularInt32Field(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedInt32Field(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularInt32Field(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedInt32Field(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedInt32Field(value: value, fieldNumber: fieldNumber) } } /// /// Int64 /// public struct ProtobufInt64: FieldType, MapKeyType, MapValueType { public typealias BaseType = Int64 static public var proto3DefaultValue: Int64 {return 0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularInt64Field(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedInt64Field(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularInt64Field(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedInt64Field(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedInt64Field(value: value, fieldNumber: fieldNumber) } } /// /// UInt32 /// public struct ProtobufUInt32: FieldType, MapKeyType, MapValueType { public typealias BaseType = UInt32 static public var proto3DefaultValue: UInt32 {return 0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularUInt32Field(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedUInt32Field(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularUInt32Field(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedUInt32Field(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedUInt32Field(value: value, fieldNumber: fieldNumber) } } /// /// UInt64 /// public struct ProtobufUInt64: FieldType, MapKeyType, MapValueType { public typealias BaseType = UInt64 static public var proto3DefaultValue: UInt64 {return 0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularUInt64Field(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedUInt64Field(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularUInt64Field(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedUInt64Field(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedUInt64Field(value: value, fieldNumber: fieldNumber) } } /// /// SInt32 /// public struct ProtobufSInt32: FieldType, MapKeyType, MapValueType { public typealias BaseType = Int32 static public var proto3DefaultValue: Int32 {return 0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularSInt32Field(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedSInt32Field(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularSInt32Field(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedSInt32Field(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedSInt32Field(value: value, fieldNumber: fieldNumber) } } /// /// SInt64 /// public struct ProtobufSInt64: FieldType, MapKeyType, MapValueType { public typealias BaseType = Int64 static public var proto3DefaultValue: Int64 {return 0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularSInt64Field(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedSInt64Field(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularSInt64Field(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedSInt64Field(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedSInt64Field(value: value, fieldNumber: fieldNumber) } } /// /// Fixed32 /// public struct ProtobufFixed32: FieldType, MapKeyType, MapValueType { public typealias BaseType = UInt32 static public var proto3DefaultValue: UInt32 {return 0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularFixed32Field(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedFixed32Field(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularFixed32Field(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedFixed32Field(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedFixed32Field(value: value, fieldNumber: fieldNumber) } } /// /// Fixed64 /// public struct ProtobufFixed64: FieldType, MapKeyType, MapValueType { public typealias BaseType = UInt64 static public var proto3DefaultValue: UInt64 {return 0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularFixed64Field(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedFixed64Field(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularFixed64Field(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedFixed64Field(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedFixed64Field(value: value, fieldNumber: fieldNumber) } } /// /// SFixed32 /// public struct ProtobufSFixed32: FieldType, MapKeyType, MapValueType { public typealias BaseType = Int32 static public var proto3DefaultValue: Int32 {return 0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularSFixed32Field(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedSFixed32Field(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularSFixed32Field(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedSFixed32Field(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedSFixed32Field(value: value, fieldNumber: fieldNumber) } } /// /// SFixed64 /// public struct ProtobufSFixed64: FieldType, MapKeyType, MapValueType { public typealias BaseType = Int64 static public var proto3DefaultValue: Int64 {return 0} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularSFixed64Field(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedSFixed64Field(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularSFixed64Field(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedSFixed64Field(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedSFixed64Field(value: value, fieldNumber: fieldNumber) } } /// /// Bool /// public struct ProtobufBool: FieldType, MapKeyType, MapValueType { public typealias BaseType = Bool static public var proto3DefaultValue: Bool {return false} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularBoolField(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedBoolField(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularBoolField(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedBoolField(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitPackedBoolField(value: value, fieldNumber: fieldNumber) } } /// /// String /// public struct ProtobufString: FieldType, MapKeyType, MapValueType { public typealias BaseType = String static public var proto3DefaultValue: String {return String()} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularStringField(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedStringField(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularStringField(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedStringField(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { assert(false) } } /// /// Bytes /// public struct ProtobufBytes: FieldType, MapValueType { public typealias BaseType = Data static public var proto3DefaultValue: Data {return Internal.emptyData} public static func decodeSingular<D: Decoder>(value: inout BaseType?, from decoder: inout D) throws { try decoder.decodeSingularBytesField(value: &value) } public static func decodeRepeated<D: Decoder>(value: inout [BaseType], from decoder: inout D) throws { try decoder.decodeRepeatedBytesField(value: &value) } public static func visitSingular<V: Visitor>(value: BaseType, fieldNumber: Int, with visitor: inout V) throws { try visitor.visitSingularBytesField(value: value, fieldNumber: fieldNumber) } public static func visitRepeated<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { try visitor.visitRepeatedBytesField(value: value, fieldNumber: fieldNumber) } public static func visitPacked<V: Visitor>(value: [BaseType], fieldNumber: Int, with visitor: inout V) throws { assert(false) } }
gpl-3.0
5f76e219f636bb25d08e6cd6d571e7e1
47.065534
117
0.720901
4.553461
false
false
false
false
sarvex/PostCard
PostCard/ModelController.swift
1
3250
// // ModelController.swift // PostCard // // Created by Sarvex Jatasra on 11/04/2015. // Copyright (c) 2015 Sarvex Jatasra. All rights reserved. // import UIKit /* A controller object that manages a simple model -- a collection of month names. The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:. It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application. There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand. */ class ModelController: NSObject, UIPageViewControllerDataSource { var pageData = NSArray() override init() { super.init() // Create the data model. let dateFormatter = NSDateFormatter() pageData = dateFormatter.monthSymbols } func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> DataViewController? { // Return the data view controller for the given index. if (self.pageData.count == 0) || (index >= self.pageData.count) { return nil } // Create a new view controller and pass suitable data. let dataViewController = storyboard.instantiateViewControllerWithIdentifier("DataViewController") as! DataViewController dataViewController.dataObject = self.pageData[index] return dataViewController } func indexOfViewController(viewController: DataViewController) -> Int { // Return the index of the given data view controller. // For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index. if let dataObject: AnyObject = viewController.dataObject { return self.pageData.indexOfObject(dataObject) } else { return NSNotFound } } // MARK: - Page View Controller Data Source func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if (index == 0) || (index == NSNotFound) { return nil } index-- return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if index == NSNotFound { return nil } index++ if index == self.pageData.count { return nil } return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } }
isc
3f95a7929bd1eb21928152d999a83889
39.123457
225
0.709538
5.593804
false
false
false
false
mownier/photostream
Photostream/Modules/Comment Writer/Interactor/CommentWriterData.swift
1
651
// // CommentWriterData.swift // Photostream // // Created by Mounir Ybanez on 30/11/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // protocol CommentWriterData { var id: String { set get } var content: String { set get } var timestamp: Double { set get } var authorName: String { set get } var authorId: String { set get } var authorAvatar: String { set get } } struct CommentWriterDataItem: CommentWriterData { var id: String = "" var content: String = "" var timestamp: Double = 0 var authorName: String = "" var authorId: String = "" var authorAvatar: String = "" }
mit
42bbec852d1c7fd597bac19884d970f9
23.074074
56
0.64
4.037267
false
false
false
false
sarvex/SwiftRecepies
Extensions/Creating a Service Within Your App with Action Extensions/Creating a Service Within Your App with Action Extensions/ViewController.swift
1
2487
// // ViewController.swift // Creating a Service Within Your App with Action Extensions // // Created by Vandad Nahavandipoor on 7/27/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import MobileCoreServices class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! let type = kUTTypeText as NSString as String func activityCompletionHandler(activityType: String!, completed: Bool, returnedItems: [AnyObject]!, activityError: NSError!){ if completed && activityError == nil{ let item = returnedItems[0] as! NSExtensionItem if let attachments = item.attachments{ let attachment = attachments[0] as! NSItemProvider if attachment.hasItemConformingToTypeIdentifier(type){ attachment.loadItemForTypeIdentifier(type, options: nil, completionHandler: {[weak self] (item: NSSecureCoding!, error: NSError!) in let strongSelf = self! if error != nil{ strongSelf.textField.text = "\(error)" } else { if let value = item as? String{ strongSelf.textField.text = value } } }) } } } } @IBAction func performShare(){ let controller = UIActivityViewController(activityItems: [textField.text], applicationActivities: nil) controller.completionWithItemsHandler = activityCompletionHandler presentViewController(controller, animated: true, completion: nil) } }
isc
223fd669a338b4c2ea56547f6e3ebbc2
31.723684
83
0.63852
5.044625
false
false
false
false
prolificinteractive/Marker
Marker/Marker/Parser/Symbol.swift
1
3516
// // Symbol.swift // Marker // // Created by Htin Linn on 4/28/17. // Copyright © 2017 Prolific Interactive. All rights reserved. // import Foundation /// A `Symbol` is a one or two character `String` used for marking up text. struct Symbol: RawRepresentable, Equatable { typealias RawValue = String /// Underlying `String` representation. let rawValue: String /// Length of the symbol. var length: Int { return rawValue.count } // MARK: - Private properties private let symbolCharacterOne: Character? private let symbolCharacterTwo: Character? // MARK: - Init/deinit /// Creates a new instance with the specified raw value. /// /// If the character count of the `rawValue` isn't either one or zero, this intializer returns `nil`. /// /// - Parameter rawValue: The raw value to use for the new instance. /// - Returns: A new `Symbol` instance. init?(rawValue: String) { guard rawValue.count > 0 && rawValue.count <= 2 else { return nil } self.rawValue = rawValue symbolCharacterOne = rawValue.first symbolCharacterTwo = rawValue.count >= 2 ? rawValue[self.rawValue.index(after: self.rawValue.startIndex)] : nil } /// Creates a new instance with specified character. /// /// - Parameter character: `Character` to be used as `rawValue`. /// - Returns: A new `Symbol` instance. init(character: Character) { self.rawValue = String(character) symbolCharacterOne = character symbolCharacterTwo = nil } // MARK: - Instance functions /// Returns a boolean indicating whether the symbol matches given characters. /// This function currently requires three characters. /// Preceding and succeeding characters are used to check if the matched character is surrounded by a space. /// Succeeding character is also used to matching two character symbols. /// /// - Parameters: /// - precedingCharacter: Character preceding the character to match. /// - character: Character to match. /// - succeedingCharacter: Character succeeding the chracter to match. /// - Returns: Boolean indicating whether the symbol matches given characters. func matches(precedingCharacter: Character?, character: Character?, succeedingCharacter: Character?) -> Bool { guard let symbolCharacterOne = self.symbolCharacterOne else { return false } if length == 1 { switch (precedingCharacter, character, succeedingCharacter) { case (.some(" "), .some(symbolCharacterOne), .some(" ")): // If the symbol is only one character and is surrounded by empty spaces, treat it like a literal. break case (_, .some(symbolCharacterOne), _): return true default: break } } else if length == 2, let symbolCharacterTwo = self.symbolCharacterTwo { switch (precedingCharacter, character, succeedingCharacter) { case (_, .some(symbolCharacterOne), .some(symbolCharacterTwo)): return true default: break } } return false } } // MARK: - Protocol conformance // MARK: - Hashable extension Symbol: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } }
mit
76756d2105e82b5c0ffb423716221cc2
31.247706
114
0.619915
4.875173
false
false
false
false
jianghongbing/APIReferenceDemo
Swift/Syntax/Range.playground/Contents.swift
1
1671
//: Playground - noun: a place where people can play import UIKit //Range:定义一个半开区间(包含最小值,不包含最大值) //1.Range的初始化 let range = 1 ..< 10; //从1开始(包含1)到10(不包含10) let letterRange = "a" ..< "z" let doubleRange = 1.0 ..< 10.0 //2.range是否为空,和包含某个值 let emptyRange = 1.0 ..< 1.0 //两端的值是一样的区间为空区间 //let isEmpty = range.isEmpty let isEmpty = emptyRange.isEmpty //let isContains = doubleRange.contains(2.56) var isContains = letterRange.contains("b") isContains = doubleRange ~= 2.5 //同上面的contains的作用一样,判断某个值是否在区间中 //3.range的边界两端的值 let lowerBound = range.lowerBound let upperBound = range.upperBound //4.range的比较,只有类型一致的range才能互相比较,否则编译器会报错误 let anotherRange = 5 ..< 15 let isEqual = range == anotherRange let isNotEqual = range != anotherRange //5.range的交集,如果有交集,值就为它们的交集,如果没有,返回的结果为一个空集,开始和结束的值都为比较的range的和自己距离最近的那个值 var clampedRange = range.clamped(to: anotherRange) let rangeOne = 20 ..< 100 clampedRange = range.clamped(to: rangeOne) //6.overlap:判断两个range之间是否有重叠的部分,即相同的元素 var isOverlap = range.overlaps(anotherRange) isOverlap = range.overlaps(rangeOne) //7.countedableRange:可遍历的range,可以通过for循环来遍历range for i in range { print("i = \(i)") } //CloseRange:闭区间,包含两端的值,API和range的基本一致 let closeRange = 0 ... 10 for n in closeRange { print("n = \(n)") }
mit
d6b39b6600c31fddcf7be0410e8832e7
28.785714
73
0.741807
2.72549
false
false
false
false
wmcginty/Shifty
Sources/Shifty/Animators/ActionAnimator.swift
1
2387
// // ActionAnimator.swift // Shifty // // Created by William McGinty on 1/6/18. // import UIKit public class ActionAnimator: NSObject { // MARK: - Properties public let timingProvider: TimingProvider public let isInverted: Bool public let actionAnimator: UIViewPropertyAnimator // MARK: - Initializers public init(timingProvider: TimingProvider, isInverted: Bool = false) { self.timingProvider = timingProvider self.isInverted = isInverted self.actionAnimator = UIViewPropertyAnimator(duration: timingProvider.duration, timingParameters: timingProvider.parameters) } // MARK: - Interface open func inverted() -> ActionAnimator { return ActionAnimator(timingProvider: timingProvider, isInverted: !isInverted) } open func animate(_ actions: [Action], in container: UIView, completion: ((UIViewAnimatingPosition) -> Void)? = nil) { configureActionAnimator(for: actions, in: container, completion: completion) startAnimation() } } // MARK: - Helper private extension ActionAnimator { func configureActionAnimator(for actions: [Action], in container: UIView, completion: ((UIViewAnimatingPosition) -> Void)? = nil) { actions.forEach { action in let replicant = action.configuredReplicant(in: container) action.layoutContainerIfNeeded() actionAnimator.addAnimations { [weak self] in self?.animations(for: action, with: replicant) } actionAnimator.addCompletion { _ in action.cleanup(replicant: replicant) } } if isInverted { actionAnimator.isReversed = true actionAnimator.fractionComplete = 0 } completion.map(actionAnimator.addCompletion) } func animations(for action: Action, with replicant: UIView) { guard let keyframe = timingProvider.keyframe else { return action.animate(with: replicant) } UIView.animateKeyframes(withDuration: 0.0, delay: 0.0, options: [], animations: { UIView.addKeyframe(withRelativeStartTime: keyframe.startTime, relativeDuration: keyframe.duration) { action.animate(with: replicant) } }, completion: nil) } }
mit
a73bf4181ceee54e080228ab93f278fb
32.152778
135
0.637202
4.871429
false
false
false
false
itribs/RBCActionSheet
RBCActionSheet/RBCActionSheet.swift
1
22322
// // RBCActionSheet.swift // StickyNote // // Created by 黄泽新 on 16/5/4. // Copyright © 2016年 Ribs. All rights reserved. // import UIKit public typealias RBCActionSheetHandler = (actionSheet: RBCActionSheet) -> Void public enum RBCActionSheetAnimationType { case Bottom case Center } public enum RBCActionSheetButtonType { case Default case Destructive case Cancel } public struct RBCActionSheetButtonItem { var title: String var buttonType: RBCActionSheetButtonType } public struct RBCActionSheetItem { private var buttonItem: RBCActionSheetButtonItem? private var handler: RBCActionSheetHandler? private var customView: UIView? private var customViewMarginInsets = UIEdgeInsetsZero public init(buttonTitle: String, handler: RBCActionSheetHandler? = nil) { self.buttonItem = RBCActionSheetButtonItem(title: buttonTitle, buttonType: .Default) self.handler = handler } public init(buttonTitle: String, type: RBCActionSheetButtonType, handler: RBCActionSheetHandler? = nil) { self.buttonItem = RBCActionSheetButtonItem(title: buttonTitle, buttonType: type) self.handler = handler } public init(customView: UIView, marginInsets: UIEdgeInsets = UIEdgeInsetsZero) { self.customView = customView self.customViewMarginInsets = marginInsets } } public class RBCActionSheet: UIView { private static var showingActionSheets = [RBCActionSheet]() private static let cellIdentifier = "cell" private static let descLinesMax: Int = 5 private static let buttonItemHeight: CGFloat = 50 private static let titleViewHeight: CGFloat = 46 private var animating = false public var shadowOpacity: Float = 0.2 public var containerViewBackgroundColor: UIColor = UIColor.whiteColor() public var containerViewMarginInsets: UIEdgeInsets = UIEdgeInsetsMake(0, 15, 15, 15) public var backgroundTapDismiss: Bool { get { return self.backgroundView.userInteractionEnabled } set { self.backgroundView.userInteractionEnabled = newValue } } public var animationType = RBCActionSheetAnimationType.Bottom public var willShowHandler: ((actionSheet: RBCActionSheet) -> Void)? public var didShowHandler: ((actionSheet: RBCActionSheet) -> Void)? public var willHideHandler: ((actionSheet: RBCActionSheet, selectedItemIndex: Int) -> Void)? public var didHideHandler: ((actionSheet: RBCActionSheet, selectedItemIndex: Int) -> Void)? public convenience init(title: String, leftItem: RBCActionSheetItem? = nil, rightItem: RBCActionSheetItem? = nil) { self.init() self.titleItem = (title: title, leftItem: leftItem, rightItem: rightItem) self.titleLabel.text = title self.titleView.addSubview(self.titleLabel) if let item = leftItem { if let view = item.customView { self.titleView.addSubview(view) } else if let buttonItem = item.buttonItem { let button = UIButton(type: .Custom) button.titleLabel?.font = UIFont.systemFontOfSize(16) button.setTitle(buttonItem.title, forState: .Normal) button.setTitleColor(UIColor(red: 111/255, green: 111/255, blue: 111/255, alpha: 1), forState: .Normal) button.setTitleColor(UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1), forState: .Highlighted) button.addTarget(self, action: #selector(titleItemButtonTap(_:)), forControlEvents: .TouchUpInside) self.titleView.addSubview(button) self.titleLeftButton = button } } if let item = rightItem { if let view = item.customView { self.titleView.addSubview(view) } else if let buttonItem = item.buttonItem { let button = UIButton(type: .Custom) button.titleLabel?.font = UIFont.systemFontOfSize(16) button.setTitle(buttonItem.title, forState: .Normal) button.setTitleColor(UIColor(red: 111/255, green: 111/255, blue: 111/255, alpha: 1), forState: .Normal) button.setTitleColor(UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1), forState: .Highlighted) button.addTarget(self, action: #selector(titleItemButtonTap(_:)), forControlEvents: .TouchUpInside) self.titleView.addSubview(button) self.titleRightButton = button } } self.containerView.addSubview(self.titleView) } public convenience init(desc: String) { self.init() self.descLabel.text = desc self.containerView.addSubview(self.descLabel) } public init() { super.init(frame: CGRect.zero) self.addSubview(self.backgroundView) self.shadowView.addSubview(self.containerView) self.containerView.addSubview(self.itemTableView) self.addSubview(self.shadowView) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func layoutSubviews() { super.layoutSubviews() if self.animating { return } let descHeight = self.heightForDesc() let titleHeight = self.titleItem == nil ? 0.0 : RBCActionSheet.titleViewHeight let itemTableViewHeight = self.itemTableView.contentSize.height let containerViewHeight = titleHeight + descHeight + itemTableViewHeight let containerViewWidth = self.frame.width - self.containerViewMarginInsets.left - self.containerViewMarginInsets.right self.backgroundView.frame = self.bounds switch self.animationType { case .Center: self.shadowView.frame = CGRect(x: self.frame.width/2 - containerViewWidth/2, y: self.frame.height/2 - containerViewHeight/2, width: containerViewWidth, height: containerViewHeight) case .Bottom: self.shadowView.frame = CGRect(x: self.containerViewMarginInsets.left, y: self.frame.height - containerViewHeight - self.containerViewMarginInsets.bottom, width: containerViewWidth, height: containerViewHeight) } self.containerView.frame = self.shadowView.bounds if self.titleItem != nil { if let leftItem = self.titleItem?.leftItem { if let leftButton = self.titleLeftButton { leftButton.sizeToFit() leftButton.frame = CGRect(x: 0, y: 0, width: leftButton.frame.width + 30, height: titleHeight) } else if let view = leftItem.customView { view.frame.origin.x = 0 view.frame.origin.y = 0 } } if let rightItem = self.titleItem?.rightItem { if let rightButton = self.titleRightButton { rightButton.sizeToFit() rightButton.frame = CGRect(x: containerViewWidth - rightButton.frame.width - 30, y: 0, width: rightButton.frame.width + 30, height: titleHeight) } else if let view = rightItem.customView { view.frame.origin.x = containerViewWidth - view.frame.width view.frame.origin.y = 0 } } self.titleLabel.frame = CGRect(x: -1, y: 0, width: containerViewWidth + 1, height: titleHeight) self.titleView.frame = CGRect(x: 0, y: 0, width: containerViewWidth, height: titleHeight) } else { self.descLabel.frame = CGRect(x: 15, y: 15, width: containerViewWidth - 30, height: descHeight - 30) } self.itemTableView.frame = CGRect(x: 0, y: titleHeight + descHeight, width: self.containerView.frame.width, height: itemTableViewHeight) } public func addItemWithTitle(title: String, buttonType: RBCActionSheetButtonType, handler: RBCActionSheetHandler? = nil) { self.addItem(RBCActionSheetItem(buttonTitle: title, type: buttonType, handler: handler)) } public func addItemWithView(view: UIView, marginInsets: UIEdgeInsets = UIEdgeInsetsZero) { self.addItem(RBCActionSheetItem(customView: view, marginInsets: marginInsets)) } public func addItem(item: RBCActionSheetItem) { self.items.append(item) } public func show() { let viewController = RBCActionSheetController(actionSheet: self) self.originalWindow = UIApplication.sharedApplication().keyWindow self.originalWindow?.endEditing(true) self.actionsheetWindow = UIWindow(frame: UIScreen.mainScreen().bounds) self.actionsheetWindow?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.actionsheetWindow?.opaque = false self.actionsheetWindow?.windowLevel = UIWindowLevelStatusBar + CGFloat(UIApplication.sharedApplication().windows.count) self.actionsheetWindow?.rootViewController = viewController self.actionsheetWindow?.makeKeyAndVisible() self.layoutIfNeeded() self.backgroundView.alpha = 0 self.willShowHandler?(actionSheet: self) RBCActionSheet.showingActionSheets.append(self) switch self.animationType { case .Center: self.animating = true self.containerView.transform = CGAffineTransformMakeScale(0.5, 0.5) self.containerView.alpha = 0 UIView.animateWithDuration(0.2, delay: 0, options: .CurveEaseOut, animations: { self.containerView.transform = CGAffineTransformIdentity self.containerView.alpha = 1 self.backgroundView.alpha = 1 }) { (f) in self.animating = false self.didShowHandler?(actionSheet: self) } case .Bottom: self.animating = true self.containerView.transform = CGAffineTransformMakeTranslation(0, self.containerView.frame.height + self.containerViewMarginInsets.bottom) UIView.animateWithDuration(0.2, delay: 0, options: .CurveEaseOut, animations: { self.containerView.transform = CGAffineTransformIdentity self.backgroundView.alpha = 1 }) { (f) in self.animating = false self.didShowHandler?(actionSheet: self) } } } public func dismiss() { guard let actionsheetWindow = self.actionsheetWindow else { return } self.backgroundView.alpha = 1 let completed = { actionsheetWindow.hidden = true actionsheetWindow.removeFromSuperview() self.actionsheetWindow?.rootViewController = nil self.actionsheetWindow = nil self.originalWindow?.makeKeyWindow() self.originalWindow = nil self.animating = false if self.dismissWithIndex >= 0 && self.dismissWithIndex < self.items.count { let item = self.items[self.dismissWithIndex] item.handler?(actionSheet: self) } self.didHideHandler?(actionSheet: self, selectedItemIndex: self.dismissWithIndex) } self.willHideHandler?(actionSheet: self, selectedItemIndex: self.dismissWithIndex) if let index = RBCActionSheet.showingActionSheets.indexOf(self) { RBCActionSheet.showingActionSheets.removeAtIndex(index) } switch self.animationType { case .Center: self.animating = true self.containerView.transform = CGAffineTransformIdentity self.containerView.alpha = 1 UIView.animateWithDuration(0.2, delay: 0, options: .CurveEaseOut, animations: { self.containerView.transform = CGAffineTransformMakeScale(0.5, 0.5) self.containerView.alpha = 0 self.backgroundView.alpha = 0 }) { (f) in completed() } case .Bottom: self.animating = true self.containerView.transform = CGAffineTransformIdentity UIView.animateWithDuration(0.2, delay: 0, options: .CurveEaseIn, animations: { self.containerView.transform = CGAffineTransformMakeTranslation(0, self.containerView.frame.height + self.containerViewMarginInsets.bottom) self.backgroundView.alpha = 0 }) { (f) in completed() } } } public static func dismissAll() { for actionSheet in RBCActionSheet.showingActionSheets { actionSheet.dismiss() } } public func changeTitle(title: String) { if self.titleItem != nil { self.titleItem?.title = title self.titleLabel.text = title } } public func changeDesc(desc: String) { if self.titleItem == nil { self.descLabel.text = desc } } private func heightForDesc() -> CGFloat { if self.titleItem != nil { return 0 } let rect = (self.descLabel.text ?? "" as NSString).boundingRectWithSize(CGSize(width: self.frame.width - self.containerViewMarginInsets.left - self.containerViewMarginInsets.right - 30, height: self.descLabel.font.lineHeight * CGFloat(RBCActionSheet.descLinesMax)), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: [NSFontAttributeName: self.descLabel.font], context: nil) return rect.height + 30 } @objc private func titleItemButtonTap(sender: UIButton) { if sender === self.titleLeftButton { self.titleItem?.leftItem?.handler?(actionSheet: self) } else if sender === self.titleRightButton { self.titleItem?.rightItem?.handler?(actionSheet: self) } } private var dismissWithIndex: Int = -1 private var items = [RBCActionSheetItem]() private var titleItem: (title: String, leftItem: RBCActionSheetItem?, rightItem: RBCActionSheetItem?)? private var titleLeftButton: UIButton? private var titleRightButton: UIButton? private var actionsheetWindow: UIWindow? private var originalWindow: UIWindow? private lazy var backgroundView: UIView = { let view = UIView() view.backgroundColor = UIColor(white: 0, alpha: 0.5) view.alpha = 0 view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss))) return view }() private lazy var shadowView: UIView = { let view = UIView() view.layer.shadowOpacity = self.shadowOpacity view.layer.shadowRadius = 8 view.layer.shadowOffset = CGSizeZero view.layer.shadowColor = UIColor.blackColor().CGColor return view }() private lazy var containerView: UIView = { let view = UIView() view.layer.cornerRadius = 3 view.backgroundColor = self.containerViewBackgroundColor view.clipsToBounds = true return view }() private lazy var titleView: UIView = { let view = UIView() view.backgroundColor = self.containerViewBackgroundColor view.layer.borderWidth = 1 view.layer.borderColor = UIColor(white: 236.0/255.0, alpha: 1).CGColor return view }() private lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(20) label.textColor = UIColor(red: 111/255, green: 111/255, blue: 111/255, alpha: 1) label.textAlignment = .Center return label }() private lazy var descLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(16) label.textColor = UIColor(red: 111/255, green: 111/255, blue: 111/255, alpha: 1) label.numberOfLines = RBCActionSheet.descLinesMax label.textAlignment = .Center return label }() private lazy var itemTableView: UITableView = { let tableView = UITableView() tableView.delegate = self tableView.dataSource = self tableView.alwaysBounceVertical = false tableView.separatorStyle = .SingleLine tableView.separatorColor = UIColor(white: 236/255, alpha: 1) tableView.backgroundColor = self.containerViewBackgroundColor tableView.allowsSelection = false tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) return tableView }() } extension RBCActionSheet: UITableViewDelegate, UITableViewDataSource { public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let item = self.items[indexPath.row] if let view = item.customView { return view.frame.height + item.customViewMarginInsets.top + item.customViewMarginInsets.bottom } return RBCActionSheet.buttonItemHeight } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(RBCActionSheet.cellIdentifier)! cell.layoutMargins = UIEdgeInsetsZero cell.separatorInset = UIEdgeInsetsZero cell.preservesSuperviewLayoutMargins = false while (cell.contentView.subviews.count > 0) { cell.contentView.subviews[0].removeFromSuperview() } let item = self.items[indexPath.row] if let buttonItem = item.buttonItem { let button = UIButton(type: .Custom) button.frame = cell.contentView.bounds button.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] button.titleLabel?.font = UIFont.systemFontOfSize(18) button.titleLabel?.adjustsFontSizeToFitWidth = true button.titleLabel?.minimumScaleFactor = 0.5 button.setTitle(buttonItem.title, forState: .Normal) button.setTitleColor(UIColor(red: 111/255, green: 111/255, blue: 111/255, alpha: 1), forState: .Normal) if buttonItem.buttonType == .Cancel { button.setBackgroundImage(RBCActionSheet.imageWithColor(UIColor(white: 0.98, alpha: 1)), forState: .Normal) } else if buttonItem.buttonType == .Destructive { button.setTitleColor(UIColor(red: 220/255, green: 81/255, blue: 78/255, alpha: 1), forState: .Normal) } button.setBackgroundImage(RBCActionSheet.imageWithColor(UIColor(white: 0.9, alpha: 1)), forState: .Highlighted) button.tag = indexPath.row button.addTarget(self, action: #selector(itemButtonTap(_:)), forControlEvents: .TouchUpInside) cell.contentView.addSubview(button) } else if let view = item.customView { view.frame.origin.x = item.customViewMarginInsets.left view.frame.origin.y = item.customViewMarginInsets.top view.frame.size.width = tableView.frame.width - item.customViewMarginInsets.left - item.customViewMarginInsets.right cell.contentView.addSubview(view) } return cell } @objc private func itemButtonTap(sender: UIButton) { self.dismissWithIndex = sender.tag self.dismiss() } private static func imageWithColor(color: UIColor) -> UIImage { let rect = CGRectMake(0.0, 0.0, 1.0, 1.0); UIGraphicsBeginImageContext(rect.size); let context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, color.CGColor); CGContextFillRect(context, rect); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image } } private class RBCActionSheetController: UIViewController { private let actionSheet: RBCActionSheet init(actionSheet: RBCActionSheet) { self.actionSheet = actionSheet super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private override func loadView() { self.view = actionSheet } }
mit
4eb1e2b9f7f8bd08dc1b032c8011f1d1
39.061041
273
0.594945
5.355977
false
false
false
false
mlgoogle/wp
wp/Scenes/Login/RegisterVC.swift
1
8413
// // RegisterVC.swift // wp // // Created by 木柳 on 2016/12/25. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit import SVProgressHUD import DKNightVersion import Kingfisher class RegisterVC: BaseTableViewController { @IBOutlet weak var phoneView: UIView! @IBOutlet weak var phoneText: UITextField! @IBOutlet weak var codeText: UITextField! @IBOutlet weak var codeBtn: UIButton! @IBOutlet weak var nextBtn: UIButton! @IBOutlet weak var pwdText: UITextField! @IBOutlet weak var thindLoginView: UIView! @IBOutlet weak var qqBtn: UIButton! @IBOutlet weak var sinaBtn: UIButton! @IBOutlet weak var wechatBtn: UIButton! @IBOutlet weak var memberText: UITextField! @IBOutlet weak var agentText: UITextField! @IBOutlet weak var recommendText: UITextField! private var timer: Timer? private var codeTime = 60 private var voiceCodeTime = 60 //MARK: --LIFECYCLE override func viewDidLoad() { super.viewDidLoad() initUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) hideTabBarWithAnimationDuration() translucent(clear: false) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) SVProgressHUD.dismiss() } //MARK: --DATA //获取验证码 @IBAction func changeCodePicture(_ sender: UIButton) { if checkoutText(){ var type = 0 SVProgressHUD.showProgressMessage(ProgressMessage: "请稍候...") if UserModel.share().registerType == .wechatPass { type = 2 } sender.isEnabled = false AppAPIHelper.commen().verifycode(verifyType: Int64(type), phone: phoneText.text!, complete: { [weak self](result) -> ()? in SVProgressHUD.dismiss() if let strongSelf = self{ if let resultDic: [String: AnyObject] = result as? [String : AnyObject]{ if let token = resultDic[SocketConst.Key.vToken]{ UserModel.share().codeToken = token as! String } if let timestamp = resultDic[SocketConst.Key.timeStamp]{ UserModel.share().timestamp = timestamp as! Int } } strongSelf.codeBtn.isEnabled = false strongSelf.timer = Timer.scheduledTimer(timeInterval: 1, target: strongSelf, selector: #selector(strongSelf.updatecodeBtnTitle), userInfo: nil, repeats: true) } return nil }, error: { (error) in sender.isEnabled = true SVProgressHUD.showErrorMessage(error: error, duration: 2, complete: nil) return nil }) } } func updatecodeBtnTitle() { if codeTime == 0 { codeBtn.isEnabled = true codeBtn.setTitle("重新发送", for: .normal) codeTime = 60 timer?.invalidate() timer = nil codeBtn.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) return } codeBtn.isEnabled = false codeTime = codeTime - 1 let title: String = "\(codeTime)秒后重新发送" codeBtn.setTitle(title, for: .normal) codeBtn.backgroundColor = UIColor.init(rgbHex: 0xCCCCCC) } //注册 @IBAction func registerBtnTapped(_ sender: Any) { if checkoutText(){ if checkTextFieldEmpty([phoneText,pwdText,codeText,memberText,agentText]){ UserModel.share().code = codeText.text UserModel.share().phone = phoneText.text register() } } } func register() { let codeStr = AppConst.md5Key + "\(UserModel.share().timestamp)" + UserModel.share().code! let codeMd5Str = codeStr.md5() if codeMd5Str != UserModel.share().codeToken{ SVProgressHUD.showErrorMessage(ErrorMessage: "验证码错误", ForDuration: AppConst.progressDuration, completion: nil) return } //重置密码 if UserModel.share().registerType == .wechatPass { SVProgressHUD.showProgressMessage(ProgressMessage: "绑定中...") let password = ((pwdText.text! + AppConst.sha256Key).sha256()+UserModel.share().phone!).sha256() let param = BingPhoneParam() param.phone = phoneText.text! param.pwd = password param.vCode = UserModel.share().code! param.vToken = UserModel.share().codeToken param.timeStamp = UserModel.share().timestamp if memberText.text!.length() > 0 { param.memberId = Int(memberText.text!)! } param.agentId = agentText.text! param.recommend = recommendText.text! param.headerUrl = UserModel.share().wechatUserInfo[SocketConst.Key.headimgurl] ?? "" param.nickname = UserModel.share().wechatUserInfo[SocketConst.Key.nickname] ?? "" param.openid = UserModel.share().wechatUserInfo[SocketConst.Key.openid] ?? "" AppAPIHelper.login().bingPhone(param: param, complete: { [weak self](result) -> ()? in SVProgressHUD.dismiss() if result != nil { UserModel.share().fetchUserInfo(phone: self?.phoneText.text ?? "", pwd: self?.pwdText.text ?? "") }else{ SVProgressHUD.showErrorMessage(ErrorMessage: "绑定失败,请稍后再试", ForDuration: 1, completion: nil) } return nil }, error: errorBlockFunc()) return } //注册 let password = ((pwdText.text! + AppConst.sha256Key).sha256()+UserModel.share().phone!).sha256() let param = RegisterParam() param.phone = phoneText.text! param.pwd = password param.vCode = UserModel.share().code! param.vToken = UserModel.share().codeToken param.timeStamp = UserModel.share().timestamp if memberText.text!.length() > 0 { param.memberId = Int(memberText.text!)! } param.agentId = agentText.text! param.recommend = recommendText.text! SVProgressHUD.showProgressMessage(ProgressMessage: "注册中...") AppAPIHelper.login().register(model: param, complete: { [weak self](result) -> ()? in SVProgressHUD.dismiss() if result != nil { UserModel.share().fetchUserInfo(phone: self?.phoneText.text ?? "", pwd: self?.pwdText.text ?? "") }else{ SVProgressHUD.showErrorMessage(ErrorMessage: "注册失败,请稍后再试", ForDuration: 1, completion: nil) } return nil }, error: errorBlockFunc()) } func checkoutText() -> Bool { if checkTextFieldEmpty([phoneText]) { if isTelNumber(num: phoneText.text!) == false{ SVProgressHUD.showErrorMessage(ErrorMessage: "手机号格式错误", ForDuration: 1, completion: nil) return false } return true } return false } //MARK: --UI func initUI() { title = UserModel.share().registerType == .wechatPass ? "绑定手机号":"注册" let nextTitle = UserModel.share().registerType == .wechatPass ? "绑定":"注册" nextBtn.setTitle(nextTitle, for: .normal) phoneView.layer.borderWidth = 0.5 pwdText.placeholder = "请输入登录密码" phoneView.layer.borderColor = UIColor.init(rgbHex: 0xcccccc).cgColor codeBtn.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) nextBtn.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) qqBtn.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) wechatBtn.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) sinaBtn.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) } }
apache-2.0
279c263001f9d479f6eb2503782b26e3
40.21
178
0.592332
4.712407
false
false
false
false
tattn/ios-architectures
ios-architectures/MVC/View.swift
1
875
// // View.swift // ios-architectures // // Created by 田中 達也 on 2016/11/30. // Copyright © 2016年 tattn. All rights reserved. // import UIKit import Kingfisher class CatListCell: UICollectionViewCell { private let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) imageView.frame = bounds imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() imageView.kf.cancelDownloadTask() imageView.image = nil } func configure(with url: URL?) { imageView.kf.setImage(with: url) } }
mit
6ea99023b904f6e56f0659fe41452824
21.736842
59
0.616898
4.52356
false
false
false
false
arthurschiller/ARKit-LeapMotion
Mac App/LeapMotion Visualization/UI Components/Scenes.swift
1
5799
// // Scenes.swift // Mac App // // Created by Arthur Schiller on 22.08.17. // import SceneKit class LeapVisualizationSceneManager: NSObject, SCNSceneRendererDelegate { let sceneView: SCNView let scene: LeapVisualizationScene var leapHandRepresentation: LeapHandRepresentation? = nil { didSet { guard let data = leapHandRepresentation else { return } scene.updateHand(with: data) } } init(sceneView: SCNView, scene: LeapVisualizationScene) { self.sceneView = sceneView self.scene = scene super.init() commonInit() } fileprivate func commonInit() { setupScene() } fileprivate func setupScene() { sceneView.scene = scene sceneView.backgroundColor = NSColor(red:0.17, green:0.17, blue:0.18, alpha:1.0) sceneView.autoenablesDefaultLighting = false sceneView.allowsCameraControl = true sceneView.showsStatistics = true sceneView.preferredFramesPerSecond = 60 sceneView.antialiasingMode = .multisampling4X sceneView.delegate = self } } class LeapVisualizationScene: SCNScene { enum Mode { case showSkeleton case fingerPainting case moveAndRotate } var mode: Mode = .showSkeleton { didSet { updateMode() } } fileprivate var interactionBoxGeometry: SCNGeometry? { didSet { guard let geometry = interactionBoxGeometry else { return } interactionBoxNode.geometry = geometry } } fileprivate let cameraNode = SCNNode() fileprivate let interactionBoxNode: SCNNode = SCNNode() // Hand Visualization fileprivate lazy var geometryNode: SCNNode = { let geometry = SCNBox(width: 70, height: 2, length: 120, chamferRadius: 2)//SCNTorus(ringRadius: 20, pipeRadius: 2) geometry.firstMaterial?.diffuse.contents = NSColor.white.withAlphaComponent(0.8) let node = SCNNode(geometry: geometry) return node }() fileprivate lazy var handNode: LeapVisualizationHandNode = LeapVisualizationHandNode() // Particles fileprivate let particleNode = SCNNode() fileprivate lazy var particleTrail: SCNParticleSystem? = self.createTrail() override init() { super.init() commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() commonInit() } fileprivate func commonInit() { setupCamera() setupHandNode() addGeometryNode() addParticleTrailNode() updateMode() } fileprivate func setupCamera() { let cameraNode = SCNNode() let camera = SCNCamera() camera.zFar = 1500 cameraNode.camera = camera cameraNode.position = SCNVector3(x: 0, y: 400, z: 0) cameraNode.rotation = SCNVector4(x: 1, y: 0, z: 0, w: CGFloat(-90.degreesToRadians)) rootNode.addChildNode(cameraNode) } fileprivate func setupHandNode() { rootNode.addChildNode(handNode) } fileprivate func addGeometryNode() { rootNode.addChildNode(geometryNode) } fileprivate func addParticleTrailNode() { guard let particleSystem = particleTrail else { return } particleNode.addParticleSystem(particleSystem) rootNode.addChildNode(particleNode) } fileprivate func createTrail() -> SCNParticleSystem? { guard let trail = SCNParticleSystem(named: "FireParticleTrail.scnp", inDirectory: nil) else { return nil } return trail } fileprivate func updateMode() { switch mode { case .showSkeleton: toggle(node: handNode, show: true) [particleNode, geometryNode].forEach { toggle(node: $0, show: false) } case .fingerPainting: toggle(node: particleNode, show: true) toggle(node: handNode, show: true) toggle(node: geometryNode, show: false) case .moveAndRotate: toggle(node: geometryNode, show: true) [particleNode, handNode].forEach { toggle(node: $0, show: false) } } } } extension LeapVisualizationScene { func updateInteractionBox(withData data: LeapInteractionBoxRepresentation) { interactionBoxGeometry = SCNBox( width: data.width, height: data.height, length: data.depth, chamferRadius: 0 ) interactionBoxGeometry?.firstMaterial?.diffuse.contents = NSColor.white.withAlphaComponent(0.2) } func updateHand(with data: LeapHandRepresentation) { switch mode { case .showSkeleton: handNode.update(with: data) case .fingerPainting: handNode.update(with: data) particleNode.position = data.fingers[1].tipPosition case .moveAndRotate: geometryNode.position = data.position geometryNode.eulerAngles = SCNVector3( x: data.eulerAngles.x, y: data.eulerAngles.y, z: data.eulerAngles.z ) } } func toggleNodes(show: Bool) { let opacityAction = SCNAction.fadeOpacity(to: show ? 1 : 0, duration: 0.3) let nodes = [handNode, particleNode, geometryNode] nodes.forEach { $0.runAction(opacityAction) } } func toggle(node: SCNNode, show: Bool) { node.runAction(show ? SCNAction.unhide() : SCNAction.hide()) } }
mit
f95d81abee892bce3bd49e414549a1dc
28.738462
123
0.607346
4.722313
false
false
false
false
cszrs/refresher
Refresher/AutoToNextView.swift
1
2942
// // AutoToNextView.swift // RefresherDemo // // Created by 云之彼端 on 15/8/20. // Copyright (c) 2015年 cezr. All rights reserved. // import UIKit private var KVOContext = "RefresherKVOContext" private let ContentOffsetKeyPath = "contentOffset" public protocol AutoToNextViewDelegate { func autoToNextStart(view: AutoToNextView) } public class AutoToNextView: UIView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ private var scrollViewBouncesDefaultValue: Bool = false private var scrollViewInsetsDefaultValue: UIEdgeInsets = UIEdgeInsetsZero private var previousOffset: CGFloat = 0 // var delegate : AutoToNextViewDelegate? private var action: (() -> ()) = {} internal var next: Bool = false { didSet { if next { startLoading() } else { } } } init(frame: CGRect, action :(() -> ())) { self.action = action super.init(frame: frame) self.autoresizingMask = .FlexibleWidth } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: UIView methods override public func willMoveToSuperview(newSuperview: UIView!) { superview?.removeObserver(self, forKeyPath: ContentOffsetKeyPath, context: &KVOContext) if let scrollView = newSuperview as? UIScrollView { scrollView.addObserver(self, forKeyPath: ContentOffsetKeyPath, options: .Initial, context: &KVOContext) scrollViewBouncesDefaultValue = scrollView.bounces scrollViewInsetsDefaultValue = scrollView.contentInset } } deinit { var scrollView = superview as? UIScrollView scrollView?.removeObserver(self, forKeyPath: ContentOffsetKeyPath, context: &KVOContext) } //MARK: KVO methods override public func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<()>) { if (context == &KVOContext) { if let scrollView = superview as? UIScrollView where object as? NSObject == scrollView { if !next { if scrollView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height*0.8 { next = true } } } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } func startLoading() { action() } func endLoading() { next = false } }
mit
a39e080909f90f21e8aee6bd51ede1cc
27.192308
161
0.606753
5.245081
false
false
false
false
calgaryscientific/pureweb-ios-samples
Swift-Asteroids/Asteroids/Asteroids/AppDelegate.swift
1
4796
// // AppDelegate.swift // Asteroids // // Created by Jonathan Neitz on 2016-02-10. // Copyright © 2016 Calgary Scientific Inc. All rights reserved. // import UIKit import PureWeb @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { var appUrl: URL! var authenticationRequired = true; registerDefaultsFromSettingsBundle() if let url = launchOptions?[UIApplicationLaunchOptionsKey.url] as? URL { if var components = URLComponents(string: url.absoluteString) { let secureScheme = UserDefaults.standard.bool(forKey: "pureweb_collab_secure") components.scheme = "http"; if secureScheme { components.scheme = "https"; } appUrl = components.url!; print("Launching App From Incoming URL") authenticationRequired = false; } } else if let urlString = UserDefaults.standard.string(forKey: "pureweb_url") { if let url = URL(string:urlString) { appUrl = url authenticationRequired = true print("Launching App From Settings URL") } } //pass the authentication and app url if let masterViewController = self.window!.rootViewController as? ViewController { masterViewController.setupWithAppURL(appUrl, authenticationRequired: authenticationRequired); } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. if PWFramework.sharedInstance().client().isConnected { PWFramework.sharedInstance().client().disconnectSynchronous() } } func registerDefaultsFromSettingsBundle() { if let settingsBundle = Bundle.main.path(forResource: "Settings", ofType: "bundle") { if let settings = NSDictionary(contentsOfFile: settingsBundle + "/Root.plist") { if let preferences = settings.object(forKey: "PreferenceSpecifiers") as? NSArray { var defaultsToRegister = [String:AnyObject]() for value in preferences { if let prefSpecification = value as? NSDictionary { if let key = prefSpecification["Key"] as? String { let value = prefSpecification["DefaultValue"] as AnyObject defaultsToRegister[key] = value } } } UserDefaults.standard.register(defaults: defaultsToRegister) } } } } }
mit
b772664e98e5ef7a4eb58160be87f118
40.695652
285
0.607508
6.092757
false
false
false
false
ackratos/firefox-ios
Client/Frontend/Intro/IntroViewController.swift
2
16881
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit struct IntroViewControllerUX { static let Width = 375 static let Height = 667 static let NumberOfCards = 3 static let PagerCenterOffsetFromScrollViewBottom = 15 static let StartBrowsingButtonTitle = NSLocalizedString("Start Browsing", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo") static let StartBrowsingButtonColor = UIColor(rgb: 0x363B40) static let StartBrowsingButtonHeight = 56 static let StartBrowsingButtonFont = UIFont.systemFontOfSize(18) static let SignInButtonTitle = NSLocalizedString("Sign in to Firefox", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo") static let SignInButtonColor = UIColor(red: 0.259, green: 0.49, blue: 0.831, alpha: 1.0) static let SignInButtonHeight = 46 static let SignInButtonFont = UIFont.systemFontOfSize(16, weight: UIFontWeightMedium) static let SignInButtonCornerRadius = CGFloat(4) static let CardTextFont = UIFont.systemFontOfSize(16) static let CardTitleFont = UIFont.systemFontOfSize(18, weight: UIFontWeightBold) static let CardTextLineHeight = CGFloat(6) static let Card1Title = NSLocalizedString("Organize", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo") static let Card2Title = NSLocalizedString("Customize", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo") static let Card1Text = NSLocalizedString("Browse multiple Web pages at the same time with tabs.", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo") static let Card2Text = NSLocalizedString("Personalize your Firefox just the way you like in Settings.", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo") static let Card3Text = NSLocalizedString("Connect Firefox everywhere you use it.", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo") static let Card3TextOffsetFromCenter = 10 static let Card3ButtonOffsetFromCenter = 10 static let FadeDuration = 0.25 static let BackForwardButtonEdgeInset = 20 static let Card1Color = UIColor(rgb: 0xFFC81E) static let Card2Color = UIColor(rgb: 0x41B450) static let Card3Color = UIColor(rgb: 0x0096DD) } let IntroViewControllerSeenProfileKey = "IntroViewControllerSeen" protocol IntroViewControllerDelegate: class { func introViewControllerDidFinish(introViewController: IntroViewController) func introViewControllerDidRequestToLogin(introViewController: IntroViewController) } class IntroViewController: UIViewController, UIScrollViewDelegate { weak var delegate: IntroViewControllerDelegate? var slides = [UIImage]() var cards = [UIImageView]() var introViews = [UIView]() var startBrowsingButton: UIButton! var introView: UIView? var slideContainer: UIView! var pageControl: UIPageControl! var backButton: UIButton! var forwardButton: UIButton! var signInButton: UIButton! private var scrollView: IntroOverlayScrollView! var slideVerticalScaleFactor: CGFloat = 1.0 override func viewDidLoad() { view.backgroundColor = UIColor.whiteColor() // scale the slides down for iPhone 4S if view.frame.height <= 480 { slideVerticalScaleFactor = 1.33 } for i in 0..<IntroViewControllerUX.NumberOfCards { slides.append(UIImage(named: "slide\(i+1)")!) } startBrowsingButton = UIButton() startBrowsingButton.backgroundColor = IntroViewControllerUX.StartBrowsingButtonColor startBrowsingButton.setTitle(IntroViewControllerUX.StartBrowsingButtonTitle, forState: UIControlState.Normal) startBrowsingButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) startBrowsingButton.titleLabel?.font = IntroViewControllerUX.StartBrowsingButtonFont startBrowsingButton.addTarget(self, action: "SELstartBrowsing", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(startBrowsingButton) startBrowsingButton.snp_makeConstraints { (make) -> Void in make.left.right.bottom.equalTo(self.view) make.height.equalTo(IntroViewControllerUX.StartBrowsingButtonHeight) } scrollView = IntroOverlayScrollView() scrollView.backgroundColor = UIColor.clearColor() scrollView.delegate = self scrollView.bounces = false scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.contentSize = CGSize(width: scaledWidthOfSlide * CGFloat(IntroViewControllerUX.NumberOfCards), height: scaledHeightOfSlide) view.addSubview(scrollView) slideContainer = UIView() slideContainer.backgroundColor = IntroViewControllerUX.Card1Color for i in 0..<IntroViewControllerUX.NumberOfCards { let imageView = UIImageView(frame: CGRect(x: CGFloat(i)*scaledWidthOfSlide, y: 0, width: scaledWidthOfSlide, height: scaledHeightOfSlide)) imageView.image = slides[i] slideContainer.addSubview(imageView) } scrollView.addSubview(slideContainer) scrollView.snp_makeConstraints { (make) -> Void in make.left.right.top.equalTo(self.view) make.bottom.equalTo(startBrowsingButton.snp_top) } pageControl = UIPageControl() pageControl.pageIndicatorTintColor = UIColor.blackColor().colorWithAlphaComponent(0.3) pageControl.currentPageIndicatorTintColor = UIColor.blackColor() pageControl.numberOfPages = IntroViewControllerUX.NumberOfCards view.addSubview(pageControl) pageControl.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(self.scrollView) make.centerY.equalTo(self.startBrowsingButton.snp_top).offset(-IntroViewControllerUX.PagerCenterOffsetFromScrollViewBottom) } // Card1 let introView1 = UIView() introViews.append(introView1) addLabelsToIntroView(introView1, text: IntroViewControllerUX.Card1Text, title: IntroViewControllerUX.Card1Title) addForwardButtonToIntroView(introView1) // Card 2 let introView2 = UIView() introViews.append(introView2) addLabelsToIntroView(introView2, text: IntroViewControllerUX.Card2Text, title: IntroViewControllerUX.Card2Title) // Card 3 let introView3 = UIView() let label3 = UILabel() label3.numberOfLines = 0 label3.attributedText = attributedStringForLabel(IntroViewControllerUX.Card3Text) label3.font = IntroViewControllerUX.CardTextFont introView3.addSubview(label3) label3.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(introView3) make.bottom.equalTo(introView3.snp_centerY).offset(-IntroViewControllerUX.Card3TextOffsetFromCenter) make.width.equalTo(self.view.frame.width <= 320 ? 200 : 260) // TODO Talk to UX about small screen sizes } signInButton = UIButton() signInButton.backgroundColor = IntroViewControllerUX.SignInButtonColor signInButton.setTitle(IntroViewControllerUX.SignInButtonTitle, forState: .Normal) signInButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) signInButton.titleLabel?.font = IntroViewControllerUX.SignInButtonFont signInButton.layer.cornerRadius = IntroViewControllerUX.SignInButtonCornerRadius signInButton.clipsToBounds = true signInButton.addTarget(self, action: "SELlogin", forControlEvents: UIControlEvents.TouchUpInside) introView3.addSubview(signInButton) signInButton.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(introView3) make.top.equalTo(introView3.snp_centerY).offset(IntroViewControllerUX.Card3ButtonOffsetFromCenter) make.height.equalTo(IntroViewControllerUX.SignInButtonHeight) make.width.equalTo(self.view.frame.width <= 320 ? 200 : 260) // TODO Talk to UX about small screen sizes } introViews.append(introView3) // Add all the cards to the view, make them invisible with zero alpha for introView in introViews { introView.alpha = 0 self.view.addSubview(introView) introView.snp_makeConstraints { (make) -> Void in make.top.equalTo(self.slideContainer.snp_bottom) make.bottom.equalTo(self.startBrowsingButton.snp_top) make.left.right.equalTo(self.view) } } // Make whole screen scrollable by bringing the scrollview to the top view.bringSubviewToFront(scrollView) // Activate the first card setActiveIntroView(introViews[0], forPage: 0) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.snp_remakeConstraints { (make) -> Void in make.left.right.top.equalTo(self.view) make.bottom.equalTo(self.startBrowsingButton.snp_top) } for i in 0..<IntroViewControllerUX.NumberOfCards { if let imageView = slideContainer.subviews[i] as? UIImageView { imageView.frame = CGRect(x: CGFloat(i)*scaledWidthOfSlide, y: 0, width: scaledWidthOfSlide, height: scaledHeightOfSlide) imageView.contentMode = UIViewContentMode.ScaleAspectFit } } slideContainer.frame = CGRect(x: 0, y: 0, width: scaledWidthOfSlide * CGFloat(IntroViewControllerUX.NumberOfCards), height: scaledHeightOfSlide) scrollView.contentSize = CGSize(width: slideContainer.frame.width, height: slideContainer.frame.height) } override func prefersStatusBarHidden() -> Bool { return true } override func shouldAutorotate() -> Bool { return false } override func supportedInterfaceOrientations() -> Int { // This actually does the right thing on iPad where the modally // presented version happily rotates with the iPad orientation. return Int(UIInterfaceOrientationMask.Portrait.rawValue) } func SELstartBrowsing() { delegate?.introViewControllerDidFinish(self) } func SELback() { if introView == introViews[1] { setActiveIntroView(introViews[0], forPage: 0) scrollView.scrollRectToVisible(scrollView.subviews[0].frame, animated: true) pageControl.currentPage = 0 } else if introView == introViews[2] { setActiveIntroView(introViews[1], forPage: 1) scrollView.scrollRectToVisible(scrollView.subviews[1].frame, animated: true) pageControl.currentPage = 1 } } func SELforward() { if introView == introViews[0] { setActiveIntroView(introViews[1], forPage: 1) scrollView.scrollRectToVisible(scrollView.subviews[1].frame, animated: true) pageControl.currentPage = 1 } else if introView == introViews[1] { setActiveIntroView(introViews[2], forPage: 2) scrollView.scrollRectToVisible(scrollView.subviews[2].frame, animated: true) pageControl.currentPage = 2 } } func SELlogin() { delegate?.introViewControllerDidRequestToLogin(self) } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width) pageControl.currentPage = page setActiveIntroView(introViews[page], forPage: page) } func scrollViewDidScroll(scrollView: UIScrollView) { let maximumHorizontalOffset = scrollView.contentSize.width - CGRectGetWidth(scrollView.frame) let currentHorizontalOffset = scrollView.contentOffset.x var percentage = currentHorizontalOffset / maximumHorizontalOffset var startColor: UIColor, endColor: UIColor if(percentage < 0.5) { startColor = IntroViewControllerUX.Card1Color endColor = IntroViewControllerUX.Card2Color percentage = percentage * 2 } else { startColor = IntroViewControllerUX.Card2Color endColor = IntroViewControllerUX.Card3Color percentage = (percentage - 0.5) * 2 } slideContainer.backgroundColor = colorForPercentage(percentage, start: startColor, end: endColor) } private func colorForPercentage(percentage: CGFloat, start: UIColor, end: UIColor) -> UIColor { let s = start.components let e = end.components let newRed = (1.0 - percentage) * s.red + percentage * e.red let newGreen = (1.0 - percentage) * s.green + percentage * e.green let newBlue = (1.0 - percentage) * s.blue + percentage * e.blue return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0) } private func setActiveIntroView(newIntroView: UIView, forPage page: Int) { if introView != newIntroView { UIView.animateWithDuration(IntroViewControllerUX.FadeDuration, animations: { () -> Void in self.introView?.alpha = 0 self.introView = newIntroView newIntroView.alpha = 1.0 }, completion: { _ in if page == 2 { self.scrollView.signinButton = self.signInButton } else { self.scrollView.signinButton = nil } }) } } private var scaledWidthOfSlide: CGFloat { return view.frame.width } private var scaledHeightOfSlide: CGFloat { return (view.frame.width / slides[0].size.width) * slides[0].size.height / slideVerticalScaleFactor } private func addForwardButtonToIntroView(introView: UIView) { let button = UIImageView(image: UIImage(named: "intro-arrow")) introView.addSubview(button) button.snp_makeConstraints { (make) -> Void in make.centerY.equalTo(introView) make.right.equalTo(introView.snp_right).offset(-IntroViewControllerUX.BackForwardButtonEdgeInset) } } private func attributedStringForLabel(text: String) -> NSMutableAttributedString { var paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = IntroViewControllerUX.CardTextLineHeight paragraphStyle.alignment = .Center var string = NSMutableAttributedString(string: text) string.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, string.length)) return string } private func addLabelsToIntroView(introView: UIView, text: String, title: String = "") { let label = UILabel() label.numberOfLines = 0 label.attributedText = attributedStringForLabel(text) label.font = IntroViewControllerUX.CardTextFont introView.addSubview(label) label.snp_makeConstraints { (make) -> Void in make.center.equalTo(introView) make.width.equalTo(self.view.frame.width <= 320 ? 240 : 280) // TODO Talk to UX about small screen sizes } if !title.isEmpty { let titleLabel = UILabel() titleLabel.numberOfLines = 0 titleLabel.textAlignment = NSTextAlignment.Center titleLabel.text = title titleLabel.font = IntroViewControllerUX.CardTitleFont introView.addSubview(titleLabel) titleLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(introView) make.bottom.equalTo(label.snp_top) make.centerX.equalTo(introView) make.width.equalTo(self.view.frame.width <= 320 ? 240 : 280) // TODO Talk to UX about small screen sizes } } } } private class IntroOverlayScrollView: UIScrollView { weak var signinButton: UIButton? private override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { if let signinFrame = signinButton?.frame { let convertedFrame = convertRect(signinFrame, fromView: signinButton?.superview) if CGRectContainsPoint(convertedFrame, point) { return false } } return CGRectContainsPoint(CGRect(origin: self.frame.origin, size: CGSize(width: self.contentSize.width, height: self.frame.size.height)), point) } } extension UIColor { var components:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { var r:CGFloat = 0 var g:CGFloat = 0 var b:CGFloat = 0 var a:CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return (r,g,b,a) } }
mpl-2.0
2336c79ea4e38edae928f3eff2a52875
41.628788
165
0.683372
4.848076
false
false
false
false
gmilos/swift
test/attr/attr_specialize.swift
3
2959
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module | %FileCheck %s struct S<T> {} // Specialize freestanding functions with the correct number of concrete types. // ---------------------------------------------------------------------------- // CHECK: @_specialize(Int) @_specialize(Int) // CHECK: @_specialize(S<Int>) @_specialize(S<Int>) @_specialize(Int, Int) // expected-error{{generic type 'oneGenericParam' specialized with too many type parameters (got 2, but expected 1)}}, @_specialize(T) // expected-error{{use of undeclared type 'T'}} public func oneGenericParam<T>(_ t: T) -> T { return t } // CHECK: @_specialize(Int, Int) @_specialize(Int, Int) @_specialize(Int) // expected-error{{generic type 'twoGenericParams' specialized with too few type parameters (got 1, but expected 2)}}, public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) { return (t, u) } @_specialize(Int) // expected-error{{generic type 'nonGenericParam' specialized with too many type parameters (got 1, but expected 0)}} func nonGenericParam(x: Int) {} // Specialize contextual types. // ---------------------------- class G<T> { // CHECK: @_specialize(Int) @_specialize(Int) @_specialize(T) // expected-error{{cannot partially specialize a generic function}} @_specialize(S<T>) // expected-error{{cannot partially specialize a generic function}} @_specialize(Int, Int) // expected-error{{generic type 'noGenericParams' specialized with too many type parameters (got 2, but expected 1)}} func noGenericParams() {} // CHECK: @_specialize(Int, Float) @_specialize(Int, Float) // CHECK: @_specialize(Int, S<Int>) @_specialize(Int, S<Int>) @_specialize(Int) // expected-error{{generic type 'oneGenericParam' specialized with too few type parameters (got 1, but expected 2)}}, func oneGenericParam<U>(_ t: T, u: U) -> (U, T) { return (u, t) } } // Specialize with requirements. // ----------------------------- protocol Thing {} struct AThing : Thing {} // CHECK: @_specialize(AThing) @_specialize(AThing) @_specialize(Int) // expected-error{{argument type 'Int' does not conform to expected type 'Thing'}} func oneRequirement<T : Thing>(_ t: T) {} protocol HasElt { associatedtype Element } struct IntElement : HasElt { typealias Element = Int } struct FloatElement : HasElt { typealias Element = Float } @_specialize(FloatElement) @_specialize(IntElement) // expected-error{{'<T where T : HasElt, T.Element == Float> (T) -> ()' requires the types 'IntElement.Element' (aka 'Int') and 'Float' be equivalent}} func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {} class Base {} class Sub : Base {} class NonSub {} @_specialize(Sub) @_specialize(NonSub) // expected-error{{'<T where T : Base> (T) -> ()' requires that 'NonSub' inherit from 'Base'}} func superTypeRequirement<T : Base>(_ t: T) {}
apache-2.0
ea2ccef9781dc5c88eaf9940a190ca4a
35.9875
176
0.662386
3.680348
false
false
false
false
adilbenmoussa/ABCircularProgressView
ABCircularProgressViewExample/ABCircularProgressViewExample/ViewController.swift
1
1885
// // ViewController.swift // ABCircularProgressViewExample // // Created by A Ben Moussa on 11/9/15. // Copyright © 2015 Adil Ben Moussa. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var progressIndicatorView: ABCircularProgressView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func start(sender: AnyObject) { // Test the ABCircularProgressView component progressIndicatorView.startSpinning() let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC)); let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) dispatch_after(dispatchTime, dispatchQueue) { () -> Void in var progress: CGFloat = 0 for i in 0..<101 { progress = CGFloat(Float(i) / 100.0) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.progressIndicatorView.progress = progress }) usleep(10000) } } // Stop spinning in the main thread // dispatchTime = dispatch_time(DISPATCH_TIME_NOW, (Int64)(3 * NSEC_PER_SEC)); // dispatch_after(dispatchTime, dispatchQueue) { () -> Void in // dispatch_async(dispatch_get_main_queue(), { () -> Void in // self.progressIndicatorView.stopSpinning() // }) // } } @IBAction func changeProgress(sender: UISlider) { progressIndicatorView.progress = CGFloat(CGFloat(sender.value) / 100.0) } }
mit
f7d19e15320fef80108aa72bb67367f4
32.642857
102
0.611465
4.572816
false
false
false
false
rudkx/swift
SwiftCompilerSources/Sources/Optimizer/DataStructures/InstructionRange.swift
1
5326
//===--- InstructionRange.swift - a range of instructions -----------------===// // // 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 SIL /// A range of basic blocks. /// /// The `InstructionRange` defines a range from a dominating "begin" instruction to one or more "end" instructions. /// The range is "exclusive", which means that the "end" instructions are not part of the range. /// /// One or more "potential" end instructions can be inserted. /// Though, not all inserted instructions end up as "end" instructions. /// /// `InstructionRange` is useful for calculating the liferange of values. /// /// The `InstructionRange` is similar to a `BasicBlockRange`, but defines the range /// in a "finer" granularity, i.e. on instructions instead of blocks. /// `InstructionRange` uses an underlying `BasicBlockRange` to compute the /// involved blocks of the instruction range. /// /// There are several kind of instructions: /// * begin: it is a single instruction which dominates all instructions of the range /// * ends: all inserted instruction which are at the end of the range /// * exits: the first instructions of the exit blocks /// * interiors: all inserted instructions which are not end instructions. /// /// See also `BasicBlockRange` for more information. /// /// This type should be a move-only type, but unfortunately we don't have move-only /// types yet. Therefore it's needed to call `deinitialize()` explicitly to /// destruct this data structure, e.g. in a `defer {}` block. struct InstructionRange : CustomStringConvertible, CustomReflectable { /// The dominating begin instruction. let begin: Instruction /// The underlying block range. private(set) var blockRange: BasicBlockRange private var insertedInsts: Set<Instruction> init(begin beginInst: Instruction, _ context: PassContext) { self.begin = beginInst self.insertedInsts = Set<Instruction>() self.blockRange = BasicBlockRange(begin: beginInst.block, context) } /// Insert a potential end instruction. mutating func insert(_ inst: Instruction) { insertedInsts.insert(inst) blockRange.insert(inst.block) } /// Returns true if the exclusive range contains `inst`. func contains(_ inst: Instruction) -> Bool { let block = inst.block if !blockRange.inclusiveRangeContains(block) { return false } var inRange = false if blockRange.contains(block) { if block != blockRange.begin { return true } inRange = true } for i in block.instructions.reversed() { if i == inst { return inRange } if insertedInsts.contains(i) { inRange = true } if i == begin { return false } } fatalError("didn't find instruction in its block") } /// Returns true if the inclusive range contains `inst`. func inclusiveRangeContains (_ inst: Instruction) -> Bool { contains(inst) || insertedInsts.contains(inst) } /// Returns true if the range is valid and that's iff the begin instruction /// dominates all instructions of the range. var isValid: Bool { blockRange.isValid && // Check if there are any inserted instructions before the begin instruction in its block. !ReverseList(first: begin).dropFirst().contains { insertedInsts.contains($0) } } /// Returns the end instructions. var ends: LazyMapSequence<LazyFilterSequence<Stack<BasicBlock>>, Instruction> { blockRange.ends.map { $0.instructions.reversed().first(where: { insertedInsts.contains($0)})! } } /// Returns the exit instructions. var exits: LazyMapSequence<LazySequence<FlattenSequence< LazyMapSequence<Stack<BasicBlock>, LazyFilterSequence<SuccessorArray>>>>, Instruction> { blockRange.exits.lazy.map { $0.instructions.first! } } /// Returns the interior instructions. var interiors: LazySequence<FlattenSequence< LazyMapSequence<Stack<BasicBlock>, LazyFilterSequence<ReverseList<Instruction>>>>> { blockRange.inserted.lazy.flatMap { var include = blockRange.contains($0) return $0.instructions.reversed().lazy.filter { if insertedInsts.contains($0) { let isInterior = include include = true return isInterior } return false } } } var description: String { """ begin: \(begin) range: \(blockRange.range) ends: \(ends.map { $0.description }.joined(separator: "\n ")) exits: \(exits.map { $0.description }.joined(separator: "\n ")) interiors:\(interiors.map { $0.description }.joined(separator: "\n ")) """ } var customMirror: Mirror { Mirror(self, children: []) } /// TODO: once we have move-only types, make this a real deinit. mutating func deinitialize() { blockRange.deinitialize() } }
apache-2.0
083e6be13d6d526d52aac0aecc94504c
36.507042
115
0.657717
4.464376
false
false
false
false
broadwaylamb/Codable
Sources/Codable.swift
1
216777
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Codable //===----------------------------------------------------------------------===// #if swift(>=3.2) #else /// A type that can encode itself to an external representation. public protocol Encodable { /// Encodes this value into the given encoder. /// /// If the value fails to encode anything, `encoder` will encode an empty /// keyed container in its place. /// /// This function throws an error if any values are invalid for the given /// encoder's format. /// /// - Parameter encoder: The encoder to write data to. func encode(to encoder: Encoder) throws } /// A type that can decode itself from an external representation. public protocol Decodable { /// Creates a new instance by decoding from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or /// if the data read is corrupted or otherwise invalid. /// /// - Parameter decoder: The decoder to read data from. init(from decoder: Decoder) throws } /// A type that can convert itself into and out of an external representation. public typealias Codable = Encodable & Decodable //===----------------------------------------------------------------------===// // CodingKey //===----------------------------------------------------------------------===// /// A type that can be used as a key for encoding and decoding. public protocol CodingKey { /// The string to use in a named collection (e.g. a string-keyed dictionary). var stringValue: String { get } /// Initializes `self` from a string. /// /// - parameter stringValue: The string value of the desired key. /// - returns: An instance of `Self` from the given string, or `nil` if the given string does not correspond to any instance of `Self`. init?(stringValue: String) /// The int to use in an indexed collection (e.g. an int-keyed dictionary). var intValue: Int? { get } /// Initializes `self` from an integer. /// /// - parameter intValue: The integer value of the desired key. /// - returns: An instance of `Self` from the given integer, or `nil` if the given integer does not correspond to any instance of `Self`. init?(intValue: Int) } extension CodingKey where Self: RawRepresentable, Self.RawValue == String { public var stringValue: String { return rawValue } public init?(stringValue: String) { self.init(rawValue: stringValue) } public var intValue: Int? { return nil } public init?(intValue: Int) { return nil } } extension CodingKey where Self: RawRepresentable, Self.RawValue == Int { public var stringValue: String { return String(describing: self) } public init?(stringValue: String) { return nil } public var intValue: Int? { return rawValue } public init?(intValue: Int) { self.init(rawValue: intValue) } } //===----------------------------------------------------------------------===// // Encoder & Decoder //===----------------------------------------------------------------------===// /// A type that can encode values into a native format for external representation. public protocol Encoder { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Any contextual information set by the user for encoding. var userInfo: [CodingUserInfoKey : Any] { get } /// Returns an encoding container appropriate for holding multiple values keyed by the given key type. /// /// - parameter type: The key type to use for the container. /// - returns: A new keyed encoding container. /// - precondition: May not be called after a prior `self.unkeyedContainer()` call. /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> /// Returns an encoding container appropriate for holding multiple unkeyed values. /// /// - returns: A new empty unkeyed container. /// - precondition: May not be called after a prior `self.container(keyedBy:)` call. /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. func unkeyedContainer() -> UnkeyedEncodingContainer /// Returns an encoding container appropriate for holding a single primitive value. /// /// - returns: A new empty single value container. /// - precondition: May not be called after a prior `self.container(keyedBy:)` call. /// - precondition: May not be called after a prior `self.unkeyedContainer()` call. /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. func singleValueContainer() -> SingleValueEncodingContainer } /// A type that can decode values from a native format into in-memory representations. public protocol Decoder { /// The path of coding keys taken to get to this point in decoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Any contextual information set by the user for decoding. var userInfo: [CodingUserInfoKey : Any] { get } /// Returns the data stored in `self` as represented in a container keyed by the given key type. /// /// - parameter type: The key type to use for the container. /// - returns: A keyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container. func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> /// Returns the data stored in `self` as represented in a container appropriate for holding values with no keys. /// /// - returns: An unkeyed container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container. func unkeyedContainer() throws -> UnkeyedDecodingContainer /// Returns the data stored in `self` as represented in a container appropriate for holding a single primitive value. /// /// - returns: A single value container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a single value container. func singleValueContainer() throws -> SingleValueDecodingContainer } //===----------------------------------------------------------------------===// // Keyed Encoding Containers //===----------------------------------------------------------------------===// /// A type that provides a view into an encoder's storage and is used to hold /// the encoded properties of an encodable type in a keyed manner. /// /// Encoders should provide types conforming to /// `KeyedEncodingContainerProtocol` for their format. public protocol KeyedEncodingContainerProtocol { associatedtype Key : CodingKey /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Encodes a null value for the given key. /// /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if a null value is invalid in the current context for this format. mutating func encodeNil(forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Bool, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Int, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Int8, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Int16, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Int32, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Int64, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: UInt, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: UInt8, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: UInt16, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: UInt32, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: UInt64, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Float, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Double, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: String, forKey key: Key) throws /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws /// Encodes a reference to the given object only if it is encoded unconditionally elsewhere in the payload (previously, or in the future). /// /// For `Encoder`s which don't support this feature, the default implementation encodes the given object unconditionally. /// /// - parameter object: The object to encode. /// - parameter key: The key to associate the object with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeConditional<T : AnyObject & Encodable>(_ object: T, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeIfPresent<T : Encodable>(_ value: T?, forKey key: Key) throws /// Stores a keyed encoding container for the given key and returns it. /// /// - parameter keyType: The key type to use for the container. /// - parameter key: The key to encode the container for. /// - returns: A new keyed encoding container. mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> /// Stores an unkeyed encoding container for the given key and returns it. /// /// - parameter key: The key to encode the container for. /// - returns: A new unkeyed encoding container. mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer /// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container. /// /// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`. /// /// - returns: A new `Encoder` to pass to `super.encode(to:)`. mutating func superEncoder() -> Encoder /// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container. /// /// - parameter key: The key to encode `super` for. /// - returns: A new `Encoder` to pass to `super.encode(to:)`. mutating func superEncoder(forKey key: Key) -> Encoder } // An implementation of _KeyedEncodingContainerBase and _KeyedEncodingContainerBox are given at the bottom of this file. /// A concrete container that provides a view into an encoder's storage, making /// the encoded properties of an encodable type accessible by keys. public struct KeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol { public typealias Key = K /// The container for the concrete encoder. The type is _*Base so that it's generic on the key type. @_versioned internal var _box: _KeyedEncodingContainerBase<Key> /// Initializes `self` with the given container. /// /// - parameter container: The container to hold. public init<Container : KeyedEncodingContainerProtocol>(_ container: Container) where Container.Key == Key { _box = _KeyedEncodingContainerBox(container) } /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. public var codingPath: [CodingKey] { return _box.codingPath } /// Encodes a null value for the given key. /// /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if a null value is invalid in the current context for this format. public mutating func encodeNil(forKey key: Key) throws { try _box.encodeNil(forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: Bool, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: Int, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: Int8, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: Int16, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: Int32, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: Int64, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: UInt, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: UInt8, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: UInt16, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: UInt32, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: UInt64, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: Float, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: Double, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode(_ value: String, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes the given value for the given key. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws { try _box.encode(value, forKey: key) } /// Encodes a reference to the given object only if it is encoded unconditionally elsewhere in the payload (previously, or in the future). /// /// For `Encoder`s which don't support this feature, the default implementation encodes the given object unconditionally. /// /// - parameter object: The object to encode. /// - parameter key: The key to associate the object with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeConditional<T : AnyObject & Encodable>(_ object: T, forKey key: Key) throws { try _box.encodeConditional(object, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Encodes the given value for the given key if it is not `nil`. /// /// - parameter value: The value to encode. /// - parameter key: The key to associate the value with. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. public mutating func encodeIfPresent<T : Encodable>(_ value: T?, forKey key: Key) throws { try _box.encodeIfPresent(value, forKey: key) } /// Stores a keyed encoding container for the given key and returns it. /// /// - parameter keyType: The key type to use for the container. /// - parameter key: The key to encode the container for. /// - returns: A new keyed encoding container. public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { return _box.nestedContainer(keyedBy: NestedKey.self, forKey: key) } /// Stores an unkeyed encoding container for the given key and returns it. /// /// - parameter key: The key to encode the container for. /// - returns: A new unkeyed encoding container. public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { return _box.nestedUnkeyedContainer(forKey: key) } /// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container. /// /// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`. /// /// - returns: A new `Encoder` to pass to `super.encode(to:)`. public mutating func superEncoder() -> Encoder { return _box.superEncoder() } /// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container. /// /// - parameter key: The key to encode `super` for. /// - returns: A new `Encoder` to pass to `super.encode(to:)`. public mutating func superEncoder(forKey key: Key) -> Encoder { return _box.superEncoder(forKey: key) } } /// A type that provides a view into a decoder's storage and is used to hold /// the encoded properties of a decodable type in a keyed manner. /// /// Decoders should provide types conforming to `UnkeyedDecodingContainer` for /// their format. public protocol KeyedDecodingContainerProtocol { associatedtype Key : CodingKey /// The path of coding keys taken to get to this point in decoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// All the keys the `Decoder` has for this container. /// /// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type. var allKeys: [Key] { get } /// Returns whether the `Decoder` contains a value associated with the given key. /// /// The value associated with the given key may be a null value as appropriate for the data format. /// /// - parameter key: The key to search for. /// - returns: Whether the `Decoder` has an entry for the given key. func contains(_ key: Key) -> Bool /// Decodes a null value for the given key. /// /// - parameter key: The key that the decoded value is associated with. /// - returns: Whether the encountered value was null. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. func decodeNil(forKey key: Key) throws -> Bool /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Int.Type, forKey key: Key) throws -> Int /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Float.Type, forKey key: Key) throws -> Float /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: Double.Type, forKey key: Key) throws -> Double /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode(_ type: String.Type, forKey key: Key) throws -> String /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? /// Returns the data stored for the given key as represented in a container keyed by the given key type. /// /// - parameter type: The key type to use for the container. /// - parameter key: The key that the nested container is associated with. /// - returns: A keyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container. func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> /// Returns the data stored for the given key as represented in an unkeyed container. /// /// - parameter key: The key that the nested container is associated with. /// - returns: An unkeyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container. func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer /// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key. /// /// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`. /// /// - returns: A new `Decoder` to pass to `super.init(from:)`. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key. func superDecoder() throws -> Decoder /// Returns a `Decoder` instance for decoding `super` from the container associated with the given key. /// /// - parameter key: The key to decode `super` for. /// - returns: A new `Decoder` to pass to `super.init(from:)`. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. func superDecoder(forKey key: Key) throws -> Decoder } // An implementation of _KeyedDecodingContainerBase and _KeyedDecodingContainerBox are given at the bottom of this file. /// A concrete container that provides a view into an decoder's storage, making /// the encoded properties of an decodable type accessible by keys. public struct KeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol { public typealias Key = K /// The container for the concrete decoder. The type is _*Base so that it's generic on the key type. @_versioned internal var _box: _KeyedDecodingContainerBase<Key> /// Initializes `self` with the given container. /// /// - parameter container: The container to hold. public init<Container : KeyedDecodingContainerProtocol>(_ container: Container) where Container.Key == Key { _box = _KeyedDecodingContainerBox(container) } /// The path of coding keys taken to get to this point in decoding. /// A `nil` value indicates an unkeyed container. public var codingPath: [CodingKey] { return _box.codingPath } /// All the keys the `Decoder` has for this container. /// /// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type. public var allKeys: [Key] { return _box.allKeys } /// Returns whether the `Decoder` contains a value associated with the given key. /// /// The value associated with the given key may be a null value as appropriate for the data format. /// /// - parameter key: The key to search for. /// - returns: Whether the `Decoder` has an entry for the given key. public func contains(_ key: Key) -> Bool { return _box.contains(key) } /// Decodes a null value for the given key. /// /// - parameter key: The key that the decoded value is associated with. /// - returns: Whether the encountered value was null. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. public func decodeNil(forKey key: Key) throws -> Bool { return try _box.decodeNil(forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return try _box.decode(Bool.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return try _box.decode(Int.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return try _box.decode(Int8.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return try _box.decode(Int16.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return try _box.decode(Int32.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return try _box.decode(Int64.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return try _box.decode(UInt.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return try _box.decode(UInt8.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return try _box.decode(UInt16.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return try _box.decode(UInt32.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return try _box.decode(UInt64.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return try _box.decode(Float.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return try _box.decode(Double.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode(_ type: String.Type, forKey key: Key) throws -> String { return try _box.decode(String.self, forKey: key) } /// Decodes a value of the given type for the given key. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { return try _box.decode(T.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? { return try _box.decodeIfPresent(Bool.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? { return try _box.decodeIfPresent(Int.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? { return try _box.decodeIfPresent(Int8.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? { return try _box.decodeIfPresent(Int16.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? { return try _box.decodeIfPresent(Int32.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? { return try _box.decodeIfPresent(Int64.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? { return try _box.decodeIfPresent(UInt.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? { return try _box.decodeIfPresent(UInt8.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? { return try _box.decodeIfPresent(UInt16.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? { return try _box.decodeIfPresent(UInt32.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? { return try _box.decodeIfPresent(UInt64.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? { return try _box.decodeIfPresent(Float.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? { return try _box.decodeIfPresent(Double.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? { return try _box.decodeIfPresent(String.self, forKey: key) } /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. public func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? { return try _box.decodeIfPresent(T.self, forKey: key) } /// Returns the data stored for the given key as represented in a container keyed by the given key type. /// /// - parameter type: The key type to use for the container. /// - parameter key: The key that the nested container is associated with. /// - returns: A keyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container. public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { return try _box.nestedContainer(keyedBy: NestedKey.self, forKey: key) } /// Returns the data stored for the given key as represented in an unkeyed container. /// /// - parameter key: The key that the nested container is associated with. /// - returns: An unkeyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container. public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { return try _box.nestedUnkeyedContainer(forKey: key) } /// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key. /// /// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`. /// /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key. public func superDecoder() throws -> Decoder { return try _box.superDecoder() } /// Returns a `Decoder` instance for decoding `super` from the container associated with the given key. /// /// - parameter key: The key to decode `super` for. /// - returns: A new `Decoder` to pass to `super.init(from:)`. /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key. public func superDecoder(forKey key: Key) throws -> Decoder { return try _box.superDecoder(forKey: key) } } //===----------------------------------------------------------------------===// // Unkeyed Encoding Containers //===----------------------------------------------------------------------===// /// A type that provides a view into an encoder's storage and is used to hold /// the encoded properties of an encodable type sequentially, without keys. /// /// Encoders should provide types conforming to `UnkeyedEncodingContainer` for /// their format. public protocol UnkeyedEncodingContainer { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// The number of elements encoded into the container. var count: Int { get } /// Encodes a null value. /// /// - throws: `EncodingError.invalidValue` if a null value is invalid in the current context for this format. mutating func encodeNil() throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Bool) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Int) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Int8) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Int16) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Int32) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Int64) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: UInt) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: UInt8) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: UInt16) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: UInt32) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: UInt64) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Float) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: Double) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode(_ value: String) throws /// Encodes the given value. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encode<T : Encodable>(_ value: T) throws /// Encodes a reference to the given object only if it is encoded unconditionally elsewhere in the payload (previously, or in the future). /// /// For `Encoder`s which don't support this feature, the default implementation encodes the given object unconditionally. /// /// For formats which don't support this feature, the default implementation encodes the given object unconditionally. /// /// - parameter object: The object to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. mutating func encodeConditional<T : AnyObject & Encodable>(_ object: T) throws /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Bool /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Int /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Int8 /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Int16 /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Int32 /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Int64 /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == UInt /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == UInt8 /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == UInt16 /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == UInt32 /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == UInt64 /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Float /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Double /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == String /// Encodes the elements of the given sequence. /// /// - parameter sequence: The sequences whose contents to encode. /// - throws: An error if any of the contained values throws an error. mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element : Encodable /// Encodes a nested container keyed by the given type and returns it. /// /// - parameter keyType: The key type to use for the container. /// - returns: A new keyed encoding container. mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> /// Encodes an unkeyed encoding container and returns it. /// /// - returns: A new unkeyed encoding container. mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer /// Encodes a nested container and returns an `Encoder` instance for encoding `super` into that container. /// /// - returns: A new `Encoder` to pass to `super.encode(to:)`. mutating func superEncoder() -> Encoder } /// A type that provides a view into a decoder's storage and is used to hold /// the encoded properties of a decodable type sequentially, without keys. /// /// Decoders should provide types conforming to `UnkeyedDecodingContainer` for /// their format. public protocol UnkeyedDecodingContainer { /// The path of coding keys taken to get to this point in decoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Returns the number of elements (if known) contained within this container. var count: Int? { get } /// Returns whether there are no more elements left to be decoded in the container. var isAtEnd: Bool { get } /// The current decoding index of the container (i.e. the index of the next element to be decoded.) /// Incremented after every successful decode call. var currentIndex: Int { get } /// Decodes a null value. /// /// If the value is not null, does not increment currentIndex. /// /// - returns: Whether the encountered value was null. /// - throws: `DecodingError.valueNotFound` if there are no more values to decode. mutating func decodeNil() throws -> Bool /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Bool.Type) throws -> Bool /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Int.Type) throws -> Int /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Int8.Type) throws -> Int8 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Int16.Type) throws -> Int16 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Int32.Type) throws -> Int32 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Int64.Type) throws -> Int64 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: UInt.Type) throws -> UInt /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: UInt8.Type) throws -> UInt8 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: UInt16.Type) throws -> UInt16 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: UInt32.Type) throws -> UInt32 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: UInt64.Type) throws -> UInt64 /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Float.Type) throws -> Float /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: Double.Type) throws -> Double /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode(_ type: String.Type) throws -> String /// Decodes a value of the given type. /// /// - parameter type: The type of value to decode. /// - returns: A value of the requested type, if present for the given key and convertible to the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func decode<T : Decodable>(_ type: T.Type) throws -> T /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Int.Type) throws -> Int? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Float.Type) throws -> Float? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: Double.Type) throws -> Double? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent(_ type: String.Type) throws -> String? /// Decodes a value of the given type, if present. /// /// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`. /// /// - parameter type: The type of value to decode. /// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type. mutating func decodeIfPresent<T : Decodable>(_ type: T.Type) throws -> T? /// Decodes a nested container keyed by the given type. /// /// - parameter type: The key type to use for the container. /// - returns: A keyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container. mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> /// Decodes an unkeyed nested container. /// /// - returns: An unkeyed decoding container view into `self`. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container. mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer /// Decodes a nested container and returns a `Decoder` instance for decoding `super` from that container. /// /// - returns: A new `Decoder` to pass to `super.init(from:)`. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null, or of there are no more values to decode. mutating func superDecoder() throws -> Decoder } //===----------------------------------------------------------------------===// // Single Value Encoding Containers //===----------------------------------------------------------------------===// /// A container that can support the storage and direct encoding of a single /// non-keyed value. public protocol SingleValueEncodingContainer { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Encodes a null value. /// /// - throws: `EncodingError.invalidValue` if a null value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encodeNil() throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: Bool) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: Int) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: Int8) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: Int16) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: Int32) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: Int64) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: UInt) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: UInt8) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: UInt16) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: UInt32) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: UInt64) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: Float) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: Double) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: String) throws /// Encodes a single value of the given type. /// /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode<T : Encodable>(_ value: T) throws } /// A `SingleValueDecodingContainer` is a container which can support the storage and direct decoding of a single non-keyed value. public protocol SingleValueDecodingContainer { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Decodes a null value. /// /// - returns: Whether the encountered value was null. func decodeNil() -> Bool /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Bool.Type) throws -> Bool /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Int.Type) throws -> Int /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Int8.Type) throws -> Int8 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Int16.Type) throws -> Int16 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Int32.Type) throws -> Int32 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Int64.Type) throws -> Int64 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: UInt.Type) throws -> UInt /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: UInt8.Type) throws -> UInt8 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: UInt16.Type) throws -> UInt16 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: UInt32.Type) throws -> UInt32 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: UInt64.Type) throws -> UInt64 /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Float.Type) throws -> Float /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Double.Type) throws -> Double /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: String.Type) throws -> String /// Decodes a single value of the given type. /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode<T : Decodable>(_ type: T.Type) throws -> T } //===----------------------------------------------------------------------===// // User Info //===----------------------------------------------------------------------===// /// A user-defined key for providing context during encoding and decoding. public struct CodingUserInfoKey : RawRepresentable, Equatable, Hashable { public typealias RawValue = String /// The key's string value. public let rawValue: String /// Initializes `self` with the given raw value. /// /// - parameter rawValue: The value of the key. public init?(rawValue: String) { self.rawValue = rawValue } /// Returns whether the given keys are equal. /// /// - parameter lhs: The key to compare against. /// - parameter rhs: The key to compare with. public static func ==(_ lhs: CodingUserInfoKey, _ rhs: CodingUserInfoKey) -> Bool { return lhs.rawValue == rhs.rawValue } /// The key's hash value. public var hashValue: Int { return self.rawValue.hashValue } } //===----------------------------------------------------------------------===// // Errors //===----------------------------------------------------------------------===// /// An error that occurs during the encoding of a value. public enum EncodingError : Error { /// The context in which the error occurred. public struct Context { /// The path of `CodingKey`s taken to get to the point of the failing encode call. public let codingPath: [CodingKey] /// A description of what went wrong, for debugging purposes. public let debugDescription: String /// The underlying error which caused this error, if any. public let underlyingError: Error? /// Initializes `self` with the given path of `CodingKey`s and a description of what went wrong. /// /// - parameter codingPath: The path of `CodingKey`s taken to get to the point of the failing encode call. /// - parameter debugDescription: A description of what went wrong, for debugging purposes. /// - parameter underlyingError: The underlying error which caused this error, if any. public init(codingPath: [CodingKey], debugDescription: String, underlyingError: Error? = nil) { self.codingPath = codingPath self.debugDescription = debugDescription self.underlyingError = underlyingError } } /// `.invalidValue` indicates that an `Encoder` or its containers could not encode the given value. /// /// Contains the attempted value, along with context for debugging. case invalidValue(Any, Context) // MARK: - NSError Bridging // CustomNSError bridging applies only when the CustomNSError conformance is applied in the same module as the declared error type. // Since we cannot access CustomNSError (which is defined in Foundation) from here, we can use the "hidden" entry points. public var _domain: String { return "NSCocoaErrorDomain" } public var _code: Int { switch self { case .invalidValue(_, _): return 4866 } } public var _userInfo: AnyObject? { // The error dictionary must be returned as an AnyObject. We can do this only on platforms with bridging, unfortunately. #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) let context: Context switch self { case .invalidValue(_, let c): context = c } var userInfo: [String : Any] = [ "NSCodingPath": context.codingPath, "NSDebugDescription": context.debugDescription ] if let underlyingError = context.underlyingError { userInfo["NSUnderlyingError"] = underlyingError } return userInfo as AnyObject #else return nil #endif } } /// An error that occurs during the decoding of a value. public enum DecodingError : Error { /// The context in which the error occurred. public struct Context { /// The path of `CodingKey`s taken to get to the point of the failing decode call. public let codingPath: [CodingKey] /// A description of what went wrong, for debugging purposes. public let debugDescription: String /// The underlying error which caused this error, if any. public let underlyingError: Error? /// Initializes `self` with the given path of `CodingKey`s and a description of what went wrong. /// /// - parameter codingPath: The path of `CodingKey`s taken to get to the point of the failing decode call. /// - parameter debugDescription: A description of what went wrong, for debugging purposes. /// - parameter underlyingError: The underlying error which caused this error, if any. public init(codingPath: [CodingKey], debugDescription: String, underlyingError: Error? = nil) { self.codingPath = codingPath self.debugDescription = debugDescription self.underlyingError = underlyingError } } /// `.typeMismatch` indicates that a value of the given type could not be decoded because it did not match the type of what was found in the encoded payload. /// /// Contains the attempted type, along with context for debugging. case typeMismatch(Any.Type, Context) /// `.valueNotFound` indicates that a non-optional value of the given type was expected, but a null value was found. /// /// Contains the attempted type, along with context for debugging. case valueNotFound(Any.Type, Context) /// `.keyNotFound` indicates that a `KeyedDecodingContainer` was asked for an entry for the given key, but did not contain one. /// /// Contains the attempted key, along with context for debugging. case keyNotFound(CodingKey, Context) /// `.dataCorrupted` indicates that the data is corrupted or otherwise invalid. /// /// Contains context for debugging. case dataCorrupted(Context) // MARK: - NSError Bridging // CustomNSError bridging applies only when the CustomNSError conformance is applied in the same module as the declared error type. // Since we cannot access CustomNSError (which is defined in Foundation) from here, we can use the "hidden" entry points. public var _domain: String { return "NSCocoaErrorDomain" } public var _code: Int { switch self { case .keyNotFound(_, _): fallthrough case .valueNotFound(_, _): return 4865 case .typeMismatch(_, _): fallthrough case .dataCorrupted(_): return 4864 } } public var _userInfo: AnyObject? { // The error dictionary must be returned as an AnyObject. We can do this only on platforms with bridging, unfortunately. #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) let context: Context switch self { case .keyNotFound(_, let c): context = c case .valueNotFound(_, let c): context = c case .typeMismatch(_, let c): context = c case .dataCorrupted( let c): context = c } var userInfo: [String : Any] = [ "NSCodingPath": context.codingPath, "NSDebugDescription": context.debugDescription ] if let underlyingError = context.underlyingError { userInfo["NSUnderlyingError"] = underlyingError } return userInfo as AnyObject #else return nil #endif } } // The following extensions allow for easier error construction. internal struct _GenericIndexKey : CodingKey { var stringValue: String var intValue: Int? init?(stringValue: String) { return nil } init?(intValue: Int) { self.stringValue = "Index \(intValue)" self.intValue = intValue } } public extension DecodingError { /// A convenience method which creates a new .dataCorrupted error using a constructed coding path and the given debug description. /// /// Constructs a coding path by appending the given key to the given container's coding path. /// /// - param key: The key which caused the failure. /// - param container: The container in which the corrupted data was accessed. /// - param debugDescription: A description of the error to aid in debugging. static func dataCorruptedError<C : KeyedDecodingContainerProtocol>(forKey key: C.Key, in container: C, debugDescription: String) -> DecodingError { let context = DecodingError.Context(codingPath: container.codingPath + [key], debugDescription: debugDescription) return .dataCorrupted(context) } /// A convenience method which creates a new .dataCorrupted error using a constructed coding path and the given debug description. /// /// Constructs a coding path by appending a nil key to the given container's coding path. /// /// - param container: The container in which the corrupted data was accessed. /// - param debugDescription: A description of the error to aid in debugging. static func dataCorruptedError(in container: UnkeyedDecodingContainer, debugDescription: String) -> DecodingError { let context = DecodingError.Context(codingPath: container.codingPath + [_GenericIndexKey(intValue: container.currentIndex)!], debugDescription: debugDescription) return .dataCorrupted(context) } /// A convenience method which creates a new .dataCorrupted error using a constructed coding path and the given debug description. /// /// Uses the given container's coding path as the constructed path. /// /// - param container: The container in which the corrupted data was accessed. /// - param debugDescription: A description of the error to aid in debugging. static func dataCorruptedError(in container: SingleValueDecodingContainer, debugDescription: String) -> DecodingError { let context = DecodingError.Context(codingPath: container.codingPath, debugDescription: debugDescription) return .dataCorrupted(context) } } //===----------------------------------------------------------------------===// // Keyed Encoding Container Implementations //===----------------------------------------------------------------------===// @_fixed_layout @_versioned internal class _KeyedEncodingContainerBase<Key : CodingKey> { // These must all be given a concrete implementation in _*Box. @_inlineable @_versioned internal var codingPath: [CodingKey] { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeNil(forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: Bool, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: Int, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: Int8, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: Int16, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: Int32, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: Int64, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: UInt, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: UInt8, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: UInt16, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: UInt32, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: UInt64, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: Float, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: Double, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode(_ value: String, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encode<T : Encodable>(_ value: T, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeConditional<T : AnyObject & Encodable>(_ object: T, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: Int?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: Float?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: Double?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent(_ value: String?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func encodeIfPresent<T : Encodable>(_ value: T?, forKey key: Key) throws { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func superEncoder() -> Encoder { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func superEncoder(forKey key: Key) -> Encoder { fatalError("_KeyedEncodingContainerBase cannot be used directly.") } } @_fixed_layout @_versioned internal final class _KeyedEncodingContainerBox<Concrete : KeyedEncodingContainerProtocol> : _KeyedEncodingContainerBase<Concrete.Key> { typealias Key = Concrete.Key @_versioned internal var concrete: Concrete @_inlineable @_versioned internal init(_ container: Concrete) { concrete = container } @_inlineable @_versioned override internal var codingPath: [CodingKey] { return concrete.codingPath } @_inlineable @_versioned override internal func encodeNil(forKey key: Key) throws { try concrete.encodeNil(forKey: key) } @_inlineable @_versioned override internal func encode(_ value: Bool, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: Int, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: Int8, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: Int16, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: Int32, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: Int64, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: UInt, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: UInt8, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: UInt16, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: UInt32, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: UInt64, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: Float, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: Double, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode(_ value: String, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encode<T : Encodable>(_ value: T, forKey key: Key) throws { try concrete.encode(value, forKey: key) } @_inlineable @_versioned override internal func encodeConditional<T : AnyObject & Encodable>(_ object: T, forKey key: Key) throws { try concrete.encodeConditional(object, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: Int?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: Float?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: Double?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent(_ value: String?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func encodeIfPresent<T : Encodable>(_ value: T?, forKey key: Key) throws { try concrete.encodeIfPresent(value, forKey: key) } @_inlineable @_versioned override internal func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { return concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key) } @_inlineable @_versioned override internal func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { return concrete.nestedUnkeyedContainer(forKey: key) } @_inlineable @_versioned override internal func superEncoder() -> Encoder { return concrete.superEncoder() } @_inlineable @_versioned override internal func superEncoder(forKey key: Key) -> Encoder { return concrete.superEncoder(forKey: key) } } @_fixed_layout @_versioned internal class _KeyedDecodingContainerBase<Key : CodingKey> { @_inlineable @_versioned internal var codingPath: [CodingKey] { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal var allKeys: [Key] { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func contains(_ key: Key) -> Bool { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeNil(forKey key: Key) throws -> Bool { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Int.Type, forKey key: Key) throws -> Int { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Float.Type, forKey key: Key) throws -> Float { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: Double.Type, forKey key: Key) throws -> Double { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode(_ type: String.Type, forKey key: Key) throws -> String { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func superDecoder() throws -> Decoder { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } @_inlineable @_versioned internal func superDecoder(forKey key: Key) throws -> Decoder { fatalError("_KeyedDecodingContainerBase cannot be used directly.") } } @_fixed_layout @_versioned internal final class _KeyedDecodingContainerBox<Concrete : KeyedDecodingContainerProtocol> : _KeyedDecodingContainerBase<Concrete.Key> { typealias Key = Concrete.Key @_versioned internal var concrete: Concrete @_inlineable @_versioned internal init(_ container: Concrete) { concrete = container } @_inlineable @_versioned override var codingPath: [CodingKey] { return concrete.codingPath } @_inlineable @_versioned override var allKeys: [Key] { return concrete.allKeys } @_inlineable @_versioned override internal func contains(_ key: Key) -> Bool { return concrete.contains(key) } @_inlineable @_versioned override internal func decodeNil(forKey key: Key) throws -> Bool { return try concrete.decodeNil(forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return try concrete.decode(Bool.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return try concrete.decode(Int.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return try concrete.decode(Int8.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return try concrete.decode(Int16.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return try concrete.decode(Int32.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return try concrete.decode(Int64.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return try concrete.decode(UInt.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return try concrete.decode(UInt8.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return try concrete.decode(UInt16.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return try concrete.decode(UInt32.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return try concrete.decode(UInt64.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return try concrete.decode(Float.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return try concrete.decode(Double.self, forKey: key) } @_inlineable @_versioned override internal func decode(_ type: String.Type, forKey key: Key) throws -> String { return try concrete.decode(String.self, forKey: key) } @_inlineable @_versioned override internal func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { return try concrete.decode(T.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? { return try concrete.decodeIfPresent(Bool.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? { return try concrete.decodeIfPresent(Int.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? { return try concrete.decodeIfPresent(Int8.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? { return try concrete.decodeIfPresent(Int16.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? { return try concrete.decodeIfPresent(Int32.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? { return try concrete.decodeIfPresent(Int64.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? { return try concrete.decodeIfPresent(UInt.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? { return try concrete.decodeIfPresent(UInt8.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? { return try concrete.decodeIfPresent(UInt16.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? { return try concrete.decodeIfPresent(UInt32.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? { return try concrete.decodeIfPresent(UInt64.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? { return try concrete.decodeIfPresent(Float.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? { return try concrete.decodeIfPresent(Double.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? { return try concrete.decodeIfPresent(String.self, forKey: key) } @_inlineable @_versioned override internal func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? { return try concrete.decodeIfPresent(T.self, forKey: key) } @_inlineable @_versioned override internal func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { return try concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key) } @_inlineable @_versioned override internal func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { return try concrete.nestedUnkeyedContainer(forKey: key) } @_inlineable @_versioned override internal func superDecoder() throws -> Decoder { return try concrete.superDecoder() } @_inlineable @_versioned override internal func superDecoder(forKey key: Key) throws -> Decoder { return try concrete.superDecoder(forKey: key) } } //===----------------------------------------------------------------------===// // Primitive and RawRepresentable Extensions //===----------------------------------------------------------------------===// extension Bool : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Bool.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension Int : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Int.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension Int8 : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Int8.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension Int16 : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Int16.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension Int32 : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Int32.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension Int64 : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Int64.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension UInt : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(UInt.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension UInt8 : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(UInt8.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension UInt16 : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(UInt16.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension UInt32 : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(UInt32.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension UInt64 : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(UInt64.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension Float : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Float.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension Double : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(Double.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } extension String : Codable { public init(from decoder: Decoder) throws { self = try decoder.singleValueContainer().decode(String.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self) } } public extension RawRepresentable where RawValue == Bool, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == Bool, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Int, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == Int, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Int8, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == Int8, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Int16, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == Int16, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Int32, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == Int32, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Int64, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == Int64, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == UInt, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == UInt, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == UInt8, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == UInt8, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == UInt16, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == UInt16, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == UInt32, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == UInt32, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == UInt64, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == UInt64, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Float, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == Float, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == Double, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == Double, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } public extension RawRepresentable where RawValue == String, Self : Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } public extension RawRepresentable where RawValue == String, Self : Decodable { public init(from decoder: Decoder) throws { let decoded = try decoder.singleValueContainer().decode(RawValue.self) guard let value = Self(rawValue: decoded) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)")) } self = value } } //===----------------------------------------------------------------------===// // Optional/Collection Type Conformances //===----------------------------------------------------------------------===// fileprivate func assertTypeIsEncodable<T>(_ type: T.Type, in wrappingType: Any.Type) { guard T.self is Encodable.Type else { if T.self == Encodable.self || T.self == Codable.self { preconditionFailure("\(wrappingType) does not conform to Encodable because Encodable does not conform to itself. You must use a concrete type to encode or decode.") } else { preconditionFailure("\(wrappingType) does not conform to Encodable because \(T.self) does not conform to Encodable.") } } } fileprivate func assertTypeIsDecodable<T>(_ type: T.Type, in wrappingType: Any.Type) { guard T.self is Decodable.Type else { if T.self == Decodable.self || T.self == Codable.self { preconditionFailure("\(wrappingType) does not conform to Decodable because Decodable does not conform to itself. You must use a concrete type to encode or decode.") } else { preconditionFailure("\(wrappingType) does not conform to Decodable because \(T.self) does not conform to Decodable.") } } } // FIXME: Uncomment when conditional conformance is available. extension Optional : Encodable /* where Wrapped : Encodable */ { public func encode(to encoder: Encoder) throws { assertTypeIsEncodable(Wrapped.self, in: type(of: self)) var container = encoder.singleValueContainer() switch self { case .none: try container.encodeNil() case .some(let wrapped): try (wrapped as! Encodable).encode(to: encoder) } } } extension Optional : Decodable /* where Wrapped : Decodable */ { public init(from decoder: Decoder) throws { // Initialize self here so we can get type(of: self). self = .none assertTypeIsDecodable(Wrapped.self, in: type(of: self)) let container = try decoder.singleValueContainer() if !container.decodeNil() { let metaType = (Wrapped.self as! Decodable.Type) let element = try metaType.init(from: decoder) self = .some(element as! Wrapped) } } } // FIXME: Uncomment when conditional conformance is available. extension Array : Encodable /* where Element : Encodable */ { public func encode(to encoder: Encoder) throws { assertTypeIsEncodable(Element.self, in: type(of: self)) var container = encoder.unkeyedContainer() for element in self { // superEncoder appends an empty element and wraps an Encoder around it. // This is normally appropriate for encoding super, but this is really what we want to do. let subencoder = container.superEncoder() try (element as! Encodable).encode(to: subencoder) } } } extension Array : Decodable /* where Element : Decodable */ { public init(from decoder: Decoder) throws { // Initialize self here so we can get type(of: self). self.init() assertTypeIsDecodable(Element.self, in: type(of: self)) let metaType = (Element.self as! Decodable.Type) var container = try decoder.unkeyedContainer() while !container.isAtEnd { // superDecoder fetches the next element as a container and wraps a Decoder around it. // This is normally appropriate for decoding super, but this is really what we want to do. let subdecoder = try container.superDecoder() let element = try metaType.init(from: subdecoder) self.append(element as! Element) } } } extension Set : Encodable /* where Element : Encodable */ { public func encode(to encoder: Encoder) throws { assertTypeIsEncodable(Element.self, in: type(of: self)) var container = encoder.unkeyedContainer() for element in self { // superEncoder appends an empty element and wraps an Encoder around it. // This is normally appropriate for encoding super, but this is really what we want to do. let subencoder = container.superEncoder() try (element as! Encodable).encode(to: subencoder) } } } extension Set : Decodable /* where Element : Decodable */ { public init(from decoder: Decoder) throws { // Initialize self here so we can get type(of: self). self.init() assertTypeIsDecodable(Element.self, in: type(of: self)) let metaType = (Element.self as! Decodable.Type) var container = try decoder.unkeyedContainer() while !container.isAtEnd { // superDecoder fetches the next element as a container and wraps a Decoder around it. // This is normally appropriate for decoding super, but this is really what we want to do. let subdecoder = try container.superDecoder() let element = try metaType.init(from: subdecoder) self.insert(element as! Element) } } } /// A wrapper for dictionary keys which are Strings or Ints. internal struct _DictionaryCodingKey : CodingKey { let stringValue: String let intValue: Int? init?(stringValue: String) { self.stringValue = stringValue self.intValue = Int(stringValue) } init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } } extension Dictionary : Encodable /* where Key : Encodable, Value : Encodable */ { public func encode(to encoder: Encoder) throws { assertTypeIsEncodable(Key.self, in: type(of: self)) assertTypeIsEncodable(Value.self, in: type(of: self)) if Key.self == String.self { // Since the keys are already Strings, we can use them as keys directly. var container = encoder.container(keyedBy: _DictionaryCodingKey.self) for (key, value) in self { let codingKey = _DictionaryCodingKey(stringValue: key as! String)! let valueEncoder = container.superEncoder(forKey: codingKey) try (value as! Encodable).encode(to: valueEncoder) } } else if Key.self == Int.self { // Since the keys are already Ints, we can use them as keys directly. var container = encoder.container(keyedBy: _DictionaryCodingKey.self) for (key, value) in self { let codingKey = _DictionaryCodingKey(intValue: key as! Int)! let valueEncoder = container.superEncoder(forKey: codingKey) try (value as! Encodable).encode(to: valueEncoder) } } else { // Keys are Encodable but not Strings or Ints, so we cannot arbitrarily convert to keys. // We can encode as an array of alternating key-value pairs, though. var container = encoder.unkeyedContainer() for (key, value) in self { // superEncoder appends an empty element and wraps an Encoder around it. // This is normally appropriate for encoding super, but this is really what we want to do. let keyEncoder = container.superEncoder() try (key as! Encodable).encode(to: keyEncoder) let valueEncoder = container.superEncoder() try (value as! Encodable).encode(to: valueEncoder) } } } } extension Dictionary : Decodable /* where Key : Decodable, Value : Decodable */ { public init(from decoder: Decoder) throws { // Initialize self here so we can print type(of: self). self.init() assertTypeIsDecodable(Key.self, in: type(of: self)) assertTypeIsDecodable(Value.self, in: type(of: self)) if Key.self == String.self { // The keys are Strings, so we should be able to expect a keyed container. let container = try decoder.container(keyedBy: _DictionaryCodingKey.self) let valueMetaType = Value.self as! Decodable.Type for key in container.allKeys { let valueDecoder = try container.superDecoder(forKey: key) let value = try valueMetaType.init(from: valueDecoder) self[key.stringValue as! Key] = (value as! Value) } } else if Key.self == Int.self { // The keys are Ints, so we should be able to expect a keyed container. let valueMetaType = Value.self as! Decodable.Type let container = try decoder.container(keyedBy: _DictionaryCodingKey.self) for key in container.allKeys { guard key.intValue != nil else { // We provide stringValues for Int keys; if an encoder chooses not to use the actual intValues, we've encoded string keys. // So on init, _DictionaryCodingKey tries to parse string keys as Ints. If that succeeds, then we would have had an intValue here. // We don't, so this isn't a valid Int key. var codingPath = decoder.codingPath codingPath.append(key) throw DecodingError.typeMismatch(Int.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected Int key but found String key instead.")) } let valueDecoder = try container.superDecoder(forKey: key) let value = try valueMetaType.init(from: valueDecoder) self[key.intValue! as! Key] = (value as! Value) } } else { // We should have encoded as an array of alternating key-value pairs. var container = try decoder.unkeyedContainer() // We're expecting to get pairs. If the container has a known count, it had better be even; no point in doing work if not. if let count = container.count { guard count % 2 == 0 else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Expected collection of key-value pairs; encountered odd-length array instead.")) } } let keyMetaType = (Key.self as! Decodable.Type) let valueMetaType = (Value.self as! Decodable.Type) while !container.isAtEnd { // superDecoder fetches the next element as a container and wraps a Decoder around it. // This is normally appropriate for decoding super, but this is really what we want to do. let keyDecoder = try container.superDecoder() let key = try keyMetaType.init(from: keyDecoder) guard !container.isAtEnd else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Unkeyed container reached end before value in key-value pair.")) } let valueDecoder = try container.superDecoder() let value = try valueMetaType.init(from: valueDecoder) self[key as! Key] = (value as! Value) } } } } //===----------------------------------------------------------------------===// // Convenience Default Implementations //===----------------------------------------------------------------------===// // Default implementation of encodeConditional(_:forKey:) in terms of encode(_:forKey:) public extension KeyedEncodingContainerProtocol { public mutating func encodeConditional<T : AnyObject & Encodable>(_ object: T, forKey key: Key) throws { try encode(object, forKey: key) } } // Default implementation of encodeIfPresent(_:forKey:) in terms of encode(_:forKey:) public extension KeyedEncodingContainerProtocol { public mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } public mutating func encodeIfPresent<T : Encodable>(_ value: T?, forKey key: Key) throws { guard let value = value else { return } try encode(value, forKey: key) } } // Default implementation of decodeIfPresent(_:forKey:) in terms of decode(_:forKey:) and decodeNil(forKey:) public extension KeyedDecodingContainerProtocol { public func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Bool.self, forKey: key) } public func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Int.self, forKey: key) } public func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Int8.self, forKey: key) } public func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Int16.self, forKey: key) } public func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Int32.self, forKey: key) } public func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Int64.self, forKey: key) } public func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(UInt.self, forKey: key) } public func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(UInt8.self, forKey: key) } public func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(UInt16.self, forKey: key) } public func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(UInt32.self, forKey: key) } public func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(UInt64.self, forKey: key) } public func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Float.self, forKey: key) } public func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(Double.self, forKey: key) } public func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(String.self, forKey: key) } public func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? { guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil } return try self.decode(T.self, forKey: key) } } // Default implementation of encodeConditional(_:) in terms of encode(_:), and encode(contentsOf:) in terms of encode(_:) loop. public extension UnkeyedEncodingContainer { public mutating func encodeConditional<T : AnyObject & Encodable>(_ object: T) throws { try self.encode(object) } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Bool { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Int { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Int8 { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Int16 { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Int32 { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Int64 { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == UInt { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == UInt8 { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == UInt16 { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == UInt32 { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == UInt64 { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Float { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == Double { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element == String { for element in sequence { try self.encode(element) } } public mutating func encode<T : Sequence>(contentsOf sequence: T) throws where T.Iterator.Element : Encodable { for element in sequence { try self.encode(element) } } } // Default implementation of decodeIfPresent(_:) in terms of decode(_:) and decodeNil() public extension UnkeyedDecodingContainer { mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Bool.self) } mutating func decodeIfPresent(_ type: Int.Type) throws -> Int? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Int.self) } mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Int8.self) } mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Int16.self) } mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Int32.self) } mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Int64.self) } mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(UInt.self) } mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(UInt8.self) } mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(UInt16.self) } mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(UInt32.self) } mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(UInt64.self) } mutating func decodeIfPresent(_ type: Float.Type) throws -> Float? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Float.self) } mutating func decodeIfPresent(_ type: Double.Type) throws -> Double? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(Double.self) } mutating func decodeIfPresent(_ type: String.Type) throws -> String? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(String.self) } mutating func decodeIfPresent<T : Decodable>(_ type: T.Type) throws -> T? { guard try !self.isAtEnd && !self.decodeNil() else { return nil } return try self.decode(T.self) } } #endif
mit
2d777bc6dbf345f34e13ae0a8d97c75a
46.39331
262
0.671086
4.681402
false
false
false
false
Gofake1/Color-Picker
Color Picker/ColorController.swift
1
1964
// // ColorController.swift // Color Picker // // Created by David Wu on 5/15/17. // Copyright © 2017 Gofake1. All rights reserved. // import Cocoa /// Public interface of `ColorPickerViewController`; any class can use this class to indirectly /// modify `ColorPickerViewController`'s state. class ColorController { static var shared = ColorController() // Should only be set by `colorPicker`'s `NSSlider`. Affects `selectedColor`. var brightness: CGFloat = 1.0 { didSet { selectedColor = NSColor(calibratedHue: masterColor.hueComponent, saturation: masterColor.saturationComponent, brightness: brightness, alpha: 1.0) } } // Should only be set by `colorPicker`'s `ColorWheelView`. Affects `selectedColor`. var masterColor = NSColor(calibratedRed: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) { didSet { selectedColor = NSColor(calibratedHue: masterColor.hueComponent, saturation: masterColor.saturationComponent, brightness: selectedColor.brightnessComponent, alpha: 1.0) } } var selectedColor = NSColor(calibratedRed: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) // Injected by ColorPickerViewController weak var colorPicker: ColorPickerViewController! /// - postcondition: Mutates `colorPicker` func setColor(_ color: NSColor) { selectedColor = color brightness = color.scaledBrightness masterColor = NSColor(calibratedHue: color.hueComponent, saturation: color.saturationComponent, brightness: 1.0, alpha: 1.0) colorPicker.updateColorWheel() colorPicker.updateSlider() colorPicker.updateLabel() } }
mit
8f34b5805705dfcb26aa0bff7a80fc3d
38.26
95
0.589404
4.944584
false
false
false
false
harenbrs/swix
swix/swix/swix/matrix/m-simple-math.swift
1
2689
// // twoD-math.swift // swix // // Created by Scott Sievert on 7/10/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate func apply_function(function: ndarray->ndarray, x: matrix)->matrix{ let y = function(x.flat) var z = zeros_like(x) z.flat = y return z } // TRIG func sin(x: matrix) -> matrix{ return apply_function(sin, x: x) } func cos(x: matrix) -> matrix{ return apply_function(cos, x: x) } func tan(x: matrix) -> matrix{ return apply_function(tan, x: x) } func tanh(x: matrix) -> matrix { return apply_function(tanh, x: x) } // BASIC INFO func abs(x: matrix) -> matrix{ return apply_function(abs, x: x) } func sign(x: matrix) -> matrix{ return apply_function(sign, x: x) } // POWER FUNCTION func pow(x: matrix, power: Double) -> matrix{ let y = pow(x.flat, power: power) var z = zeros_like(x) z.flat = y return z } func sqrt(x: matrix) -> matrix{ return apply_function(sqrt, x: x) } // ROUND func floor(x: matrix) -> matrix{ return apply_function(floor, x: x) } func ceil(x: matrix) -> matrix{ return apply_function(ceil, x: x) } func round(x: matrix) -> matrix{ return apply_function(round, x: x) } // LOG func log(x: matrix) -> matrix{ return apply_function(log, x: x) } // BASIC STATS func min(x:matrix, y:matrix)->matrix{ var z = zeros_like(x) z.flat = min(x.flat, y: y.flat) return z } func max(x:matrix, y:matrix)->matrix{ var z = zeros_like(x) z.flat = max(x.flat, y: y.flat) return z } // AXIS func sum(x: matrix, axis:Int = -1) -> ndarray{ // arg dim: indicating what dimension you want to sum over. For example, if dim==0, then it'll sum over dimension 0 -- it will add all the numbers in the 0th dimension, x[0..<x.shape.0, i] assert(axis==0 || axis==1, "if you want to sum over the entire matrix, call `sum(x.flat)`.") if axis==1{ let n = x.shape.1 let m = ones((n,1)) return (x *! m).flat } else if axis==0 { let n = x.shape.0 let m = ones((1,n)) return (m *! x).flat } // the program will never get below this line assert(false) return zeros(1) } func prod(x: matrix, axis:Int = -1) -> ndarray{ assert(axis==0 || axis==1, "if you want to sum over the entire matrix, call `sum(x.flat)`.") let y = log(x) let z = sum(y, axis:axis) return exp(z) } func mean(x:matrix, axis:Int = -1) -> ndarray{ assert(axis==0 || axis==1, "If you want to find the average of the whole matrix call `mean(x.flat)`") let div = axis==0 ? x.shape.0 : x.shape.1 return sum(x, axis:axis) / div.double }
mit
4efc8ecb62b034b6e0334333c5bbcae6
20.512
192
0.601711
2.926007
false
false
false
false
odigeoteam/TableViewKit
Examples/SampleApp/SampleApp/SelectionViewController.swift
1
3804
import Foundation import UIKit import TableViewKit class SelectionSection: TableSection { var items: ObservableArray<TableItem> = [] weak var tableViewManager: TableViewManager! required init() { } } public protocol SelectionItemProtocol: TableItem { var value: Any { get } var selected: Bool { get set } init(title: String, value: Any, selected: Bool) } public enum SelectionType { case Single, Multiple } public class SelectionItem: SelectionItemProtocol { public static var drawer = AnyCellDrawer(CustomDrawer.self) public var title: String? public var value: Any public var selected: Bool public var onSelection: (Selectable) -> Void = { _ in } public var accessoryType: UITableViewCell.AccessoryType = .none public var accessoryView: UIView? public var cellHeight: CGFloat? = UITableView.automaticDimension public required init(title: String, value: Any, selected: Bool = false) { self.value = value self.selected = selected self.title = title } } public class SelectionViewController: UITableViewController { private var tableViewManager: TableViewManager! private var selectionType: SelectionType! private var selectedItems: [SelectionItem]! public var items: [SelectionItem]! public var onSelection: (([SelectionItem]) -> Void)? private func commonInit() { selectionType = .Single items = [] selectedItems = [] } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) commonInit() } public init(style: UITableView.Style, selectionType: SelectionType) { super.init(style: style) commonInit() self.selectionType = selectionType } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } public override func awakeFromNib() { super.awakeFromNib() commonInit() } override public func viewDidLoad() { super.viewDidLoad() tableViewManager = TableViewManager(tableView: self.tableView) setupTaleViewItems() } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) onSelection?(selectedItems) } private func fillSelected() { selectedItems = items.filter { $0.selected == true } } private func setupTaleViewItems() { let section = SelectionSection() tableViewManager.sections.insert(section, at: 0) for element in items { element.onSelection = { item in self.toogleItemCheck(item: item as! SelectionItem) } element.accessoryType = element.selected ? .checkmark : .none section.items.append(element) } fillSelected() } private func toogleItemCheck(item: SelectionItem) { if selectionType == .Single { if let checkedItem = itemSelected() { checkedItem.selected = false checkedItem.accessoryType = .none checkedItem.reload(with: .fade) } } item.selected = !item.selected item.accessoryType = item.accessoryType == .checkmark ? .none : .checkmark item.reload(with: .fade) fillSelected() } private func itemSelected() -> SelectionItem? { // for section in tableViewManager.sections { // let checkedItems = section.items.filter { $0.accessoryType == .Checkmark } // if checkedItems.count != 0 { // return checkedItems.first as? SelectionItemProtocol // } // } return nil } }
mit
31dbf268a24166b90c3e723ab99bddca
24.530201
88
0.636698
4.966057
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/00158-swift-streamprinter-printtext.swift
11
756
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func k<q { enum k { func j var _ = j } } class x { s m func j(m) } struct j<u> : r { func j(j: j.n) { } } enum q<v> { let k: v let u: v.l } protocol y { o= p>(r: m<v>) } struct D : y { s p = Int func y<v k r { s m } class y<D> { w <r: func j<v x: v) { x.k() } func x(j: Int = a) { } let k = x
apache-2.0
f035de7cd9bbe0a2e4b97100b95e1272
17.439024
78
0.574074
2.810409
false
false
false
false
researchpanelasia/sop-ios-sdk
SurveyonPartners/models/ImplResearch.swift
1
2116
// // ImpleResearch.swift // SurveyonPartners // // Copyright © 2017年 d8aspring. All rights reserved. // struct ResearchInvalidDataError: Error { } class ImplResearch: Research, SurveyListItem { var surveyId: String var title: String var loi: String var url: String var quotaId: String var cpi: String var ir: String var isAnswered: Bool var isClosed: Bool var isFixedLoi: Bool var isNotifiable: Bool var date: String var blockedDevices: [String: Bool] var extraInfo: [String: AnyObject] var surveyIdLabel: String { get {return "r" + surveyId} } var name: String { get {return ""} } init(json: [String: AnyObject]) throws { let getString = {(_ val: String!) throws -> String in try val ?? {throw ResearchInvalidDataError()}()} let getBool = {(_ val: String!) throws -> Bool in try getString(val) == "1"} self.surveyId = try getString(json["survey_id"] as? String) self.title = try getString(json["title"] as? String) self.loi = try getString(json["loi"] as? String) self.url = try getString(json["url"] as? String) self.quotaId = try getString(json["quota_id"] as? String) self.cpi = try getString(json["cpi"] as? String) self.ir = try getString(json["ir"] as? String) self.isAnswered = try getBool(json["is_answered"] as? String) self.isClosed = try getBool(json["is_closed"] as? String) self.isFixedLoi = try getBool(json["is_fixed_loi"] as? String) self.isNotifiable = try getBool(json["is_notifiable"] as? String) self.date = try getString(json["date"] as? String) self.blockedDevices = ImplResearch.parseBlockedDevice(json["blocked_devices"] as? [String:Int]) self.extraInfo = json["extra_info"] as? [String: AnyObject] ?? [:] } static func parseBlockedDevice(_ dic: [String:Int]?) -> [String: Bool] { guard let dic = dic else { return [:] } var parsed = [String: Bool]() for (k, v) in dic { parsed[k] = (v == 1) } return parsed } func isMobileBlocked() -> Bool { return blockedDevices["MOBILE"] ?? false } }
mit
d22f6d0bb1b84f5746d4a5683c8af22d
25.4125
106
0.644108
3.557239
false
false
false
false
Counter-Weight/Edge-of-the-Empire-Dice-Roller-Script
Edge of the Empire Diceroll.swift
1
5285
import Darwin // for arc4random_uniform enum Symbol { // state values for dice faces // case blank // removed to simplify calculations case success case failure case advantage case threat case triumph // critical_success case despair // critical_failure case light case dark } /* All The Die Types */ func forceDie() -> [Symbol] { let num = arc4random_uniform(12) + 1 switch num { case 1...6: return [.dark] case 7: return [.dark] case 8, 9: return [.light] case 10...12: return [.light, .light] default: return [] } } func challengeDie() -> [Symbol] { let num = arc4random_uniform(12) + 1 switch num { case 1: return [] case 2, 3: return [.failure] case 4, 5: return [.failure, .failure] case 6, 7: return [.threat] case 8, 9: return [.threat, .failure] case 10, 11: return [.threat, .threat] case 12: return [.despair] default: return [] } } func proficiencyDie() -> [Symbol] { let num = arc4random_uniform(12) + 1 switch num { case 1: return [] case 2, 3: return [.success] case 4, 5: return [.success, .success] case 6: return [.advantage] case 7...9: return [.advantage, .success] case 10, 11: return [.advantage, .advantage] case 12: return [.triumph] default: return [] } } func difficultyDie() -> [Symbol] { let num = arc4random_uniform(8) + 1 switch num { case 1: return [] case 2: return [.failure] case 3: return [.failure, .failure] case 4...6: return [.threat] case 7: return [.threat, .threat] case 8: return [.threat, .failure] default: return [] } } func abilityDie() -> [Symbol] { let num = arc4random_uniform(8) + 1 switch num { case 1: return [] case 2, 3: return [.success] case 4: return [.success, .success] case 5, 6: return [.advantage] case 7: return [.success, .advantage] case 8: return [.advantage, .advantage] default: return [] } } func setBackDie() -> [Symbol] { let num = arc4random_uniform(6) + 1 switch num { case 1, 2: return [] case 3, 4: return [.failure] case 5, 6: return [.threat] default: return [] } } func boostDie() -> [Symbol] { let num = arc4random_uniform(6) + 1 switch num { case 1, 2: return [] case 3: return [.advantage, .advantage] case 4: return [.advantage] case 5: return [.advantage, .success] case 6: return [.success] default: return [] } } /* End Of The Die Types */ // determines which die to roll func rollDice(numberOfDice number: Int, ofType type: Character) -> [Symbol] { // stores the function to roll dice let typeFunction : () -> [Symbol] // determine type of dice and set the `typeFunction` appropriately switch type { case "f": typeFunction = forceDie case "c": typeFunction = challengeDie case "p": typeFunction = proficiencyDie case "d": typeFunction = difficultyDie case "a": typeFunction = abilityDie case "s": typeFunction = setBackDie case "b": typeFunction = boostDie default: print("`\(type)`, is not a valid dice type, the final character of an argument must be the type of dice") return [] } // roll dice var result = [Symbol]() for _ in 0..<number { result += typeFunction() } return result } // outputs the results of a roll func output() { // continue unlesss empty: no die were rolled, or only blanks were rolled guard !roll.isEmpty else { print("Empty/blank roll") print("FAILURE!") return } var successes = 0, failures = 0, advantages = 0, threats = 0, light = 0, dark = 0, triumphs = 0, despairs = 0 for dieFace in roll { switch dieFace { case .success: successes += 1 case .failure: failures += 1 case .advantage: advantages += 1 case .threat: threats += 1 case .light: light += 1 case .dark: dark += 1 case .triumph: triumphs += 1 case .despair: despairs += 1 } } if successes + triumphs - despairs - threats > 0 { print("SUCCESS!") } else { print("FAILURE!") } // Success/Failure if successes > 0 { print("\(successes) Success" + (successes > 1 ? "es" : "")) } if failures > 0 { print("\(failures) Failure" + (failures > 1 ? "s" : "")) } // Advantage/Threat if advantages > 0 { print("\(advantages) Advantage" + (advantages > 1 ? "s" : "")) } if threats > 0 { print("\(threats) Threat" + (threats > 1 ? "s" : "")) } // Triumph/Despair if triumphs > 0 { print("\(triumphs) Triumph" + (triumphs > 1 ? "s" : "")) } if despairs > 0 { print("\(despairs) Despair" + (despairs > 1 ? "s" : "")) } // Light/Dark if light > 0 { print("\(light) Light Side" + (light > 1 ? "s" : "")) } if dark > 0 { print("\(dark) Dark Side" + (dark > 1 ? "s" : "")) } } var roll = [Symbol]() // parses the command line argument for the number and type of dice to roll for arg in CommandLine.arguments.dropFirst() { // second argument and onward, because the first argument seems to be the call to the file/command // should be the type of dice guard let diceType = arg.characters.last else { print("no dice-type was specified for `\(arg)`") continue } // dice should be the number of dice to roll. If not, then let dice = Int(String(arg.characters.dropLast())) ?? 1 roll += rollDice(numberOfDice: dice, ofType: diceType) } // count/calc each die face and output output()
gpl-3.0
15d651b02c22d5c9e3ea690e2a8429dc
17.942652
145
0.627436
2.817164
false
false
false
false
satoshi0212/GeoFenceDemo
GeoFenceDemo/Views/AddViewController.swift
1
2256
// // AddViewController.swift // GeoFenceDemo // // Created by Satoshi Hattori on 2016/08/08. // Copyright © 2016年 Satoshi Hattori. All rights reserved. // import UIKit import MapKit protocol AddViewControllerDelegate { func addViewController(controller: AddViewController, didAddCoordinate coordinate: CLLocationCoordinate2D, radius: Double, identifier: String, note: String, eventType: EventType) } class AddViewController: UITableViewController, UITextFieldDelegate { @IBOutlet var addButton: UIBarButtonItem! @IBOutlet weak var eventTypeSegmentedControl: UISegmentedControl! @IBOutlet weak var radiusTextField: UITextField! @IBOutlet weak var noteTextField: UITextField! @IBOutlet weak var mapView: MKMapView! var delegate: AddViewControllerDelegate! override func viewDidLoad() { super.viewDidLoad() self.addButton.enabled = false self.tableView.tableFooterView = UIView() self.radiusTextField.delegate = self self.noteTextField.delegate = self } // MARK: - Action @IBAction func textFieldEditingChanged(sender: UITextField) { self.addButton.enabled = !self.radiusTextField.text!.isEmpty && !self.noteTextField.text!.isEmpty } @IBAction func onCancel(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) } @IBAction private func onAdd(sender: AnyObject) { let coordinate = mapView.centerCoordinate let radius = (radiusTextField.text! as NSString).doubleValue let identifier = NSUUID().UUIDString let note = noteTextField.text! let eventType = (eventTypeSegmentedControl.selectedSegmentIndex == 0) ? EventType.OnEntry : EventType.OnExit self.delegate!.addViewController(self, didAddCoordinate: coordinate, radius: radius, identifier: identifier, note: note, eventType: eventType) } @IBAction private func onZoomToCurrentLocation(sender: AnyObject) { Utilities.zoomToUserLocationInMapView(mapView, distance: 2000) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
a9bbabb40c0d6036454b33d0ddad4d0f
33.136364
182
0.70617
5.227378
false
false
false
false
mbigatti/ImagesGenerator
ImagesGenerator/ViewController.swift
1
5667
// // ViewController.swift // ImagesGenerator // // Created by Massimiliano Bigatti on 19/06/15. // Copyright © 2015 Massimiliano Bigatti. All rights reserved. // import UIKit import CoreGraphics class ViewController: UIViewController { @IBOutlet weak var circleView: UIView! @IBOutlet weak var color1TextField: UITextField! @IBOutlet weak var lineWidthTextField: UITextField! @IBOutlet weak var color2TextField: UITextField! @IBOutlet weak var sizeSlider: UISlider! let gradientLayer = CAGradientLayer() let shapeLayer = CAShapeLayer() let backgroundShapeLayer = CAShapeLayer() override func viewDidLoad() { super.viewDidLoad() // // // gradientLayer.frame = CGRect(x: 0, y: 0, width: circleView.layer.frame.width, height: circleView.layer.frame.height) gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 0, y: 1) gradientLayer.mask = shapeLayer circleView.layer.addSublayer(backgroundShapeLayer) circleView.layer.addSublayer(gradientLayer) updateImage() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sizeSliderValueChanged(sender: UISlider) { updateImage() } @IBAction func dataChanged(sender: UITextField) { updateImage() } @IBAction func export(sender: UIButton) { let oldSize = sizeSlider.value for index in 1...60 { sizeSlider.setValue(Float(index), animated: false) updateImage() let filename = "progress-\(index)@2x.png" saveImage(filename) } sizeSlider.value = oldSize updateImage() } private func updateImage() { updateGradient() updateBackgroundShape() updateArcShape() } private func updateGradient() { // // gradient // let color1 = UIColor.colorWithRGBString(color1TextField.text!) let color2 = UIColor.colorWithRGBString(color2TextField.text!) var colors = [AnyObject]() colors.append(color1.CGColor) colors.append(color2.CGColor) gradientLayer.colors = colors } private func updateBackgroundShape() { let center = CGPoint(x: circleView.frame.size.width / 2, y: circleView.frame.size.height / 2) let bezierPath = UIBezierPath(arcCenter: center, radius: (circleView.frame.size.width - CGFloat(strtoul(lineWidthTextField.text!, nil, 10))) / 2, startAngle: CGFloat(-M_PI_2), endAngle: CGFloat(3 * M_PI_2), clockwise: true) let path = CGPathCreateCopyByStrokingPath(bezierPath.CGPath, nil, CGFloat(strtoul(lineWidthTextField.text!, nil, 10)), bezierPath.lineCapStyle, bezierPath.lineJoinStyle, bezierPath.miterLimit) backgroundShapeLayer.path = path backgroundShapeLayer.fillColor = UIColor(white: 1.0, alpha: 0.2).CGColor } private func updateArcShape() { let center = CGPoint(x: circleView.frame.size.width / 2, y: circleView.frame.size.height / 2) let endAngle = (Double(sizeSlider.value) * 4 * M_PI_2) / 60 - M_PI_2 let bezierPath = UIBezierPath(arcCenter: center, radius: (circleView.frame.size.width - CGFloat(strtoul(lineWidthTextField.text!, nil, 10))) / 2, startAngle: CGFloat(-M_PI_2), endAngle: CGFloat(endAngle), clockwise: true) bezierPath.lineCapStyle = .Round let path = CGPathCreateCopyByStrokingPath(bezierPath.CGPath, nil, CGFloat(strtoul(lineWidthTextField.text!, nil, 10)), bezierPath.lineCapStyle, bezierPath.lineJoinStyle, bezierPath.miterLimit) shapeLayer.path = path } func saveImage(filename: String) { let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL let localUrl = NSURL(string: filename, relativeToURL: documentsUrl)! print("\(localUrl)") let color = circleView.backgroundColor; circleView.backgroundColor = UIColor.clearColor() UIGraphicsBeginImageContext(circleView.frame.size); circleView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); let imageData = UIImagePNGRepresentation(image); imageData?.writeToURL(localUrl, atomically: true) circleView.backgroundColor = color; } } extension UIColor { class func colorWithRGBString(hexString: String) -> UIColor { let redString = hexString.substringWithRange(Range(start: hexString.startIndex, end: hexString.startIndex.advancedBy(2))) let greenString = hexString.substringWithRange(Range(start: hexString.startIndex.advancedBy(2), end: hexString.startIndex.advancedBy(4))) let blueString = hexString.substringWithRange(Range(start: hexString.startIndex.advancedBy(4), end: hexString.startIndex.advancedBy(6))) let red = CGFloat(strtoul(redString, nil, 16)) / 255 let green = CGFloat(strtoul(greenString, nil, 16)) / 255 let blue = CGFloat(strtoul(blueString, nil, 16)) / 255 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } }
mit
8010f9f06e75a0550c0a862029b3fdd9
35.320513
200
0.643134
4.897148
false
false
false
false
LedgerHQ/ledger-wallet-ios
ledger-wallet-ios/Controllers/Pairing/Add/PairingAddViewController.swift
1
10050
// // PairingAddViewController.swift // ledger-wallet-ios // // Created by Nicolas Bigot on 15/01/2015. // Copyright (c) 2015 Ledger. All rights reserved. // import UIKit protocol PairingAddViewControllerDelegate: class { func pairingAddViewController(pairingAddViewController: PairingAddViewController, didCompleteWithOutcome outcome: PairingProtocolManager.PairingOutcome, pairingItem: PairingKeychainItem?) } final class PairingAddViewController: BaseViewController { @IBOutlet private weak var containerView: UIView! @IBOutlet private weak var stepNumberLabel: Label! @IBOutlet private weak var stepIndicationLabel: Label! @IBOutlet private weak var bottomInsetConstraint: NSLayoutConstraint! weak var delegate: PairingAddViewControllerDelegate? = nil private var pairingProtocolManager: PairingProtocolManager? = nil private var currentStepViewController: PairingAddBaseStepViewController? = nil // MARK: - Actions override func complete() { // complete current step view controller currentStepViewController?.complete() } override func cancel() { // cancel current step view controller currentStepViewController?.cancel() // complete completeWithOutcome(PairingProtocolManager.PairingOutcome.DeviceTerminated, pairingItem: nil) } private func completeWithOutcome(outcome: PairingProtocolManager.PairingOutcome, pairingItem: PairingKeychainItem?) { // terminate pairing manager pairingProtocolManager?.delegate = nil pairingProtocolManager?.terminate() // notify delegate delegate?.pairingAddViewController(self, didCompleteWithOutcome: outcome, pairingItem: pairingItem) } // MARK: - Interface override func updateView() { super.updateView() navigationItem.leftBarButtonItem?.customView?.hidden = !currentStepViewController!.cancellable navigationItem.rightBarButtonItem?.customView?.hidden = !currentStepViewController!.finalizable stepNumberLabel?.text = "\(currentStepViewController!.stepNumber)." stepIndicationLabel?.text = currentStepViewController!.stepIndication } override func configureView() { super.configureView() // configure pairing manager pairingProtocolManager = PairingProtocolManager() pairingProtocolManager?.delegate = self // go to first step navigateToStep(PairingAddScanStepViewController.self, dataToPass: nil, completion: nil) } // MARK: - View lifecycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) ApplicationManager.sharedInstance.disablesIdleTimer = true } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) ApplicationManager.sharedInstance.disablesIdleTimer = false } // MARK: - Layout override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() currentStepViewController?.view.frame = containerView.bounds } } extension PairingAddViewController { // MARK: - Steps management private class CompletionBlockWrapper { let closure: (Bool) -> Void init(closure: (Bool) -> Void) { self.closure = closure } } private func navigateToStep(stepClass: PairingAddBaseStepViewController.Type, dataToPass data: AnyObject?, completion: ((Bool) -> Void)?) { // instantiate new view controller let newViewController = stepClass.instantiateFromNib() newViewController.data = data addChildViewController(newViewController) newViewController.didMoveToParentViewController(self) newViewController.view.frame = containerView.bounds newViewController.view.setNeedsLayout() newViewController.view.layoutIfNeeded() containerView?.addSubview(newViewController.view) // animate slide to new view controller if there is already a view controller if let currentViewController = currentStepViewController { // create transision let transition = CATransition() transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) transition.type = kCATransitionPush transition.subtype = kCATransitionFromRight transition.duration = VisualFactory.Durations.Animation.Default transition.delegate = self transition.setValue(currentViewController, forKey: "previousStepViewController") if completion != nil { transition.setValue(CompletionBlockWrapper(closure: completion!), forKey: "completionBlock") } // remove current view controller from children currentViewController.willMoveToParentViewController(nil) currentViewController.removeFromParentViewController() self.containerView?.layer.addAnimation(transition, forKey: nil) } else { completion?(true) } // retain new view controller currentStepViewController = newViewController // update view updateView() } func handleStepResult(object: AnyObject, stepViewController: PairingAddBaseStepViewController) { if (stepViewController is PairingAddScanStepViewController) { // go to connection navigateToStep(PairingAddConnectionStepViewController.self, dataToPass: nil) { finished in // join room self.pairingProtocolManager?.joinRoom(object as! String) self.pairingProtocolManager?.sendPublicKey() } } else if (stepViewController is PairingAddCodeStepViewController) { // go to finalize navigateToStep(PairingAddFinalizeStepViewController.self, dataToPass: nil) { finished in // send challenge response (self.pairingProtocolManager?.sendChallengeResponse(object as! String))! } } else if (stepViewController is PairingAddNameStepViewController) { // save pairing item let name = object as! String if let item = pairingProtocolManager?.createNewPairingItemNamed(name) { // register remote notifications RemoteNotificationsManager.sharedInstance.registerForRemoteNotifications() // complete completeWithOutcome(PairingProtocolManager.PairingOutcome.DeviceSucceeded, pairingItem: item) } else { // complete completeWithOutcome(PairingProtocolManager.PairingOutcome.DeviceFailed, pairingItem: nil) } } } } extension PairingAddViewController: PairingProtocolManagerDelegate { // MARK: - PairingProtocolManager delegate func pairingProtocolManager(pairingProtocolManager: PairingProtocolManager, didReceiveChallenge challenge: String) { // go to code navigateToStep(PairingAddCodeStepViewController.self, dataToPass: challenge, completion: nil) } func pairingProtocolManager(pairingProtocolManager: PairingProtocolManager, didTerminateWithOutcome outcome: PairingProtocolManager.PairingOutcome) { if (outcome == PairingProtocolManager.PairingOutcome.DongleSucceeded) { // go to name navigateToStep(PairingAddNameStepViewController.self, dataToPass: nil, completion: nil) } else { // notify delegate completeWithOutcome(outcome, pairingItem: nil) } } } extension PairingAddViewController { // MARK: - Keyboard management override func keyboardWillHide(userInfo: [NSObject : AnyObject]) { super.keyboardWillHide(userInfo) let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let options = UIViewAnimationOptions(rawValue: UInt((userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue << 16)) adjustContentInset(0, duration: duration, options: options, animated: true) } override func keyboardWillShow(userInfo: [NSObject : AnyObject]) { super.keyboardWillShow(userInfo) let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let options = UIViewAnimationOptions(rawValue: UInt((userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue << 16)) adjustContentInset(keyboardFrame.size.height, duration: duration, options: options, animated: true) } private func adjustContentInset(height: CGFloat, duration: NSTimeInterval, options: UIViewAnimationOptions, animated: Bool) { bottomInsetConstraint?.constant = height view.setNeedsLayout() if (animated) { UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: options, animations: { self.view.layoutIfNeeded() }, completion: nil) } else { view.layoutIfNeeded() } } } extension PairingAddViewController { // MARK: - CATransition delegate override func animationDidStop(anim: CAAnimation, finished flag: Bool) { // remove previous view controller view let previousStepViewController = anim.valueForKey("previousStepViewController") as? PairingAddBaseStepViewController previousStepViewController?.view.removeFromSuperview() // call completion block let completionBlock = anim.valueForKey("completionBlock") as? CompletionBlockWrapper completionBlock?.closure(flag) } }
mit
b173c7e1e888fceadc3f80512ea76f43
37.803089
191
0.679303
5.946746
false
false
false
false
knutnyg/picnic
picnic/viewControllers/CountrySelectorViewController.swift
1
5287
import Foundation import UIKit import BButton class CountrySelectorViewController : UIViewController, UITextFieldDelegate { var instructionLabel:UILabel! var useDetectedButton:BButton! var countryTableView:CountryTableViewController! var topFilterField:UITextField! var delegate:UIViewController!=nil var userModel:UserModel! var selectorType:CountrySelectorType! var backButton:UIButton! var backButtonItem:UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white setupNavigationBar() topFilterField = createTextField() topFilterField.addTarget(self, action: #selector(CountrySelectorViewController.topFilterTextEdited(_:)), for: UIControlEvents.editingChanged) countryTableView = CountryTableViewController(userModel: userModel, selectorType: selectorType) countryTableView.view.translatesAutoresizingMaskIntoConstraints = false self.addChildViewController(countryTableView) view.addSubview(topFilterField) view.addSubview(countryTableView.view) let views:[String : AnyObject] = ["countryTable":countryTableView.view, "topFilter":topFilterField] let visualFormat = String(format: "V:|-74-[topFilter(40)]-[countryTable]-0-|") let verticalLayout = NSLayoutConstraint.constraints( withVisualFormat: visualFormat, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[countryTable]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[topFilter]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) view.addConstraints(verticalLayout) } func setupNavigationBar(){ switch selectorType! { case .home_COUNTRY: navigationItem.title = "Home Country" case .gps: navigationItem.title = "Current Location" } let verticalOffset = 3 as CGFloat; navigationController?.navigationBar.setTitleVerticalPositionAdjustment(verticalOffset, for: UIBarMetrics.default) backButton = createfontAwesomeButton("\u{f060}") backButton.addTarget(self, action: #selector(CountrySelectorViewController.back(_:)), for: UIControlEvents.touchUpInside) backButtonItem = UIBarButtonItem(customView: backButton) navigationItem.leftBarButtonItem = backButtonItem } func back(_: UIEvent) { navigationController?.popViewController(animated: true) } func createInstructionLabel() -> UILabel{ let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = NSTextAlignment.center label.numberOfLines = 4 switch selectorType! { case .home_COUNTRY: label.text = "Please set your preferred home country or use the one detected:" break case .gps: label.text = "Please set your preferred current country or use the one detected:" } return label } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } func topFilterTextEdited(_ theTextField:UITextField) -> Void { if let text = theTextField.text { countryTableView.setCountryArray(countryTableView.createCountryNameList().filter{$0.countryName.lowercased().contains(text.lowercased())} ) } else { countryTableView.setCountryArray(countryTableView.createCountryNameList()) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true; } func backButtonPressed(_ notification: Notification) { navigationController?.popViewController(animated: true) } func createTextField() -> UITextField{ let textField = UITextField() textField.delegate = self textField.translatesAutoresizingMaskIntoConstraints = false textField.borderStyle = UITextBorderStyle.roundedRect textField.placeholder = "Filter" textField.autocorrectionType = UITextAutocorrectionType.no textField.textAlignment = NSTextAlignment.center textField.keyboardType = UIKeyboardType.default textField.returnKeyType = UIReturnKeyType.done return textField } /* ---- Initializers ---- */ init(userModel:UserModel, selectorType:CountrySelectorType) { super.init(nibName: nil, bundle: nil) self.userModel = userModel self.selectorType = selectorType } 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") } }
bsd-2-clause
f221e3f68036ae283a6aa477583903da
36.232394
178
0.674295
5.697198
false
false
false
false
mixpanel/mixpanel-swift
Sources/MixpanelType.swift
1
10072
// // MixpanelType.swift // Mixpanel // // Created by Yarden Eitan on 8/19/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation /// Property keys must be String objects and the supported value types need to conform to MixpanelType. /// MixpanelType can be either String, Int, UInt, Double, Float, Bool, [MixpanelType], [String: MixpanelType], Date, URL, or NSNull. /// Numbers are not NaN or infinity public protocol MixpanelType: Any { /** Checks if this object has nested object types that Mixpanel supports. */ func isValidNestedTypeAndValue() -> Bool func equals(rhs: MixpanelType) -> Bool } extension Optional: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. */ public func isValidNestedTypeAndValue() -> Bool { guard let val = self else { return true } // nil is valid switch val { case let v as MixpanelType: return v.isValidNestedTypeAndValue() default: // non-nil but cannot be unwrapped to MixpanelType return false } } public func equals(rhs: MixpanelType) -> Bool { if let v = self as? String, rhs is String { return v == rhs as! String } else if let v = self as? NSString, rhs is NSString { return v == rhs as! NSString } else if let v = self as? NSNumber, rhs is NSNumber { return v.isEqual(to: rhs as! NSNumber) } else if let v = self as? Int, rhs is Int { return v == rhs as! Int } else if let v = self as? UInt, rhs is UInt { return v == rhs as! UInt } else if let v = self as? Double, rhs is Double { return v == rhs as! Double } else if let v = self as? Float, rhs is Float { return v == rhs as! Float } else if let v = self as? Bool, rhs is Bool { return v == rhs as! Bool } else if let v = self as? Date, rhs is Date { return v == rhs as! Date } else if let v = self as? URL, rhs is URL { return v == rhs as! URL } else if self is NSNull && rhs is NSNull { return true } return false } } extension String: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is String { return self == rhs as! String } return false } } extension NSString: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is NSString { return self == rhs as! NSString } return false } } extension NSNumber: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return !self.doubleValue.isInfinite && !self.doubleValue.isNaN } public func equals(rhs: MixpanelType) -> Bool { if rhs is NSNumber { return self.isEqual(rhs) } return false } } extension Int: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is Int { return self == rhs as! Int } return false } } extension UInt: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is UInt { return self == rhs as! UInt } return false } } extension Double: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return !self.isInfinite && !self.isNaN } public func equals(rhs: MixpanelType) -> Bool { if rhs is Double { return self == rhs as! Double } return false } } extension Float: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return !self.isInfinite && !self.isNaN } public func equals(rhs: MixpanelType) -> Bool { if rhs is Float { return self == rhs as! Float } return false } } extension Bool: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is Bool { return self == rhs as! Bool } return false } } extension Date: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is Date { return self == rhs as! Date } return false } } extension URL: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is URL { return self == rhs as! URL } return false } } extension NSNull: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. Will always return true. */ public func isValidNestedTypeAndValue() -> Bool { return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is NSNull { return true } return false } } extension Array: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. */ public func isValidNestedTypeAndValue() -> Bool { for element in self { guard let _ = element as? MixpanelType else { return false } } return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is [MixpanelType] { let rhs = rhs as! [MixpanelType] if self.count != rhs.count { return false } if !isValidNestedTypeAndValue() { return false } let lhs = self as! [MixpanelType] for (i, val) in lhs.enumerated() { if !val.equals(rhs: rhs[i]) { return false } } return true } return false } } extension NSArray: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. */ public func isValidNestedTypeAndValue() -> Bool { for element in self { guard let _ = element as? MixpanelType else { return false } } return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is [MixpanelType] { let rhs = rhs as! [MixpanelType] if self.count != rhs.count { return false } if !isValidNestedTypeAndValue() { return false } let lhs = self as! [MixpanelType] for (i, val) in lhs.enumerated() { if !val.equals(rhs: rhs[i]) { return false } } return true } return false } } extension Dictionary: MixpanelType { /** Checks if this object has nested object types that Mixpanel supports. */ public func isValidNestedTypeAndValue() -> Bool { for (key, value) in self { guard let _ = key as? String, let _ = value as? MixpanelType else { return false } } return true } public func equals(rhs: MixpanelType) -> Bool { if rhs is [String: MixpanelType] { let rhs = rhs as! [String: MixpanelType] if self.keys.count != rhs.keys.count { return false } if !isValidNestedTypeAndValue() { return false } for (key, val) in self as! [String: MixpanelType] { guard let rVal = rhs[key] else { return false } if !val.equals(rhs: rVal) { return false } } return true } return false } } func assertPropertyTypes(_ properties: Properties?) { if let properties = properties { for (_, v) in properties { MPAssert(v.isValidNestedTypeAndValue(), "Property values must be of valid type (MixpanelType) and valid value. Got \(type(of: v)) and Value \(v)") } } } extension Dictionary { func get<T>(key: Key, defaultValue: T) -> T { if let value = self[key] as? T { return value } return defaultValue } }
apache-2.0
5ee6e5f5fc3414259bdb840942d93c17
26.667582
132
0.554463
4.860521
false
false
false
false
fredrikcollden/LittleMaestro
SoundEngine.swift
1
1059
// // SoundEngine.swift // MaestroLevel // // Created by Fredrik Colldén on 2015-11-28. // Copyright © 2015 Marie. All rights reserved. // import UIKit import AVFoundation class SoundEngine { let qualityOfServiceClass = Int(QOS_CLASS_BACKGROUND.rawValue) init() { } func addSound(name: String) -> AVAudioPlayer { print(name) let path = NSBundle.mainBundle().pathForResource(name, ofType: "caf") let url = NSURL.fileURLWithPath(path!) var audioPlayer:AVAudioPlayer do { try audioPlayer = AVAudioPlayer(contentsOfURL: url) //audioPlayer.enableRate = true audioPlayer.prepareToPlay() } catch { audioPlayer = AVAudioPlayer() print("Player not available") } return audioPlayer } func playSound (sound: AVAudioPlayer, length: CGFloat) { if (sound.playing) { sound.pause() sound.currentTime = 0 } sound.play() } }
lgpl-3.0
95f6accb58bfb1d0345620b44d57185f
21.978261
77
0.576159
4.71875
false
false
false
false
noppoMan/swifty-libuv
Sources/Address.swift
1
1269
// // Address.swift // SwiftyLibuv // // Created by Yuki Takei on 6/12/16. // // #if os(Linux) import Glibc #else import Darwin.C #endif import CLibUv /** Wrapper class of sockaddr/sockaddr_in Currently only supported ipv4 */ public class Address { public private(set) var host: String public private(set)var port: Int var _sockAddrinPtr: UnsafeMutablePointer<sockaddr_in>? = nil var address: UnsafePointer<sockaddr> { if _sockAddrinPtr == nil { _sockAddrinPtr = UnsafeMutablePointer<sockaddr_in>.allocate(capacity: 1) uv_ip4_addr(host, Int32(port), _sockAddrinPtr) } return _sockAddrinPtr!.cast(to: UnsafePointer<sockaddr>.self) } /** Convert a string containing an IPv4 addresses to a binary structure. - parameter host: Host to bind - parameter port: Port to bind */ public init(host: String = "0.0.0.0", port: Int = 3000){ self.host = host self.port = port } deinit { if _sockAddrinPtr != nil { dealloc(_sockAddrinPtr!, capacity: 1) } } } extension Address: CustomStringConvertible { public var description: String { return "\(host):\(port)" } }
mit
e4093700b45a52397d105a79039ca4fc
20.15
84
0.606777
3.833837
false
false
false
false
nathantannar4/NTComponents
NTComponents/UI Kit/Alerts/NTToast.swift
1
5628
// // NTToast.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Created by Nathan Tannar on 2/12/17. // import UIKit open class NTToast: NTAnimatedView { open var currentState: NTViewState = .hidden open var dismissOnTap: Bool = true open let label: NTLabel = { let label = NTLabel(style: .body) return label }() open let button: NTButton = { let button = NTButton() button.backgroundColor = .clear button.trackTouchLocation = false button.contentHorizontalAlignment = .center button.ripplePercent = 0.7 button.addTarget(self, action: #selector(dismiss), for: .touchUpInside) button.layer.cornerRadius = 5 return button }() public convenience init(text: String?, color: UIColor = Color.Gray.P800, actionTitle: String, target: Any, selector: Selector) { var bounds = UIScreen.main.bounds bounds.origin.y = bounds.height - 50 bounds.size.height = 50 self.init(frame: bounds) backgroundColor = color label.text = text label.textColor = color.isLight ? .black : .white button.rippleColor = color.isLight ? color.darker(by: 10) : color.lighter(by: 10) button.title = actionTitle button.addTarget(target, action: selector, for: .touchUpInside) label.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: button.leftAnchor, topConstant: 2, leftConstant: 12, bottomConstant: 2, rightConstant: 4, widthConstant: 0, heightConstant: 0) button.anchor(label.topAnchor, left: nil, bottom: label.bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 12, widthConstant: 60, heightConstant: 0) } public convenience init(text: String?, color: UIColor = Color.Gray.P800, height: CGFloat = 50) { var bounds = UIScreen.main.bounds bounds.origin.y = bounds.height - height bounds.size.height = height self.init(frame: bounds) backgroundColor = color label.text = text label.textColor = color.isLight ? .black : .white label.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 2, leftConstant: 12, bottomConstant: 2, rightConstant: 12, widthConstant: 0, heightConstant: 0) } public override init(frame: CGRect) { super.init(frame: frame) ripplePercent = 1.5 touchUpAnimationTime = 0.4 addSubview(label) addSubview(button) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc internal func didTap(_ recognizer: UITapGestureRecognizer) { if dismissOnTap { dismiss() } } open func show(_ view: UIView? = UIApplication.presentedController?.view, duration: TimeInterval? = 2) { if currentState != .hidden { return } guard let view = view else { return } addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(NTToast.didTap(_:)))) frame = CGRect(x: 0, y: view.frame.height, width: view.frame.width, height: self.frame.height) view.addSubview(self) currentState = .transitioning UIView.transition(with: self, duration: 0.3, options: .curveLinear, animations: {() -> Void in self.frame = CGRect(x: 0, y: view.frame.height - self.frame.height, width: view.frame.width, height: self.frame.height) }, completion: { finished in self.currentState = .visible guard let duration = duration else { return } DispatchQueue.executeAfter(duration, closure: { self.dismiss() }) }) } @objc open func dismiss() { if currentState != .visible { return } currentState = .transitioning button.isEnabled = false UIView.transition(with: self, duration: 0.6, options: .curveLinear, animations: {() -> Void in self.alpha = 0 }, completion: { finished in self.currentState = .hidden self.removeFromSuperview() }) } open override func animateToNormal() { // Purposefully Empty } open class func genericErrorMessage() { let alert = NTToast(text: "Sorry, an error occurred") alert.show(duration: 3.0) } }
mit
ddf6cbb224a5498757a6f423ca4e5cad
37.278912
206
0.648481
4.498002
false
false
false
false