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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Qminder/swift-api | TestWebsockets/Sources/TestWebsockets/WebSocketMessage.swift | 1 | 1110 | //
// WebSocketMessage.swift
// Async
//
// Created by Kristaps Grinbergs on 11/05/2018.
//
import Foundation
/// Qminder Event type
public enum QminderEvent: String, CustomStringConvertible, CaseIterable {
/// Ticket created
case ticketCreated = "TICKET_CREATED"
/// Ticket called
case ticketCalled = "TICKET_CALLED"
/// Ticke recalled
case ticketRecalled = "TICKET_RECALLED"
/// Ticket cancelled
case ticketCancelled = "TICKET_CANCELLED"
/// Ticket served
case ticketServed = "TICKET_SERVED"
/// Ticket changed
case ticketChanged = "TICKET_CHANGED"
/// Overview monitor change
case overviewMonitorChange = "OVERVIEW_MONITOR_CHANGE"
/// Lines changed
case linesChanged = "LINES_CHANGED"
public var description: String {
return self.rawValue
}
}
/// Websocket message model
struct WebsocketMessage: Codable {
/// ID of websocket message
var id: String
/// Subscribe event
var subscribe: String
/// Event type enum representation
var eventType: QminderEvent {
return QminderEvent.init(rawValue: subscribe)!
}
}
| mit | 02676ae387858bb960cd1410ba77a2b8 | 19.181818 | 73 | 0.694595 | 4.065934 | false | false | false | false |
tylerbrockett/cse394-principles-of-mobile-applications | final-project/Appa/SearchResultViewController.swift | 1 | 5400 | /*
* @authors Tyler Brockett, Shikha Mehta, Tam Le
* @course ASU CSE 394
* @project Group Project
* @version April 15, 2016
* @project-description Allows users to track Geocaches
* @class-name SearchResultViewController.swift
* @class-description Displays details about single Geocache. Allows user to view weather data, logs, or nearby restaurants
*/
import MapKit
import UIKit
import Foundation
class SearchResultViewController: UIViewController {
var geocache:Geocache?
var baseLocation:CLLocation = CLLocation()
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var name: UITextField!
@IBOutlet weak var desc: UITextField!
@IBOutlet weak var longitude: UITextField!
@IBOutlet weak var latitude: UITextField!
@IBOutlet weak var currentTemp: UILabel!
@IBOutlet weak var lowTemp: UILabel!
@IBOutlet weak var highTemp: UILabel!
@IBOutlet weak var weatherDescription: UILabel!
var restaurants:[Restaurant] = []
override func viewDidLoad() {
super.viewDidLoad()
if geocache != nil {
self.name.text = geocache!.name!
self.desc.text = geocache!.desc!
NSLog("Lat \(geocache!.latitude!) Lon \(geocache!.longitude!)")
self.latitude.text = String(format:"%.3f", Double(geocache!.latitude!))
self.longitude.text = String(format:"%.3f", Double(geocache!.longitude!))
let center:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: Double(geocache!.latitude!), longitude: Double(geocache!.longitude!))
let width = 1000.0 // meters
let height = 1000.0
let region = MKCoordinateRegionMakeWithDistance(center, width, height)
mapView.setRegion(region, animated: true)
// Add Geocache Annotation
let geoAnnotation = MKPointAnnotation()
geoAnnotation.coordinate = center
geoAnnotation.title = "Geocache"
self.mapView.addAnnotation(geoAnnotation)
// Get weather data
let task:NetworkAsyncTask = NetworkAsyncTask()
task.getForecast(Double(geocache!.latitude!), lon: Double(geocache!.longitude!), callback: { (res:WeatherForecast?, error:String?) -> Void in
if error != nil {
NSLog(error!.localizedCapitalizedString)
} else {
self.setForecastData(res)
}
})
} else {
NSLog("Geocache object should never be nil")
}
}
func setForecastData(forecast:WeatherForecast?) {
if forecast != nil {
self.currentTemp.text = forecast!.getTemp() + "\u{00B0}F" // \u{00B0} is the degree symbol
self.lowTemp.text = forecast!.getLow() + "\u{00B0}F"
self.highTemp.text = forecast!.getHigh() + "\u{00B0}F"
self.weatherDescription.text = forecast!.getDescription()
} else {
self.currentTemp.text = "N/A"
self.lowTemp.text = "N/A"
self.highTemp.text = "N/A"
self.weatherDescription.text = "N/A"
}
}
@IBAction func foodNearby(sender: UIButton) {
if let lat:Double = (latitude.text! as NSString).doubleValue, lon:Double = (longitude.text! as NSString).doubleValue {
let task = NetworkAsyncTask()
task.getFoodNearby(lat, lon: lon, radius: 5.0, callback: { (res:[Restaurant]?, error: String?) -> Void in
if error == nil && res != nil {
self.restaurants = res!
self.performSegueWithIdentifier("nearbyFood", sender: nil)
} else {
let alert = UIAlertController(title: "No Results", message: "There were no food locations found near this area. Sorry!", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
NSLog(error!)
}
})
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "nearbyFood"){
if let viewController: NearbyFoodViewController = segue.destinationViewController as? NearbyFoodViewController {
viewController.restaurants = self.restaurants
if let lat:Double = (latitude.text! as NSString).doubleValue, lon:Double = (longitude.text! as NSString).doubleValue {
viewController.geocacheLocation = CLLocation(latitude: lat, longitude: lon)
}
}
}
if(segue.identifier == "newLogEntry"){
if let viewController:NewLogEntryViewController = segue.destinationViewController as? NewLogEntryViewController {
viewController.geocache = self.geocache!
}
}
if(segue.identifier == "logs"){
if let viewController:LogViewController = segue.destinationViewController as? LogViewController {
viewController.geocache = self.geocache!
}
}
}
}
| mit | c97d3f6f2d070db2f926833da0e5d20c | 42.902439 | 186 | 0.598148 | 4.817128 | false | false | false | false |
svachmic/ios-url-remote | URLRemote/Classes/Controllers/TypeSelectionTableViewCell.swift | 1 | 737 | //
// TypeSelectionTableViewCell.swift
// URLRemote
//
// Created by Michal Švácha on 13/01/17.
// Copyright © 2017 Svacha, Michal. All rights reserved.
//
import UIKit
import Material
///
class TypeSelectionTableViewCell: UITableViewCell {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var infoButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = .clear
self.label = self.viewWithTag(1) as? UILabel
self.label?.font = RobotoFont.medium(with: 16)
self.label?.textColor = .gray
self.infoButton = self.viewWithTag(2) as? UIButton
self.infoButton?.tintColor = UIColor(named: .green)
}
}
| apache-2.0 | 142218bf7a86626170b72c9f5562a9dc | 24.310345 | 59 | 0.651226 | 4.242775 | false | false | false | false |
kreshikhin/scituner | SciTuner/Models/Note.swift | 1 | 1531 | //
// Note.swift
// SciTuner
//
// Created by Denis Kreshikhin on 8/10/17.
// Copyright © 2017 Denis Kreshikhin. All rights reserved.
//
import Foundation
struct Note: Comparable, CustomStringConvertible{
typealias `Self` = Note
static let semitoneNames = ["c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b"]
var number: Int = 0
var octave: Int { return number / 12 }
var semitone: Int { return number % 12 }
var string: String {
get { return Self.semitoneNames[semitone] + String(octave) }
}
var description: String { return string }
init(number: Int) {
self.number = number
}
init(octave: Int, semitone: Int) {
number = 12 * octave + semitone
}
init(_ name: String) {
let lowercased = name.lowercased().trimmingCharacters(in: .whitespaces)
var semitone = 0
var octave = 0
for (i, n) in Self.semitoneNames.enumerated() {
if lowercased.hasPrefix(n) { semitone = i }
}
for i in 0...8 {
if lowercased.hasSuffix(String(i)) { octave = i }
}
number = 12 * octave + semitone
}
static func < (lhs: Self, rhs: Self) -> Bool {
return lhs.number <= rhs.number
}
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.number == rhs.number
}
static func + (lhs: Self, rhs: Int) -> Note {
return Note(number: lhs.number + rhs)
}
}
| mit | 294ee1e0b3a929261607015994d9089a | 24.081967 | 96 | 0.536601 | 3.740831 | false | false | false | false |
Ricky-Choi/AppcidCocoaUtil | AppcidCocoaUtil/ACDOverlayViewController.swift | 1 | 24232 | //
// ACDOverlayViewController.swift
// ACD
//
// Created by Jae Young Choi on 2015. 11. 4..
// Copyright © 2015년 Appcid. All rights reserved.
//
#if os(iOS)
import UIKit
enum ACDOverlayType {
case staticRatio(CGFloat) // height ratio
case dynamicRatio(CGFloat, CGFloat) // max height ratio, recommend height ratio
case staticValue(CGFloat) // height
case dynamicValue(CGFloat, CGFloat) // max height, recommend height
func isStatic() -> Bool {
switch self {
case .staticRatio(_), .staticValue(_):
return true
default:
return false
}
}
func isDynamic() -> Bool {
return !isStatic()
}
}
enum ACDDynamicMode {
case max
case recommend
}
protocol ACDOverlay {
var statusBarHidden: Bool { get }
}
protocol ACDPartlyOverlay: ACDOverlay {
var overlayType: ACDOverlayType { get }
var swipeUpEnabled: Bool { get }
var dynamicGestureEnabled: Bool { get }
var showDimmingView: Bool { get }
var dimmingColor: UIColor { get }
var useVisualEffectViewForDimming: Bool { get }
var dismissWhenTapDimmingView: Bool { get }
var baseScrollView: UIScrollView? { get }
}
open class ACDOverlayViewController: UIViewController, ACDPartlyOverlay {
var statusBarHidden = false
var overlayType = ACDOverlayType.dynamicRatio(0.9, 0.6)
var dynamicMode = ACDDynamicMode.recommend
var dynamicHeight: (max: CGFloat, recommend: CGFloat) = (0, 0)
var swipeUpEnabled: Bool = false
var dynamicGestureEnabled: Bool = true
var swipeCloseEnabled: Bool = true
var swipeStopRecommandY: Bool = true
var showDimmingView: Bool {
return true
}
var dimmingColor: UIColor {
return UIColor(white: 0.0, alpha: 0.5)
}
var useVisualEffectViewForDimming: Bool {
return false
}
var dismissWhenTapDimmingView = true
var baseScrollView: UIScrollView? = nil
var startFrame: CGRect = CGRect.zero
var keyboardHeight: CGFloat = 0
var contentHeight: CGFloat = 0 {
didSet {
print("overlay view's content height: \(contentHeight)")
}
}
weak var extendView: UIView?
fileprivate weak var rubberBandView: UIView?
var observeKeyboard = false {
didSet {
guard oldValue != observeKeyboard else {
return
}
let notificationCenter = NotificationCenter.default
if observeKeyboard {
// register notification
notificationCenter.addObserver(self, selector: #selector(ACDOverlayViewController.keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(ACDOverlayViewController.keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
} else {
// remove notification
notificationCenter.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
notificationCenter.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
}
}
func initSetup() {
modalPresentationStyle = .custom
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initSetup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSetup()
}
deinit {
print("deinit \(self)")
observeKeyboard = false
}
override open func loadView() {
view = ACDOverlayView()
}
weak var pan: UIPanGestureRecognizer?
override open func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let pan = UIPanGestureRecognizer(target: self, action: #selector(ACDOverlayViewController.panGesture(_:)))
pan.delegate = self
view.addGestureRecognizer(pan)
// top shadow
if let shadowImage = UIImage(named: "overlay_shadow") {
let shadow = UIImageView(image: shadowImage)
view.addSubview(shadow)
shadow.fillXToSuperview()
shadow.fixHeight(shadowImage.size.height)
NSLayoutConstraint(item: shadow, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0).isActive = true
} else {
view.layer.shadowOpacity = 0.5
view.layer.shadowOffset = CGSize(width: 0, height: 0)
}
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let presentationController = presentationController as? ACDOverlayPresentationController, let containerView = presentationController.containerView , self.overlayType.isDynamic() {
switch overlayType {
case .dynamicRatio(let maxRatio, let recommendedRatio):
dynamicHeight = (max: containerView.frame.height * maxRatio, recommend: containerView.frame.height * recommendedRatio)
case .dynamicValue(let maxHeight, let recommendedHeight):
dynamicHeight = (max: maxHeight, recommend: recommendedHeight)
default:
fatalError()
}
adjustScrollInset()
}
addBottomRubberBand()
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeExtendView()
}
func heightForShrink(_ containerView: UIView) -> CGFloat {
switch self.overlayType {
case .dynamicRatio(let maxRatio, let recommendedRatio):
return containerView.frame.size.height * (swipeStopRecommandY ? recommendedRatio : maxRatio)
case .dynamicValue(let maxHeight, let recommendedHeight):
return swipeStopRecommandY ? recommendedHeight : maxHeight
case .staticRatio(let recommendedRatio):
return containerView.frame.size.height * recommendedRatio
case .staticValue(let recommendedHeight):
return recommendedHeight
}
}
func heightForShrink() -> CGFloat {
if let presentationController = presentationController as? ACDOverlayPresentationController, let containerView = presentationController.containerView {
return heightForShrink(containerView)
}
return 0
}
func oddHeightForDynamicType() -> CGFloat {
switch self.overlayType {
case .dynamicRatio(let maxRatio, let recommendedRatio):
if let presentationController = presentationController as? ACDOverlayPresentationController, let containerView = presentationController.containerView {
return containerView.frame.size.height * (maxRatio - recommendedRatio)
} else {
return 0
}
case .dynamicValue(let maxHeight, let recommendedHeight):
return maxHeight - recommendedHeight
default:
return 0
}
}
override open var prefersStatusBarHidden : Bool {
return statusBarHidden
}
let useBanding = false
func panGesture(_ gesture: UIPanGestureRecognizer) {
guard let presentationController = presentationController as? ACDOverlayPresentationController else {
return
}
pan = gesture
if gesture.state == .began {
startFrame = view.frame
} else if gesture.state == .changed {
let translation = gesture.translation(in: gesture.view)
var newY = startFrame.origin.y + translation.y
var containerViewFrame = CGRect.zero
if let containerView = presentationController.containerView {
containerViewFrame = containerView.frame
} else {
containerViewFrame = UIScreen.main.bounds
}
if !useBanding {
var targetY: CGFloat = 0.0
if overlayType.isStatic() {
switch overlayType {
case .staticRatio(let ratio):
targetY = containerViewFrame.size.height * (1 - ratio) - keyboardHeight
case .staticValue(let height):
targetY = containerViewFrame.size.height - height - keyboardHeight
default:
fatalError()
}
} else {
switch overlayType {
case .dynamicRatio(let maxRatio, let recommendedRatio):
targetY = containerViewFrame.size.height * (1 - (dynamicGestureEnabled ? maxRatio : recommendedRatio))
case .dynamicValue(let maxHeight, let recommendedHeight):
targetY = containerViewFrame.size.height - (dynamicGestureEnabled ? maxHeight : recommendedHeight)
default:
fatalError()
}
}
if newY < targetY {
newY = targetY
}
}
if !swipeCloseEnabled {
var targetY: CGFloat = 0.0
if overlayType.isStatic() {
switch overlayType {
case .staticRatio(let ratio):
targetY = containerViewFrame.size.height * (1 - ratio) - keyboardHeight
case .staticValue(let height):
targetY = containerViewFrame.size.height - height - keyboardHeight
default:
fatalError()
}
} else {
switch overlayType {
case .dynamicRatio(_, let recommendedRatio):
targetY = containerViewFrame.size.height * (1 - recommendedRatio)
case .dynamicValue(_, let recommendedHeight):
targetY = containerViewFrame.size.height - (recommendedHeight)
default:
fatalError()
}
}
if newY > targetY {
newY = targetY
}
}
view.frame = CGRect(x: startFrame.origin.x, y: newY, width: startFrame.size.width, height: startFrame.size.height)
presentationController.overlayY = newY
} else if gesture.state == .ended || gesture.state == .cancelled {
let translation = gesture.translation(in: gesture.view)
let velocity = gesture.velocity(in: gesture.view)
let overlayY = startFrame.origin.y + translation.y// + velocity.y
var containerViewFrame = CGRect.zero
if let containerView = presentationController.containerView {
containerViewFrame = containerView.frame
} else if gesture.state == .cancelled {
containerViewFrame = UIScreen.main.bounds
} else {
return // TODO: dismiss??
}
var targetY: CGFloat = 0.0
if overlayType.isStatic() {
switch overlayType {
case .staticRatio(let ratio):
targetY = containerViewFrame.size.height * (1 - ratio) - keyboardHeight
case .staticValue(let height):
targetY = containerViewFrame.size.height - height - keyboardHeight;
default:
fatalError()
}
if (overlayY >= targetY && overlayY < containerViewFrame.size.height && velocity.y > 0) || (overlayY >= containerViewFrame.size.height) {
if swipeCloseEnabled {
dismiss(animated: true, completion: nil)
}
return
}
} else {
let maxY: CGFloat;
let recommendedY: CGFloat;
switch overlayType {
case .dynamicRatio(let maxRatio, let recommendedRatio):
maxY = containerViewFrame.size.height * (1 - maxRatio)
recommendedY = containerViewFrame.size.height * (1 - recommendedRatio)
case .dynamicValue(let maxHeight, let recommendedHeight):
maxY = containerViewFrame.size.height - maxHeight
recommendedY = containerViewFrame.size.height - recommendedHeight
default:
fatalError()
}
if dynamicGestureEnabled {
if swipeStopRecommandY {
if overlayY < maxY {
targetY = maxY
dynamicMode = .max
} else if overlayY >= maxY && overlayY < recommendedY {
if velocity.y > 0 {
targetY = recommendedY
dynamicMode = .recommend
} else {
targetY = maxY
dynamicMode = .max
}
} else if overlayY >= recommendedY && overlayY < containerViewFrame.size.height {
if velocity.y > 0 {
if swipeCloseEnabled {
dismiss(animated: true, completion: nil)
}
return
} else {
targetY = recommendedY
dynamicMode = .recommend
}
} else {
dismiss(animated: true, completion: nil)
return
}
} else {
if overlayY < maxY {
targetY = maxY
dynamicMode = .max
} else if overlayY >= maxY && overlayY < containerViewFrame.size.height {
if velocity.y > 0 {
if swipeCloseEnabled {
dismiss(animated: true, completion: nil)
}
return
} else {
targetY = maxY
dynamicMode = .max
}
} else {
dismiss(animated: true, completion: nil)
return
}
}
} else {
if (overlayY < containerViewFrame.size.height && velocity.y > 0) || (overlayY >= containerViewFrame.size.height) {
if swipeCloseEnabled {
dismiss(animated: true, completion: nil)
}
return
} else {
targetY = recommendedY
}
}
}
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: velocity.y / containerViewFrame.size.height, options: [], animations: { () -> Void in
self.view.frame = CGRect(x: self.startFrame.origin.x, y: targetY, width: self.startFrame.size.width, height: self.startFrame.size.height)
presentationController.overlayY = targetY
}) { finished in
self.fitViewDidAppear()
switch self.overlayType {
case .dynamicRatio(_, _), .dynamicValue(_, _):
self.adjustScrollInsetForViewHeight(containerViewFrame.size.height - targetY)
default:
break
}
}
}
}
func moveView(targetY: CGFloat, comeplete: (() -> ())?) {
guard let presentationController = presentationController as? ACDOverlayPresentationController else {
return
}
var containerViewFrame = CGRect.zero
if let containerView = presentationController.containerView {
containerViewFrame = containerView.frame
}
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.frame = CGRect(x: self.startFrame.origin.x, y: targetY, width: self.startFrame.size.width, height: self.startFrame.size.height)
presentationController.overlayY = targetY
}, completion: { (finished: Bool) -> Void in
self.fitViewDidAppear()
comeplete?()
switch self.overlayType {
case .dynamicRatio(_, _), .dynamicValue(_, _):
self.adjustScrollInsetForViewHeight(containerViewFrame.size.height - targetY)
default:
break
}
})
}
func fitViewDidAppear() { print(#function) }
func adjustScrollInsetForViewHeight(_ height: CGFloat) {
contentHeight = height
guard let scrollView = baseScrollView, let superview = scrollView.superview else {
return
}
let origin = superview.convert(scrollView.frame.origin, to: view)
let newInsetBottom = scrollView.frame.size.height + origin.y - height
let originalScrollInset = scrollView.contentInset
let newScrollInset = UIEdgeInsets(top: originalScrollInset.top, left: originalScrollInset.left, bottom: newInsetBottom, right: originalScrollInset.right)
scrollView.setInset(newScrollInset)
}
func adjustScrollInset() {
if self.overlayType.isDynamic() {
let height: CGFloat
switch dynamicMode {
case .max:
height = dynamicHeight.max
case .recommend:
height = dynamicHeight.recommend
}
adjustScrollInsetForViewHeight(height)
}
}
func moveToMaxHeight(_ comeplete: (() -> ())? = nil) {
guard let presentationController = presentationController as? ACDOverlayPresentationController else {
return
}
if let pan = pan , pan.state == .began || pan.state == .changed {
return
}
var containerViewFrame = CGRect.zero
if let containerView = presentationController.containerView {
containerViewFrame = containerView.frame
}
if self.overlayType.isDynamic() {
dynamicMode = .max
self.moveView(targetY: containerViewFrame.height - dynamicHeight.max, comeplete: comeplete)
}
}
}
extension ACDOverlayViewController {
func keyboardWillHide(_ aNotification: Notification) {
keyboardAnimation(aNotification, isShow: false)
}
func keyboardWillShow(_ aNotification: Notification) {
keyboardAnimation(aNotification, isShow: true)
}
func keyboardAnimation(_ aNotification: Notification, isShow: Bool) {
let userInfo: NSDictionary = (aNotification as NSNotification).userInfo! as NSDictionary
let keyboardFrame: CGRect = (userInfo.object(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue).cgRectValue
let viewSize = view.frame.size
view.frame = CGRect(x: 0, y: keyboardFrame.origin.y - viewSize.height, width: viewSize.width, height: viewSize.height)
if isShow {
keyboardHeight = keyboardFrame.height
} else {
keyboardHeight = 0
}
}
}
extension ACDOverlayViewController {
func showExtendView(_ contentView: UIView, margin: ACDMargin = ACDMarginZero, height: CGFloat = 150, showClose: Bool = true, backgroundColor: UIColor = UIColor(white: 0, alpha: 0.4), heightOffset: CGFloat = 0) {
removeExtendView()
// background
let extendView = UIView()
extendView.backgroundColor = backgroundColor
view.addSubview(extendView)
extendView.fillXToSuperview()
if height <= 0 {
NSLayoutConstraint(item: extendView, attribute: .top, relatedBy: .equal, toItem: view.superview, attribute: .top, multiplier: 1, constant: -heightOffset).isActive = true
} else {
extendView.fixHeight(height)
}
NSLayoutConstraint(item: extendView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: heightOffset).isActive = true
(view as! ACDOverlayView).extendView = extendView
// content
extendView.addSubview(contentView)
contentView.fillToSuperview(margin)
if showClose {
// close button
let closeButton = UIButton(type: .custom)
closeButton.setImage(UIImage(named: "close"), for: .normal)
let buttonInset: CGFloat = 7
closeButton.contentEdgeInsets = UIEdgeInsets(top: buttonInset, left: buttonInset, bottom: buttonInset, right: buttonInset)
closeButton.addTarget(self, action: #selector(ACDOverlayViewController.extendViewCloseButtonTouched(_:)), for: .touchUpInside)
extendView.addSubview(closeButton)
closeButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: closeButton, attribute: .top, relatedBy: .equal, toItem: extendView, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: closeButton, attribute: .trailing, relatedBy: .equal, toItem: extendView, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
}
self.extendView = extendView
}
func removeExtendView() {
if extendView?.superview != nil {
extendView?.removeFromSuperview()
}
}
func extendViewCloseButtonTouched(_ sender: AnyObject) {
removeExtendView()
}
fileprivate func addBottomRubberBand(_ color: UIColor = UIColor.white) {
let rubberBandView = UIView()
rubberBandView.backgroundColor = color
view.insertSubview(rubberBandView, at: 0)
rubberBandView.fillXToSuperview()
rubberBandView.fixHeight(UIScreen.main.bounds.height)
NSLayoutConstraint(item: rubberBandView, attribute: .top, relatedBy: .equal, toItem: rubberBandView.superview, attribute: .bottom, multiplier: 1, constant: -1).isActive = true
self.rubberBandView = rubberBandView
}
func setBottomRubberBandViewColor(_ color: UIColor?) {
self.rubberBandView?.backgroundColor = color
}
}
extension ACDOverlayViewController: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
class ACDOverlayView: UIView {
var extendView: UIView?
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let extendView = extendView {
let pointForExtendView = extendView.convert(point, from: self)
if extendView.bounds.contains(pointForExtendView) {
return extendView.hitTest(pointForExtendView, with: event)
}
}
return super.hitTest(point, with: event)
}
}
#endif
| mit | b8a4f794c8cb1db77b05b70f99dde315 | 37.519873 | 215 | 0.558339 | 5.664952 | false | false | false | false |
lucdion/aide-devoir | sources/AideDevoir/Classes/UI/Common/WCLShineLayer.swift | 1 | 3753 | //
// WCLShineLayer.swift
// WCLShineButton
//
// **************************************************
// * _____ *
// * __ _ __ ___ \ / *
// * \ \/ \/ / / __\ / / *
// * \ _ / | (__ / / *
// * \/ \/ \___/ / /__ *
// * /_____/ *
// * *
// **************************************************
// Github :https://github.com/imwcl
// HomePage:https://imwcl.com
// CSDN :http://blog.csdn.net/wang631106979
//
// Created by 王崇磊 on 16/9/14.
// Copyright © 2016年 王崇磊. All rights reserved.
//
// @class WCLShineLayer
// @abstract 展示Shine的layer
// @discussion 展示Shine的layer
//
import UIKit
class WCLShineLayer: CALayer, CAAnimationDelegate {
let shapeLayer = CAShapeLayer()
var fillColor: UIColor = UIColor(rgb: (255, 102, 102)) {
willSet {
shapeLayer.strokeColor = newValue.cgColor
}
}
var params: WCLShineParams = WCLShineParams()
var displaylink: CADisplayLink?
var endAnim: (() -> Void)?
//MARK: Public Methods
public func startAnim() {
let anim = CAKeyframeAnimation(keyPath: "path")
anim.duration = params.animDuration * 0.1
let size = frame.size
let fromPath = UIBezierPath(arcCenter: CGPoint.init(x: size.width/2, y: size.height/2), radius: 1, startAngle: 0, endAngle: CGFloat(Double.pi) * 2.0, clockwise: false).cgPath
let toPath = UIBezierPath(arcCenter: CGPoint.init(x: size.width/2, y: size.height/2), radius: size.width/2 * CGFloat(params.shineDistanceMultiple), startAngle: 0, endAngle: CGFloat(Double.pi) * 2.0, clockwise: false).cgPath
anim.delegate = self
anim.values = [fromPath, toPath]
anim.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)]
anim.isRemovedOnCompletion = false
anim.fillMode = kCAFillModeForwards
shapeLayer.add(anim, forKey: "path")
if params.enableFlashing {
startFlash()
}
}
//MARK: Initial Methods
override init() {
super.init()
initLayers()
}
override init(layer: Any) {
super.init(layer: layer)
initLayers()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Privater Methods
private func initLayers() {
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.strokeColor = fillColor.cgColor
shapeLayer.lineWidth = 1.5
addSublayer(shapeLayer)
}
private func startFlash() {
displaylink = CADisplayLink(target: self, selector: #selector(flashAction))
if #available(iOS 10.0, *) {
displaylink?.preferredFramesPerSecond = 6
} else {
displaylink?.frameInterval = 10
}
displaylink?.add(to: .current, forMode: .commonModes)
}
@objc private func flashAction() {
let index = Int(arc4random()%UInt32(params.colorRandom.count))
shapeLayer.strokeColor = params.colorRandom[index].cgColor
}
//MARK: CAAnimationDelegate
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
displaylink?.invalidate()
displaylink = nil
shapeLayer.removeAllAnimations()
let angleLayer = WCLShineAngleLayer(frame: bounds, params: params)
addSublayer(angleLayer)
angleLayer.startAnim()
endAnim?()
}
}
}
| apache-2.0 | 2e65be7da938a0a99a716c9f9ce79b5e | 32.267857 | 231 | 0.542136 | 4.435714 | false | false | false | false |
PureSwift/SwiftCF | SwiftCF/SwiftCF/DateFormatter.swift | 1 | 4360 | //
// DateFormatter.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 7/4/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
import SwiftFoundation
/// Formats a date.
public struct DateFormatter: Formatter {
// MARK: - Properties
public var locale: Locale? {
mutating didSet {
self = DateFormatter(format: format, properties: properties, locale: locale)
}
}
public var format: String {
mutating didSet {
if !isUniquelyReferencedNonObjC(&self.internalFormatter) {
// make copy
self = DateFormatter(format: format, properties: properties, locale: locale)
}
// set format
CFDateFormatterSetFormat(self.internalFormatter.value, format)
}
}
public var properties: [DateFormatterProperty] {
mutating didSet {
if !isUniquelyReferencedNonObjC(&self.internalFormatter) {
// make copy
self = DateFormatter(format: format, properties: properties, locale: locale)
}
// set properties
self.internalFormatter.value.setProperties(properties)
}
}
// MARK: - Private Properties
private var internalFormatter: InternalDateFormatter
private let internalQueue = dispatch_queue_create("DateFormatter Thread Safety Internal Queue", nil)
// MARK: - Initialization
public init(format: String, properties: [DateFormatterProperty] = [], locale: Locale? = nil) {
let formatter = CFDateFormatterRef.withStyle(.NoStyle, timeStyle: .NoStyle, locale: locale)
CFDateFormatterSetFormat(formatter, format)
self.properties = properties
self.format = format
self.locale = locale
self.internalFormatter = InternalDateFormatter(value: formatter)
}
// MARK: - Format
public func stringFromValue(value: Date) -> String {
return self.internalFormatter.stringFromDate(value)
}
public func valueFromString(string: String) -> Date? {
return self.internalFormatter.dateFromString(string)
}
}
public enum DateFormatterProperty {
//case Calendar(Calendar) // CFCalendar
//case TimeZone(TimeZone) // CFTimeZone
case IsLenient(Bool)
case CalendarName(String)
case DefaultFormat(String)
case TwoDigitStartDate(Date)
case DefaultDate(Date)
case EraSymbols([String])
case MonthSymbols([String])
case ShortMonthSymbols([String])
case WeekdaySymbols([String])
case ShortWeekdaySymbols([String])
case AMSymbol(StringValue)
case PMSymbol(StringValue)
case LongEraSymbols([String])
case VeryShortMonthSymbols([String])
case StandaloneMonthSymbols([String])
case ShortStandaloneMonthSymbols([String])
case VeryShortStandaloneMonthSymbols([String])
case VeryShortWeekdaySymbols([String])
case StandaloneWeekdaySymbols([String])
case ShortStandaloneWeekdaySymbols([String])
case VeryShortStandaloneWeekdaySymbols([String])
case QuarterSymbols([String])
case ShortQuarterSymbols([String])
case StandaloneQuarterSymbols([String])
case ShortStandaloneQuarterSymbols([String])
case GregorianStartDate(Date)
case DoesRelativeDateFormattingKey(Bool)
}
// MARK: - Internal
internal final class InternalDateFormatter {
let value: CFDateFormatterRef
init(value: CFDateFormatterRef) {
self.value = value
}
let internalQueue = dispatch_queue_create("DateFormatter Thread Safety Queue", nil)
func stringFromDate(value: Date) -> String {
var stringValue: String!
dispatch_sync(self.internalQueue) { () -> Void in
stringValue = self.value.stringFromDate(value)
}
return stringValue
}
func dateFromString(string: String) -> Date? {
var date: Date?
dispatch_sync(self.internalQueue) { () -> Void in
date = self.value.dateFromString(string)
}
return date
}
}
| mit | ff2d8c60fded317c7dc6125a08d822ae | 26.764331 | 104 | 0.620326 | 5.421642 | false | false | false | false |
ennioma/Buttons-Sequence-View-03 | Buttons-Sequence-View-03/Buttons-Sequence-View-03/SourceCode/ButtonsSequenceView/ButtonsSequenceView.swift | 1 | 1185 | //
// ButtonsSequenceView.swift
// Buttons-Sequence-View-03
//
// Created by Ennio Masi on 22/09/15.
// Copyright © 2015 ennioma. All rights reserved.
//
import UIKit
@objc protocol ButtonsSequenceDelegate: class {
func buttonClickedAtIndex(index: Int)
}
@IBDesignable class ButtonsSequenceView: UIView {
var view: UIView!
weak var delegate: ButtonsSequenceDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
loadXib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadXib()
}
func loadXib() {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "ButtonsSequenceView", bundle: bundle)
view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(view)
}
@IBAction func doAction(sender: AnyObject) {
let index = sender.tag - 2000
if (index >= 0) {
delegate?.buttonClickedAtIndex(index)
}
}
}
| gpl-3.0 | 6fbf9375bff89117b5ef177151692754 | 23.163265 | 73 | 0.605574 | 4.289855 | false | false | false | false |
calkinssean/TIY-Assignments | Day 21/SpotifyAPI/Album.swift | 1 | 1988 | //
// Album.swift
// SpotifyAPI
//
// Created by Sean Calkins on 2/29/16.
// Copyright © 2016 Dape App Productions LLC. All rights reserved.
//
import Foundation
class Album: NSObject, NSCoding {
//NSCoding Constants
let kAlbumTitle = "title"
let kAlbumImageUrls = "imageUrls"
let kAlbumIdString = "idString"
let kAlbumSongs = "songs"
var title: String = ""
var imageUrls: [String] = [""]
var idString: String = ""
var songs = [Song]()
override init() {
}
init(dict: JSONDictionary) {
if
let title = dict["name"] as? String {
self.title = title
print(title)
} else {
print("couldn't parse title")
}
if let idString = dict["id"] as? String {
self.idString = idString
} else {
print("couldn't parse idString")
}
if let items = dict["images"] as? JSONArray {
for item in items {
if let imageUrl = item["url"] as? String {
self.imageUrls.append(imageUrl)
print(imageUrls.count)
} else {
print("error with image url")
}
}
}
}
required init?(coder aDecoder: NSCoder) {
self.title = aDecoder.decodeObjectForKey(kAlbumTitle) as! String
self.imageUrls = aDecoder.decodeObjectForKey(kAlbumImageUrls) as! [String]
self.idString = aDecoder.decodeObjectForKey(kAlbumIdString) as! String
self.songs = aDecoder.decodeObjectForKey(kAlbumSongs) as! [Song]
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey: kAlbumTitle)
aCoder.encodeObject(imageUrls, forKey: kAlbumImageUrls)
aCoder.encodeObject(idString, forKey: kAlbumIdString)
aCoder.encodeObject(songs, forKey: kAlbumSongs)
}
} | cc0-1.0 | 2677c1b52bafbcecbd7f65173c813b83 | 27.4 | 82 | 0.560644 | 4.53653 | false | false | false | false |
Kawoou/FlexibleImage | Sources/Filter/HardLightFilter.swift | 1 | 2433 | //
// HardLightFilter.swift
// FlexibleImage
//
// Created by Kawoou on 2017. 5. 12..
// Copyright © 2017년 test. All rights reserved.
//
#if !os(OSX)
import UIKit
#else
import AppKit
#endif
#if !os(watchOS)
import Metal
#endif
internal class HardLightFilter: ImageFilter {
// MARK: - Property
internal override var metalName: String {
get {
return "HardLightFilter"
}
}
internal var color: FIColorType = (1.0, 1.0, 1.0, 1.0)
// MARK: - Internal
#if !os(watchOS)
@available(OSX 10.11, iOS 8, tvOS 9, *)
internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool {
let factors: [Float] = [color.r, color.g, color.b, color.a]
for i in 0..<factors.count {
var factor = factors[i]
let size = max(MemoryLayout<Float>.size, 16)
let options: MTLResourceOptions
if #available(iOS 9.0, *) {
options = [.storageModeShared]
} else {
options = [.cpuCacheModeWriteCombined]
}
let buffer = device.device.makeBuffer(
bytes: &factor,
length: size,
options: options
)
#if swift(>=4.0)
commandEncoder.setBuffer(buffer, offset: 0, index: i)
#else
commandEncoder.setBuffer(buffer, offset: 0, at: i)
#endif
}
return super.processMetal(device, commandBuffer, commandEncoder)
}
#endif
override func processNone(_ device: ImageNoneDevice) -> Bool {
guard let context = device.context else { return false }
let color = FIColor(
red: CGFloat(self.color.r),
green: CGFloat(self.color.g),
blue: CGFloat(self.color.b),
alpha: CGFloat(self.color.a)
)
context.saveGState()
context.setBlendMode(.hardLight)
context.setFillColor(color.cgColor)
context.fill(device.drawRect!)
context.restoreGState()
return super.processNone(device)
}
}
| mit | 23523a799ce3750cc29d6f29f596ec35 | 26.931034 | 160 | 0.515638 | 4.664107 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/API/Types/Game/Game.swift | 1 | 1389 | //
// Game.swift
// Pelican
//
// Created by Takanu Kyriako on 31/08/2017.
//
import Foundation
/**
This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers.
*/
public struct Game: Codable {
/// Title of the game.
public var title: String
/// Description of the game.
public var description: String
/// Photo that will be displayed in the game message in chats.
public var photo: [Photo]
/// Brief description of the game as well as provide space for high scores.
public var text: String?
/// Special entities that appear in text, such as usernames.
public var textEntities: [MessageEntity]?
/// Animation type that will be displayed in the game message in chats. Upload via BotFather
public var animation: Animation?
/// Coding keys to map values when Encoding and Decoding.
enum CodingKeys: String, CodingKey {
case title
case description
case photo
case text
case textEntities = "text_entities"
case animation
}
public init(title: String,
description: String,
photo: [Photo],
text: String? = nil,
textEntities: [MessageEntity]? = nil,
animation: Animation? = nil) {
self.title = title
self.description = description
self.photo = photo
self.text = text
self.textEntities = textEntities
self.animation = animation
}
}
| mit | 15d1241ce3c385c47ed291ba63a9f6a4 | 21.770492 | 120 | 0.697624 | 3.837017 | false | false | false | false |
donald-pinckney/Ideal-Gas-Simulator | Thermo/ExSwift/Array.swift | 1 | 29710 | //
// Array.swift
// ExSwift
//
// Created by pNre on 03/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
internal extension Array {
private var indexesInterval: HalfOpenInterval<Int> { return HalfOpenInterval<Int>(0, self.count) }
/**
Checks if self contains a list of items.
:param: items Items to search for
:returns: true if self contains all the items
*/
func contains <T: Equatable> (items: T...) -> Bool {
return items.all { self.indexOf($0) >= 0 }
}
/**
Difference of self and the input arrays.
:param: values Arrays to subtract
:returns: Difference of self and the input arrays
*/
func difference <T: Equatable> (values: [T]...) -> [T] {
var result = [T]()
elements: for e in self {
if let element = e as? T {
for value in values {
// if a value is in both self and one of the values arrays
// jump to the next iteration of the outer loop
if value.contains(element) {
continue elements
}
}
// element it's only in self
result.append(element)
}
}
return result
}
/**
Intersection of self and the input arrays.
:param: values Arrays to intersect
:returns: Array of unique values contained in all the dictionaries and self
*/
func intersection <U: Equatable> (values: [U]...) -> Array {
var result = self
var intersection = Array()
for (i, value) in enumerate(values) {
// the intersection is computed by intersecting a couple per loop:
// self n values[0], (self n values[0]) n values[1], ...
if (i > 0) {
result = intersection
intersection = Array()
}
// find common elements and save them in first set
// to intersect in the next loop
value.each { (item: U) -> Void in
if result.contains(item) {
intersection.append(item as Element)
}
}
}
return intersection
}
/**
Union of self and the input arrays.
:param: values Arrays
:returns: Union array of unique values
*/
func union <U: Equatable> (values: [U]...) -> Array {
var result = self
for array in values {
for value in array {
if !result.contains(value) {
result.append(value as Element)
}
}
}
return result
}
/**
First element of the array.
:returns: First element of the array if not empty
*/
@availability(*, unavailable, message="use the 'first' property instead") func first () -> Element? {
return first
}
/**
Last element of the array.
:returns: Last element of the array if not empty
*/
@availability(*, unavailable, message="use the 'last' property instead") func last () -> Element? {
return last
}
/**
Index of the first occurrence of item, if found.
:param: item The item to search for
:returns: Index of the matched item or nil
*/
func indexOf <U: Equatable> (item: U) -> Int? {
if item is Element {
return find(unsafeBitCast(self, [U].self), item)
}
return nil
}
/**
Index of the first item that meets the condition.
:param: condition A function which returns a boolean if an element satisfies a given condition or not.
:returns: Index of the first matched item or nil
*/
func indexOf (condition: Element -> Bool) -> Int? {
for (index, element) in enumerate(self) {
if condition(element) {
return index
}
}
return nil
}
/**
Gets the index of the last occurrence of item, if found.
:param: item The item to search for
:returns: Index of the matched item or nil
*/
func lastIndexOf <U: Equatable> (item: U) -> Int? {
if item is Element {
for (index, value) in enumerate(lazy(self).reverse()) {
if value as U == item {
return count - 1 - index
}
}
return nil
}
return nil
}
/**
Gets the object at the specified index, if it exists.
:param: index
:returns: Object at index in self
*/
func get (index: Int) -> Element? {
// If the index is out of bounds it's assumed relative
func relativeIndex (index: Int) -> Int {
var _index = (index % count)
if _index < 0 {
_index = count + _index
}
return _index
}
let _index = relativeIndex(index)
return _index < count ? self[_index] : nil
}
/**
Gets the objects in the specified range.
:param: range
:returns: Subarray in range
*/
func get (range: Range<Int>) -> Array {
return self[rangeAsArray: range]
}
/**
Returns an array of grouped elements, the first of which contains the first elements
of the given arrays, the 2nd contains the 2nd elements of the given arrays, and so on.
:param: arrays Arrays to zip
:returns: Array of grouped elements
*/
func zip (arrays: [Any]...) -> [[Any?]] {
var result = [[Any?]]()
// Gets the longest array length
let max = arrays.map { (array: [Any]) -> Int in
return array.count
}.max() as Int
for i in 0..<max {
// i-th element in self as array + every i-th element in each array in arrays
result.append([get(i)] + arrays.map { (array) -> Any? in
return array.get(i)
})
}
return result
}
/**
Produces an array of arrays, each containing n elements, each offset by step.
If the final partition is not n elements long it is dropped.
:param: n The number of elements in each partition.
:param: step The number of elements to progress between each partition. Set to n if not supplied.
:returns: Array partitioned into n element arrays, starting step elements apart.
*/
func partition (var n: Int, var step: Int? = nil) -> [Array] {
var result = [Array]()
// If no step is supplied move n each step.
if step == nil {
step = n
}
if step < 1 { step = 1 } // Less than 1 results in an infinite loop.
if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason.
if n > count { return [[]] }
for i in stride(from: 0, through: count - n, by: step!) {
result += [self[i..<(i + n)]]
}
return result
}
/**
Produces an array of arrays, each containing n elements, each offset by step.
:param: n The number of elements in each partition.
:param: step The number of elements to progress between each partition. Set to n if not supplied.
:param: pad An array of elements to pad the last partition if it is not long enough to
contain n elements. If nil is passed or there are not enough pad elements
the last partition may less than n elements long.
:returns: Array partitioned into n element arrays, starting step elements apart.
*/
func partition (var n: Int, var step: Int? = nil, pad: Array?) -> [Array] {
var result = [Array]()
// If no step is supplied move n each step.
if step == nil {
step = n
}
// Less than 1 results in an infinite loop.
if step < 1 {
step = 1
}
// Allow 0 if user wants [[],[],[]] for some reason.
if n < 1 {
n = 0
}
for i in stride(from: 0, to: count, by: step!) {
var end = i + n
if end > count {
end = count
}
result += [self[i..end]]
if end != i + n {
break
}
}
if let padding = pad {
let remaining = count % n
result[result.count - 1] += padding[0..<remaining] as Array
}
return result
}
/**
Produces an array of arrays, each containing n elements, each offset by step.
:param: n The number of elements in each partition.
:param: step The number of elements to progress between each partition. Set to n if not supplied.
:returns: Array partitioned into n element arrays, starting step elements apart.
*/
func partitionAll (var n: Int, var step: Int? = nil) -> [Array] {
var result = [Array]()
// If no step is supplied move n each step.
if step == nil {
step = n
}
if step < 1 { step = 1 } // Less than 1 results in an infinite loop.
if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason.
for i in stride(from: 0, to: count, by: step!) {
result += [self[i..(i + n)]]
}
return result
}
/**
Applies cond to each element in array, splitting it each time cond returns a new value.
:param: cond Function which takes an element and produces an equatable result.
:returns: Array partitioned in order, splitting via results of cond.
*/
func partitionBy <T: Equatable> (cond: (Element) -> T) -> [Array] {
var result = [Array]()
var lastValue: T? = nil
for item in self {
let value = cond(item)
if value == lastValue! {
let index: Int = result.count - 1
result[index] += [item]
} else {
result.append([item])
lastValue = value
}
}
return result
}
/**
Randomly rearranges the elements of self using the Fisher-Yates shuffle
*/
mutating func shuffle () {
for var i = self.count - 1; i >= 1; i-- {
let j = Int.random(max: i)
swap(&self[i], &self[j])
}
}
/**
Shuffles the values of the array into a new one
:returns: Shuffled copy of self
*/
func shuffled () -> Array {
var shuffled = self
shuffled.shuffle()
return shuffled
}
/**
Returns a random subarray of given length.
:param: n Length
:returns: Random subarray of length n
*/
func sample (size n: Int = 1) -> Array {
if n >= count {
return self
}
let index = Int.random(max: count - n)
return self[index..<(n + index)]
}
/**
Max value in the current array (if Array.Element implements the Comparable protocol).
:returns: Max value
*/
func max <U: Comparable> () -> U {
return maxElement(map {
return $0 as U
})
}
/**
Min value in the current array (if Array.Element implements the Comparable protocol).
:returns: Min value
*/
func min <U: Comparable> () -> U {
return minElement(map {
return $0 as U
})
}
/**
The value for which call(value) is highest.
:returns: Max value in terms of call(value)
*/
func maxBy <U: Comparable> (call: (Element) -> (U)) -> Element? {
if let firstValue = self.first {
var maxElement: T = firstValue
var maxValue: U = call(firstValue)
for i in 1..<self.count {
let element: Element = self[i]
let value: U = call(element)
if value > maxValue {
maxElement = element
maxValue = value
}
}
return maxElement
} else {
return nil
}
}
/**
The value for which call(value) is lowest.
:returns: Min value in terms of call(value)
*/
func minBy <U: Comparable> (call: (Element) -> (U)) -> Element? {
if let firstValue = self.first {
var maxElement: T = firstValue
var minValue: U = call(firstValue)
for i in 1..<self.count {
let element: Element = self[i]
let value: U = call(element)
if value < minValue {
maxElement = element
minValue = value
}
}
return maxElement
} else {
return nil
}
}
/**
Iterates on each element of the array.
:param: call Function to call for each element
*/
func each (call: (Element) -> ()) {
for item in self {
call(item)
}
}
/**
Iterates on each element of the array with its index.
:param: call Function to call for each element
*/
func each (call: (Int, Element) -> ()) {
for (index, item) in enumerate(self) {
call(index, item)
}
}
/**
Iterates on each element of the array from Right to Left.
:param: call Function to call for each element
*/
func eachRight (call: (Element) -> ()) {
reverse().each(call)
}
/**
Iterates on each element of the array, with its index, from Right to Left.
:param: call Function to call for each element
*/
func eachRight (call: (Int, Element) -> ()) {
for (index, item) in enumerate(reverse()) {
call(count - index - 1, item)
}
}
/**
Checks if test returns true for any element of self.
:param: test Function to call for each element
:returns: true if test returns true for any element of self
*/
func any (test: (Element) -> Bool) -> Bool {
for item in self {
if test(item) {
return true
}
}
return false
}
/**
Checks if test returns true for all the elements in self
:param: test Function to call for each element
:returns: True if test returns true for all the elements in self
*/
func all (test: (Element) -> Bool) -> Bool {
for item in self {
if !test(item) {
return false
}
}
return true
}
/**
Opposite of filter.
:param: exclude Function invoked to test elements for the exclusion from the array
:returns: Filtered array
*/
func reject (exclude: (Element -> Bool)) -> Array {
return filter {
return !exclude($0)
}
}
/**
Returns an array containing the first n elements of self.
:param: n Number of elements to take
:returns: First n elements
*/
func take (n: Int) -> Array {
return self[0..<Swift.max(0, n)]
}
/**
Returns the elements of the array up until an element does not meet the condition.
:param: condition A function which returns a boolean if an element satisfies a given condition or not.
:returns: Elements of the array up until an element does not meet the condition
*/
func takeWhile (condition: (Element) -> Bool) -> Array {
var lastTrue = -1
for (index, value) in enumerate(self) {
if condition(value) {
lastTrue = index
} else {
break
}
}
return take(lastTrue + 1)
}
/**
Returns the first element in the array to meet the condition.
:param: condition A function which returns a boolean if an element satisfies a given condition or not.
:returns: The first element in the array to meet the condition
*/
func takeFirst (condition: (Element) -> Bool) -> Element? {
for value in self {
if condition(value) {
return value
}
}
return nil
}
/**
Returns an array containing the the last n elements of self.
:param: n Number of elements to take
:returns: Last n elements
*/
func tail (n: Int) -> Array {
return self[(count - n)..<count]
}
/**
Subarray from n to the end of the array.
:param: n Number of elements to skip
:returns: Array from n to the end
*/
func skip (n: Int) -> Array {
return n > count ? [] : self[n..<count]
}
/**
Skips the elements of the array up until the condition returns false.
:param: condition A function which returns a boolean if an element satisfies a given condition or not
:returns: Elements of the array starting with the element which does not meet the condition
*/
func skipWhile (condition: (Element) -> Bool) -> Array {
var lastTrue = -1
for (index, value) in enumerate(self) {
if condition(value) {
lastTrue = index
} else {
break
}
}
return skip(lastTrue + 1)
}
/**
Costructs an array removing the duplicate values in self
if Array.Element implements the Equatable protocol.
:returns: Array of unique values
*/
func unique <T: Equatable> () -> [T] {
var result = [T]()
for item in self {
if !result.contains(item as T) {
result.append(item as T)
}
}
return result
}
/**
Returns the set of elements for which call(element) is unique
:param: call The closure to use to determine uniqueness
:returns: The set of elements for which call(element) is unique
*/
func uniqueBy <T: Equatable> (call: (Element) -> (T)) -> [Element] {
var result: [Element] = []
var uniqueItems: [T] = []
for item in self {
var callResult: T = call(item)
if !uniqueItems.contains(callResult) {
uniqueItems.append(callResult)
result.append(item)
}
}
return result
}
/**
Creates a dictionary composed of keys generated from the results of
running each element of self through groupingFunction. The corresponding
value of each key is an array of the elements responsible for generating the key.
:param: groupingFunction
:returns: Grouped dictionary
*/
func groupBy <U> (groupingFunction group: (Element) -> U) -> [U: Array] {
var result = [U: Array]()
for item in self {
let groupKey = group(item)
// If element has already been added to dictionary, append to it. If not, create one.
if result.has(groupKey) {
result[groupKey]! += [item]
} else {
result[groupKey] = [item]
}
}
return result
}
/**
Similar to groupBy, instead of returning a list of values,
returns the number of values for each group.
:param: groupingFunction
:returns: Grouped dictionary
*/
func countBy <U> (groupingFunction group: (Element) -> U) -> [U: Int] {
var result = [U: Int]()
for item in self {
let groupKey = group(item)
if result.has(groupKey) {
result[groupKey]!++
} else {
result[groupKey] = 1
}
}
return result
}
/**
Returns all of the combinations in the array of the given length
:param: length
:returns: Combinations
*/
func combination (length: Int) -> [[Element]] {
if length < 0 || length > self.count {
return []
}
var indexes: [Int] = (0..<length).toArray()
var combinations: [[Element]] = []
var offset = self.count - indexes.count
while true {
var combination: [Element] = []
for index in indexes {
combination.append(self[index])
}
combinations.append(combination)
var i = indexes.count - 1
while i >= 0 && indexes[i] == i + offset {
i--
}
if i < 0 {
break
}
i++
var start = indexes[i-1] + 1
for j in (i-1)..<indexes.count {
indexes[j] = start + j - i + 1
}
}
return combinations
}
/**
Returns the number of elements which meet the condition
:param: test Function to call for each element
:returns: the number of elements meeting the condition
*/
func countWhere (test: (Element) -> Bool) -> Int {
var result = 0
for item in self {
if test(item) {
result++
}
}
return result
}
/**
Joins the array elements with a separator.
:param: separator
:return: Joined object if self is not empty and its elements are instances of C, nil otherwise
*/
func implode <C: ExtensibleCollectionType> (separator: C) -> C? {
if Element.self is C.Type {
return Swift.join(separator, unsafeBitCast(self, [C].self))
}
return nil
}
/**
Creates an array with values generated by running each value of self
through the mapFunction and discarding nil return values.
:param: mapFunction
:returns: Mapped array
*/
func mapFilter <V> (mapFunction map: (Element) -> (V)?) -> [V] {
var mapped = [V]()
each { (value: Element) -> Void in
if let mappedValue = map(value) {
mapped.append(mappedValue)
}
}
return mapped
}
/**
self.reduce with initial value self.first()
*/
func reduce (combine: (Element, Element) -> Element) -> Element? {
if let firstElement = first {
return skip(1).reduce(firstElement, combine: combine)
}
return nil
}
/**
self.reduce from right to left
*/
func reduceRight <U> (initial: U, combine: (U, Element) -> U) -> U {
return reverse().reduce(initial, combine: combine)
}
/**
self.reduceRight with initial value self.last()
*/
func reduceRight (combine: (Element, Element) -> Element) -> Element? {
return reverse().reduce(combine)
}
/**
Creates an array with the elements at the specified indexes.
:param: indexes Indexes of the elements to get
:returns: Array with the elements at indexes
*/
func at (indexes: Int...) -> Array {
return indexes.map { self.get($0)! }
}
/**
Converts the array to a dictionary with the keys supplied via the keySelector.
:param: keySelector
:returns: A dictionary
*/
func toDictionary <U> (keySelector:(Element) -> U) -> [U: Element] {
var result: [U: Element] = [:]
for item in self {
result[keySelector(item)] = item
}
return result
}
/**
Flattens a nested Array self to an array of OutType objects.
:returns: Flattened array
*/
func flatten <OutType> () -> [OutType] {
var result = [OutType]()
let reflection = reflect(self)
for i in 0..<reflection.count {
result += Ex.bridgeObjCObject(reflection[i].1.value) as [OutType]
}
return result
}
/**
Flattens a nested Array self to an array of AnyObject.
:returns: Flattened array
*/
func flattenAny () -> [AnyObject] {
var result = [AnyObject]()
for item in self {
if let array = item as? NSArray {
result += array.flattenAny()
} else if let object = item as? NSObject {
result.append(object)
}
}
return result
}
/**
Sorts the array according to the given comparison function.
:param: isOrderedBefore Comparison function.
:returns: An array that is sorted according to the given function
*/
func sortBy (isOrderedBefore: (T, T) -> Bool) -> [T] {
return sorted(isOrderedBefore)
}
/**
Removes the last element from self and returns it.
:returns: The removed element
*/
mutating func pop () -> Element {
return removeLast()
}
/**
Same as append.
:param: newElement Element to append
*/
mutating func push (newElement: Element) {
return append(newElement)
}
/**
Returns the first element of self and removes it from the array.
:returns: The removed element
*/
mutating func shift () -> Element {
return removeAtIndex(0)
}
/**
Prepends an object to the array.
:param: newElement Object to prepend
*/
mutating func unshift (newElement: Element) {
insert(newElement, atIndex: 0)
}
/**
Inserts an array at a given index in self.
:param: newArray Array to insert
:param: atIndex Where to insert the array
*/
mutating func insert (newArray: Array, atIndex: Int) {
self = take(atIndex) + newArray + skip(atIndex)
}
/**
Deletes all the items in self that are equal to element.
:param: element Element to remove
*/
mutating func remove<U: Equatable, Element> (element: Element) {
fatalError("NOT IMPLEMENTED!")
}
/**
Constructs an array containing the values in the given range.
:param: range
:returns: Array of values
*/
static func range <U: ForwardIndexType> (range: Range<U>) -> [U] {
return [U](range)
}
/**
Returns the subarray in the given range.
:param: range Range of the subarray elements
:returns: Subarray or nil if the index is out of bounds
*/
subscript (#rangeAsArray: Range<Int>) -> Array {
// Fix out of bounds indexes
let start = Swift.max(0, rangeAsArray.startIndex)
let end = Swift.min(rangeAsArray.endIndex, count)
if start > end {
return []
}
return Array(self[Range(start: start, end: end)] as Slice<T>)
}
/**
Returns a subarray whose items are in the given interval in self.
:param: interval Interval of indexes of the subarray elements
:returns: Subarray or nil if the index is out of bounds
*/
subscript (interval: HalfOpenInterval<Int>) -> Array {
return self[rangeAsArray: Range(start: interval.start, end: interval.end)]
}
/**
Returns a subarray whose items are in the given interval in self.
:param: interval Interval of indexes of the subarray elements
:returns: Subarray or nil if the index is out of bounds
*/
subscript (interval: ClosedInterval<Int>) -> Array {
return self[rangeAsArray: Range(start: interval.start, end: interval.end + 1)]
}
/**
Creates an array with the elements at indexes in the given list of integers.
:param: first First index
:param: second Second index
:param: rest Rest of indexes
:returns: Array with the items at the specified indexes
*/
subscript (first: Int, second: Int, rest: Int...) -> Array {
let indexes = [first, second] + rest
return indexes.map { self[$0] }
}
}
/**
Remove an element from the array
*/
public func - <T: Equatable> (first: Array<T>, second: T) -> Array<T> {
return first - [second]
}
/**
Difference operator
*/
public func - <T: Equatable> (first: Array<T>, second: Array<T>) -> Array<T> {
return first.difference(second)
}
/**
Intersection operator
*/
public func & <T: Equatable> (first: Array<T>, second: Array<T>) -> Array<T> {
return first.intersection(second)
}
/**
Union operator
*/
public func | <T: Equatable> (first: Array<T>, second: Array<T>) -> Array<T> {
return first.union(second)
}
/**
Array duplication.
:param: array Array to duplicate
:param: n How many times the array must be repeated
:returns: Array of repeated values
*/
public func * <ItemType> (array: Array<ItemType>, n: Int) -> Array<ItemType> {
var result = Array<ItemType>()
n.times {
result += array
}
return result
}
/**
Array items concatenation à la Ruby.
:param: array Array of Strings to join
:param: separator Separator to join the array elements
:returns: Joined string
*/
public func * (array: Array<String>, separator: String) -> String {
return array.implode(separator)!
}
| mit | 7f3b9f8ce685fe6ba465c969cd3ac2f1 | 25.813177 | 110 | 0.529806 | 4.591099 | false | false | false | false |
facile-it/Monads | Sources/ResultType.swift | 2 | 5120 | import Abstract
import Functional
// MARK: - Definition
// sourcery: map, joined, reducible
// sourcery: concrete = "Result"
// sourcery: transformer1, transformer2
// sourcery: secondaryParameter = "ErrorType"
// sourcery: secondaryParameterRequiredProtocols = "Error"
public protocol ResultType: PureConstructible {
associatedtype ErrorType: Error
init(_ error: ErrorType)
init()
func run() throws -> ElementType?
func fold <A> (ifSuccess: (ElementType) -> A, ifFailure: (ErrorType) -> A, ifCancel: () -> A) -> A
}
// MARK: - Concrete
// sourcery: secondaryParameter
// sourcery: secondaryParameterRequiredProtocols = "Error"
// sourcery: functorLaws, applicativeLaws, monadLaws
// sourcery: fixedTypesForTests = "Int"
// sourcery: fixedSecondaryParameterForTests = "AnyError"
// sourcery: arbitrary
// sourcery: arbitraryAdditionalParameterForGeneric = "E"
// sourcery: arbitraryAdditionalGenericParameterProtocols = "Error & Arbitrary"
public enum Result<T,E>: ResultType where E: Error {
public typealias ElementType = T
public typealias ErrorType = E
case success(T)
case failure(E)
case cancel
public static func pure(_ value: ElementType) -> Result {
return .success(value)
}
public init(_ error: ErrorType) {
self = .failure(error)
}
public init() {
self = .cancel
}
public func fold<A>(ifSuccess: (T) -> A, ifFailure: (E) -> A, ifCancel: () -> A) -> A {
switch self {
case .success(let value):
return ifSuccess(value)
case .failure(let error):
return ifFailure(error)
case .cancel:
return ifCancel()
}
}
public func run() throws -> ElementType? {
switch self {
case .success(let value):
return value
case .failure(let error):
throw error
case .cancel:
return nil
}
}
}
extension Result where T: Equatable, E: Equatable {
public static func == (left: Result, right: Result) -> Bool {
switch (left,right) {
case (.success(let leftValue), .success(let rightValue)):
return leftValue == rightValue
case (.failure(let leftError), .failure(let rightError)):
return leftError == rightError
case (.cancel,.cancel):
return true
default:
return false
}
}
}
// MARK: - Functor
extension ResultType {
public func map <A> (_ transform: @escaping (ElementType) -> A) -> Result<A,ErrorType> {
return fold(
ifSuccess: { .success(transform($0)) },
ifFailure: { .failure($0) },
ifCancel: { .cancel })
}
}
// MARK: - Joined
extension ResultType where ElementType: ResultType, ElementType.ErrorType == ErrorType {
public var joined: Result<ElementType.ElementType,ErrorType> {
return fold(
ifSuccess: { $0.fold(
ifSuccess: { .success($0) },
ifFailure: { .failure($0) },
ifCancel: { .cancel }) },
ifFailure: { .failure($0) },
ifCancel: { .cancel })
}
}
// MARK: - Custom Zip (ErrorType: Semigroup)
extension ResultType where ErrorType: Semigroup {
public static func zip <A,B> (_ a: A, _ b: B) -> Result<(A.ElementType,B.ElementType),ErrorType> where A: ResultType, B: ResultType, A.ErrorType == ErrorType, B.ErrorType == ErrorType, ElementType == (A.ElementType,B.ElementType) {
return a.fold(
ifSuccess: { aValue in b.fold(
ifSuccess: { bValue in .success((aValue,bValue)) },
ifFailure: { bError in .failure(bError) },
ifCancel: { .cancel }) },
ifFailure: { aError in b.fold(
ifSuccess: { _ in .failure(aError) },
ifFailure: { bError in .failure(aError <> bError)},
ifCancel: { .cancel }) },
ifCancel: { .cancel })
}
}
// MARK: - Reducible
extension ResultType {
static var neutral: Result<ElementType,ErrorType> {
return .cancel
}
static func appending(_ x: ElementType) -> Endo<Result<ElementType,ErrorType>> {
return { $0.fold(
ifSuccess: Result.success,
ifFailure: { _ in Result.success(x) },
ifCancel: { Result.success(x) })
}
}
}
extension Result: Reducible {
public typealias ReducibleElementType = ElementType
public func reduce<T>(_ initialResult: T, _ nextPartialResult: (T, ElementType) throws -> T) rethrows -> T {
switch self {
case .success(let value):
return try nextPartialResult(initialResult,value)
case .failure:
return initialResult
case .cancel:
return initialResult
}
}
}
// MARK: Utility
extension ResultType {
public func mapError<E>(_ transform: @escaping (ErrorType) -> E) -> Result<ElementType,E> {
return fold(
ifSuccess: Result.success,
ifFailure: Result.failure • transform,
ifCancel: { Result.cancel })
}
public func fallback(to defaultValue: ElementType) -> Result<ElementType,ErrorType> {
return fold(
ifSuccess: Result.success,
ifFailure: { _ in Result.success(defaultValue) },
ifCancel: { Result.success(defaultValue) })
}
public var toOptionalValue: ElementType? {
return fold(
ifSuccess: F.identity,
ifFailure: { _ in nil },
ifCancel: { nil })
}
public var toOptionalError: ErrorType? {
return fold(
ifSuccess: { _ in nil },
ifFailure: F.identity,
ifCancel: { nil })
}
public var isCanceled: Bool {
return fold(
ifSuccess: { _ in false },
ifFailure: { _ in false },
ifCancel: { true })
}
}
| mit | 5d370936ae67c34106059ff1c23cd80e | 24.979695 | 232 | 0.67839 | 3.441829 | false | false | false | false |
wibosco/ConvenientFileManager | Examples/Swift Example/SwiftExample/Stories/List/ListViewController.swift | 1 | 4020 | //
// ListViewController.swift
// SwiftExample
//
// Created by William Boles on 11/11/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
import ConvenientFileManager
class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var images = [Media]()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var addMediaBarButtonItem: UIBarButtonItem!
lazy var imagePickerViewController: UIImagePickerController = {
let imagePickerViewController = UIImagePickerController()
imagePickerViewController.delegate = self
imagePickerViewController.modalPresentationStyle = .currentContext
imagePickerViewController.sourceType = .savedPhotosAlbum
return imagePickerViewController
}()
//MARK: ViewLifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 100.0
addMediaBarButtonItem.action = #selector(ListViewController.addMediaButtonPressed)
addMediaBarButtonItem.target = self
}
//MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MediaTableViewCell", for: indexPath) as! MediaTableViewCell
let media = images[indexPath.row]
cell.locationLabel.text = media.location.rawValue.capitalized
cell.mediaImageView.image = loadImageFromMediaSavedLocation(media: media)
return cell
}
//MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let media = images[indexPath.row]
switch media.location {
case .cache:
FileManager.deleteDataFromCacheDirectory(relativePath: media.name)
case .documents:
FileManager.deleteDataFromDocumentsDirectory(relativePath: media.name)
}
images.remove(at: indexPath.row)
tableView.reloadData()
}
//MARK: Media
func loadImageFromMediaSavedLocation(media: Media) -> UIImage? {
let imageData: Data?
switch media.location {
case .cache:
imageData = FileManager.retrieveDataFromCacheDirectory(relativePath: media.name)
case .documents:
imageData = FileManager.retrieveDataFromDocumentsDirectory(relativePath: media.name)
}
guard let unwrappedImageData = imageData else {
return nil
}
return UIImage(data: unwrappedImageData)
}
//MARK: ButtonActions
func addMediaButtonPressed(sender: UIBarButtonItem) {
present(imagePickerViewController, animated: true, completion: nil)
}
//MARK: UIImagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage, let imageData = UIImagePNGRepresentation(image) else {
return
}
let media = Media(name: UUID().uuidString, location: Location.randomLocation())
switch media.location {
case .cache:
FileManager.writeToCacheDirectory(data: imageData, relativePath: media.name)
case .documents:
FileManager.writeToDocumentsDirectory(data: imageData, relativePath: media.name)
}
images.append(media)
picker.dismiss(animated: true, completion: { [weak self] in
self?.tableView.reloadData()
})
}
}
| mit | 46ca81bf9d4be0911609de819072c6ca | 32.773109 | 153 | 0.668823 | 5.858601 | false | false | false | false |
keyeMyria/edx-app-ios | Test/Result+Assertions.swift | 7 | 776 | //
// Result+Assertions.swift
// edX
//
// Created by Akiva Leffert on 5/26/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import edX
func AssertSuccess<A>(result : Result<A> , file : String = __FILE__, line : UInt = __LINE__, assertions : (A -> Void)? = nil) {
switch result {
case let .Success(r): assertions?(r.value)
case let .Failure(e): XCTFail("Unexpected failure: \(e.localizedDescription)", file : file, line : line)
}
}
func AssertFailure<A>(result : Result<A> , file : String = __FILE__, line : UInt = __LINE__, assertions : (NSError -> Void)? = nil) {
switch result {
case let .Success(r): XCTFail("Unexpected success: \(r.value)", file : file, line : line)
case let .Failure(e): assertions?(e)
}
}
| apache-2.0 | 7dc09876f7fb318e98801979dc317fc2 | 31.333333 | 133 | 0.625 | 3.418502 | false | false | false | false |
ncalexan/firefox-ios | Client/Frontend/Home/HomePanelViewController.swift | 1 | 14007 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SnapKit
import UIKit
import Storage // For VisitType.
private struct HomePanelViewControllerUX {
// Height of the top panel switcher button toolbar.
static let ButtonContainerHeight: CGFloat = 40
static let ButtonContainerBorderColor = UIColor.black.withAlphaComponent(0.1)
static let BackgroundColorNormalMode = UIConstants.PanelBackgroundColor
static let BackgroundColorPrivateMode = UIConstants.PrivateModeAssistantToolbarBackgroundColor
static let ToolbarButtonDeselectedColorNormalMode = UIColor(white: 0.2, alpha: 0.5)
static let ToolbarButtonDeselectedColorPrivateMode = UIColor(white: 0.9, alpha: 1)
}
protocol HomePanelViewControllerDelegate: class {
func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType)
func homePanelViewController(_ HomePanelViewController: HomePanelViewController, didSelectPanel panel: Int)
func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController)
func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController)
func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool)
}
protocol HomePanel: class {
weak var homePanelDelegate: HomePanelDelegate? { get set }
}
struct HomePanelUX {
static let EmptyTabContentOffset = -180
}
protocol HomePanelDelegate: class {
func homePanelDidRequestToSignIn(_ homePanel: HomePanel)
func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel)
func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool)
func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType)
func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType)
}
struct HomePanelState {
var selectedIndex: Int = 0
}
enum HomePanelType: Int {
case topSites = 0
case bookmarks = 1
case history = 2
case readingList = 3
var localhostURL: URL {
return URL(string:"#panel=\(self.rawValue)", relativeTo: UIConstants.AboutHomePage as URL)!
}
}
class HomePanelViewController: UIViewController, UITextFieldDelegate, HomePanelDelegate {
var profile: Profile!
var notificationToken: NSObjectProtocol!
var panels: [HomePanelDescriptor]!
var url: URL?
weak var delegate: HomePanelViewControllerDelegate?
fileprivate var buttonContainerView: UIView!
fileprivate var buttonContainerBottomBorderView: UIView!
fileprivate var controllerContainerView: UIView!
fileprivate var buttons: [UIButton] = []
var homePanelState: HomePanelState {
return HomePanelState(selectedIndex: selectedPanel?.rawValue ?? 0)
}
override func viewDidLoad() {
view.backgroundColor = HomePanelViewControllerUX.BackgroundColorNormalMode
let blur: UIVisualEffectView? = DeviceInfo.isBlurSupported() ? UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light)) : nil
if let blur = blur {
view.addSubview(blur)
}
buttonContainerView = UIView()
buttonContainerView.backgroundColor = HomePanelViewControllerUX.BackgroundColorNormalMode
buttonContainerView.clipsToBounds = true
buttonContainerView.accessibilityNavigationStyle = .combined
buttonContainerView.accessibilityLabel = NSLocalizedString("Panel Chooser", comment: "Accessibility label for the Home panel's top toolbar containing list of the home panels (top sites, bookmarsk, history, remote tabs, reading list).")
view.addSubview(buttonContainerView)
self.buttonContainerBottomBorderView = UIView()
buttonContainerView.addSubview(buttonContainerBottomBorderView)
buttonContainerBottomBorderView.backgroundColor = HomePanelViewControllerUX.ButtonContainerBorderColor
controllerContainerView = UIView()
view.addSubview(controllerContainerView)
blur?.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
buttonContainerView.snp.makeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(HomePanelViewControllerUX.ButtonContainerHeight)
}
buttonContainerBottomBorderView.snp.makeConstraints { make in
make.top.equalTo(self.buttonContainerView.snp.bottom).offset(-1)
make.left.right.bottom.equalTo(self.buttonContainerView)
}
controllerContainerView.snp.makeConstraints { make in
make.top.equalTo(self.buttonContainerView.snp.bottom)
make.left.right.bottom.equalTo(self.view)
}
self.panels = HomePanels().enabledPanels
updateButtons()
// Gesture recognizer to dismiss the keyboard in the URLBarView when the buttonContainerView is tapped
let dismissKeyboardGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(HomePanelViewController.SELhandleDismissKeyboardGestureRecognizer(_:)))
dismissKeyboardGestureRecognizer.cancelsTouchesInView = false
buttonContainerView.addGestureRecognizer(dismissKeyboardGestureRecognizer)
}
func SELhandleDismissKeyboardGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) {
view.window?.rootViewController?.view.endEditing(true)
}
var selectedPanel: HomePanelType? = nil {
didSet {
if oldValue == selectedPanel {
// Prevent flicker, allocations, and disk access: avoid duplicate view controllers.
return
}
if let index = oldValue?.rawValue {
if index < buttons.count {
let currentButton = buttons[index]
currentButton.isSelected = false
currentButton.isUserInteractionEnabled = true
}
}
hideCurrentPanel()
if let index = selectedPanel?.rawValue {
if index < buttons.count {
let newButton = buttons[index]
newButton.isSelected = true
newButton.isUserInteractionEnabled = false
}
if index < panels.count {
let panel = self.panels[index].makeViewController(profile)
let accessibilityLabel = self.panels[index].accessibilityLabel
if let panelController = panel as? UINavigationController,
let rootPanel = panelController.viewControllers.first {
setupHomePanel(rootPanel, accessibilityLabel: accessibilityLabel)
self.showPanel(panelController)
} else {
setupHomePanel(panel, accessibilityLabel: accessibilityLabel)
self.showPanel(panel)
}
}
}
self.updateButtonTints()
}
}
func setupHomePanel(_ panel: UIViewController, accessibilityLabel: String) {
(panel as? HomePanel)?.homePanelDelegate = self
panel.view.accessibilityNavigationStyle = .combined
panel.view.accessibilityLabel = accessibilityLabel
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
fileprivate func hideCurrentPanel() {
if let panel = childViewControllers.first {
panel.willMove(toParentViewController: nil)
panel.beginAppearanceTransition(false, animated: false)
panel.view.removeFromSuperview()
panel.endAppearanceTransition()
panel.removeFromParentViewController()
}
}
fileprivate func showPanel(_ panel: UIViewController) {
addChildViewController(panel)
panel.beginAppearanceTransition(true, animated: false)
controllerContainerView.addSubview(panel.view)
panel.endAppearanceTransition()
panel.view.snp.makeConstraints { make in
make.top.equalTo(self.buttonContainerView.snp.bottom)
make.left.right.bottom.equalTo(self.view)
}
panel.didMove(toParentViewController: self)
}
func SELtappedButton(_ sender: UIButton!) {
for (index, button) in buttons.enumerated() where button == sender {
selectedPanel = HomePanelType(rawValue: index)
delegate?.homePanelViewController(self, didSelectPanel: index)
break
}
}
fileprivate func updateButtons() {
// Remove any existing buttons if we're rebuilding the toolbar.
for button in buttons {
button.removeFromSuperview()
}
buttons.removeAll()
var prev: UIView? = nil
for panel in panels {
let button = UIButton()
buttonContainerView.addSubview(button)
button.addTarget(self, action: #selector(HomePanelViewController.SELtappedButton(_:)), for: UIControlEvents.touchUpInside)
if let image = UIImage.templateImageNamed("panelIcon\(panel.imageName)") {
button.setImage(image, for: UIControlState.normal)
}
if let image = UIImage.templateImageNamed("panelIcon\(panel.imageName)Selected") {
button.setImage(image, for: UIControlState.selected)
}
button.accessibilityLabel = panel.accessibilityLabel
button.accessibilityIdentifier = panel.accessibilityIdentifier
buttons.append(button)
button.snp.remakeConstraints { make in
let left = prev?.snp.right ?? self.view.snp.left
make.left.equalTo(left)
make.height.centerY.equalTo(self.buttonContainerView)
make.width.equalTo(self.buttonContainerView).dividedBy(self.panels.count)
}
prev = button
}
}
func updateButtonTints() {
for (index, button) in self.buttons.enumerated() {
if index == self.selectedPanel?.rawValue {
button.tintColor = UIConstants.HighlightBlue
} else {
button.tintColor = HomePanelViewControllerUX.ToolbarButtonDeselectedColorNormalMode
}
}
}
func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) {
// If we can't get a real URL out of what should be a URL, we let the user's
// default search engine give it a shot.
// Typically we'll be in this state if the user has tapped a bookmarked search template
// (e.g., "http://foo.com/bar/?query=%s"), and this will get them the same behavior as if
// they'd copied and pasted into the URL bar.
// See BrowserViewController.urlBar:didSubmitText:.
guard let url = URIFixup.getURL(url) ??
profile.searchEngines.defaultEngine.searchURLForQuery(url) else {
Logger.browserLogger.warning("Invalid URL, and couldn't generate a search URL for it.")
return
}
return self.homePanel(homePanel, didSelectURL: url, visitType: visitType)
}
func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) {
delegate?.homePanelViewController(self, didSelectURL: url, visitType: visitType)
dismiss(animated: true, completion: nil)
}
func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) {
delegate?.homePanelViewControllerDidRequestToCreateAccount(self)
}
func homePanelDidRequestToSignIn(_ homePanel: HomePanel) {
delegate?.homePanelViewControllerDidRequestToSignIn(self)
}
func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) {
delegate?.homePanelViewControllerDidRequestToOpenInNewTab(url, isPrivate: isPrivate)
}
}
protocol HomePanelContextMenu {
func getSiteDetails(for indexPath: IndexPath) -> Site?
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]?
func presentContextMenu(for indexPath: IndexPath)
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?)
}
extension HomePanelContextMenu {
func presentContextMenu(for indexPath: IndexPath) {
guard let site = getSiteDetails(for: indexPath) else { return }
presentContextMenu(for: site, with: indexPath, completionHandler: {
return self.contextMenu(for: site, with: indexPath)
})
}
func contextMenu(for site: Site, with indexPath: IndexPath) -> PhotonActionSheet? {
guard let actions = self.getContextMenuActions(for: site, with: indexPath) else { return nil }
let contextMenu = PhotonActionSheet(site: site, actions: actions)
contextMenu.modalPresentationStyle = .overFullScreen
contextMenu.modalTransitionStyle = .crossDissolve
return contextMenu
}
func getDefaultContextMenuActions(for site: Site, homePanelDelegate: HomePanelDelegate?) -> [PhotonActionSheetItem]? {
guard let siteURL = URL(string: site.url) else { return nil }
let openInNewTabAction = PhotonActionSheetItem(title: Strings.OpenInNewTabContextMenuTitle, iconString: "") { action in
homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false)
}
let openInNewPrivateTabAction = PhotonActionSheetItem(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "") { action in
homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true)
}
return [openInNewTabAction, openInNewPrivateTabAction]
}
}
| mpl-2.0 | 1fcbe3bbed52c7c71eaa82bcf625f941 | 41.704268 | 243 | 0.688727 | 5.81686 | false | false | false | false |
emilybache/GildedRose-Refactoring-Kata | swift/Sources/GildedRose/GildedRose.swift | 1 | 2144 | public class GildedRose {
var items: [Item]
public init(items: [Item]) {
self.items = items
}
public func updateQuality() {
for i in 0 ..< items.count {
if items[i].name != "Aged Brie", items[i].name != "Backstage passes to a TAFKAL80ETC concert" {
if items[i].quality > 0 {
if items[i].name != "Sulfuras, Hand of Ragnaros" {
items[i].quality = items[i].quality - 1
}
}
} else {
if items[i].quality < 50 {
items[i].quality = items[i].quality + 1
if items[i].name == "Backstage passes to a TAFKAL80ETC concert" {
if items[i].sellIn < 11 {
if items[i].quality < 50 {
items[i].quality = items[i].quality + 1
}
}
if items[i].sellIn < 6 {
if items[i].quality < 50 {
items[i].quality = items[i].quality + 1
}
}
}
}
}
if items[i].name != "Sulfuras, Hand of Ragnaros" {
items[i].sellIn = items[i].sellIn - 1
}
if items[i].sellIn < 0 {
if items[i].name != "Aged Brie" {
if items[i].name != "Backstage passes to a TAFKAL80ETC concert" {
if items[i].quality > 0 {
if items[i].name != "Sulfuras, Hand of Ragnaros" {
items[i].quality = items[i].quality - 1
}
}
} else {
items[i].quality = items[i].quality - items[i].quality
}
} else {
if items[i].quality < 50 {
items[i].quality = items[i].quality + 1
}
}
}
}
}
}
| mit | 5d2c07bf4fc7e178a35912441fc60862 | 35.338983 | 107 | 0.361007 | 4.513684 | false | false | false | false |
Somnibyte/MLKit | Example/Pods/Upsurge/Source/Operations/PointerUtilities.swift | 1 | 4211 | // Copyright © 2016 Venture Media Labs.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: One parameter
/// Call `body(pointer)` with the pointer for the type
public func withPointer<T: TensorType, R>(_ t: T, body: (UnsafePointer<T.Element>) throws -> R) rethrows -> R {
return try t.withUnsafePointer(body)
}
/// Call `body(pointer)` with the mutable pointer for the type
public func withPointer<T: MutableTensorType, R>(_ t: inout T, body: (UnsafeMutablePointer<T.Element>) throws -> R) rethrows -> R {
return try t.withUnsafeMutablePointer(body)
}
// MARK: Two parameters
/// Call `body(p1, p2)` with the pointers for the two types
public func withPointers<T1: TensorType, T2: TensorType, R>(_ t1: T1, _ t2: T2, body: (UnsafePointer<T1.Element>, UnsafePointer<T2.Element>) throws -> R) rethrows -> R where T1.Element == T2.Element {
return try t1.withUnsafeBufferPointer { p1 in
return try t2.withUnsafeBufferPointer { p2 in
return try body(p1.baseAddress!, p2.baseAddress!)
}
}
}
/// Call `body(p1, p2)` with the pointers for the two types
public func withPointers<T1: TensorType, T2: MutableTensorType, R>(_ t1: T1, _ t2: inout T2, body: (UnsafePointer<T1.Element>, UnsafeMutablePointer<T2.Element>) throws -> R) rethrows -> R where T1.Element == T2.Element {
return try t1.withUnsafeBufferPointer { p1 in
return try t2.withUnsafeMutableBufferPointer { p2 in
return try body(p1.baseAddress!, p2.baseAddress!)
}
}
}
/// Call `body(p1, p2)` with the pointers for the two types
public func withPointers<T1: MutableTensorType, T2: TensorType, R>(_ t1: inout T1, _ t2: T2, body: (UnsafeMutablePointer<T1.Element>, UnsafePointer<T2.Element>) throws -> R) rethrows -> R where T1.Element == T2.Element {
return try t1.withUnsafeMutableBufferPointer { p1 in
return try t2.withUnsafeBufferPointer { p2 in
return try body(p1.baseAddress!, p2.baseAddress!)
}
}
}
/// Call `body(p1, p2)` with the pointers for the two types
public func withPointers<T1: MutableTensorType, T2: MutableTensorType, R>(_ t1: inout T1, _ t2: inout T2, body: (UnsafeMutablePointer<T1.Element>, UnsafeMutablePointer<T2.Element>) throws -> R) rethrows -> R where T1.Element == T2.Element {
return try t1.withUnsafeMutableBufferPointer { p1 in
return try t2.withUnsafeMutableBufferPointer { p2 in
return try body(p1.baseAddress!, p2.baseAddress!)
}
}
}
// MARK: Three parameters
/// Call `body(p1, p2, p3)` with the pointers for the three types
public func withPointers<T1: TensorType, T2: TensorType, T3: MutableTensorType, R>(_ t1: T1, _ t2: T2, _ t3: inout T3, body: (UnsafePointer<T1.Element>, UnsafePointer<T2.Element>, UnsafeMutablePointer<T3.Element>) throws -> R) rethrows -> R where T1.Element == T2.Element, T2.Element == T3.Element {
return try t1.withUnsafeBufferPointer { p1 in
return try t2.withUnsafeBufferPointer { p2 in
return try t3.withUnsafeMutableBufferPointer { p3 in
return try body(p1.baseAddress!, p2.baseAddress!, p3.baseAddress!)
}
}
}
}
| mit | 784ae3d55ad8afb08e8b3cf90a5ee98e | 49.119048 | 299 | 0.707601 | 3.820327 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Models/Event/Eventsable.swift | 1 | 1553 | //
// Eventsable.swift
// MEGameTracker
//
// Created by Emily Ivie on 4/2/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
public protocol Eventsable {
var gameSequenceUuid: UUID? { get }
var events: [Event] { get set }
var rawEventDictionary: [CodableDictionary] { get }
func getEvents(gameSequenceUuid: UUID?, with manager: CodableCoreDataManageable?) -> [Event]
}
extension Eventsable {
public func getEvents(gameSequenceUuid: UUID?, with manager: CodableCoreDataManageable?) -> [Event] {
let events: [Event] = rawEventDictionary.map({
$0.dictionary
}).map({
guard let id = $0["id"] as? String,
let type = EventType(stringValue: $0["type"] as? String),
var e = Event.get(id: id, type: type, gameSequenceUuid: gameSequenceUuid, with: manager)
else { return nil }
// store what object is holding this at present:
if let mission = self as? Mission {
e.inMissionId = mission.id
} else if let map = self as? Map {
e.inMapId = map.id
} else if let person = self as? Person {
e.inPersonId = person.id
} else if let item = self as? Item {
e.inItemId = item.id
}
return e
}).filter({ $0 != nil }).map({ $0! })
return events
}
public func getEvents() -> [Event] {
return getEvents(gameSequenceUuid: self.gameSequenceUuid, with: nil)
}
}
| mit | bad91ed5362e19f83f8d3fc5993565a2 | 32.73913 | 105 | 0.574742 | 4.228883 | false | false | false | false |
mahabaleshwarhnr/GitHub-challenges---iOS | GithubApiDemo/GithubApiDemo/Helpers/UrlBuilder.swift | 1 | 742 | //
// UrlBuilder.swift
// GithubApiDemo
//
// Created by Mahabaleshwar on 23/08/16.
// Copyright © 2016 DP Samant. All rights reserved.
//
import Foundation
public class UrlBuilder {
static var per_page = 20
static var pageNumber = 1
private static func getHostUrl() -> String {
return "https://api.github.com"
}
static func getPageInfo() {
}
static func getRepositoriesUrl(forLanguage: String) -> String {
//https://api.github.com/search/repositories?q=language:swift&sort=stars&order=desc&page=1&per_page=10
return getHostUrl() + "/search/repositories?q=language:" + forLanguage + "&sort=stars&order=desc&page=\(pageNumber)&per_page=\(per_page)"
}
} | mit | f267750b798e6251d871eff25e5c50ee | 25.5 | 145 | 0.647773 | 3.686567 | false | false | false | false |
LuizZak/TaskMan | TaskMan/ChangeSegmentTaskViewController.swift | 1 | 2779 | //
// ChangeSegmentTaskViewController.swift
// TaskMan
//
// Created by Luiz Fernando Silva on 05/12/16.
// Copyright © 2016 Luiz Fernando Silva. All rights reserved.
//
import Cocoa
class ChangeSegmentTaskViewController: NSViewController {
@IBOutlet weak var txtTaskName: NSTextField!
@IBOutlet weak var btnOk: NSButton!
@IBOutlet weak var tableView: NSTableView!
/// The task controller to get the tasks and segment information from
var taskController: TaskController!
/// The segment to replace the task of
var segment: TaskSegment!
/// Callback to fire when the user has chosen a task
var callback: ((ChangeSegmentTaskViewController) -> ())?
/// Gets the currently selected task
fileprivate(set) var selectedTask: Task?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
self.title = "Change segment's task";
}
override func viewWillAppear() {
super.viewWillAppear()
if let window = self.view.window {
if let screenSize = window.screen?.frame.size {
window.setFrameOrigin(NSPoint(x: (screenSize.width - window.frame.size.width) / 2, y: (screenSize.height - window.frame.size.height) / 2))
}
}
// Fetch the name of the task of the current segment
if let task = taskController.getTask(withId: segment.taskId) {
txtTaskName.stringValue = task.name
} else {
txtTaskName.stringValue = "< None >"
}
}
@IBAction func didTapOk(_ sender: NSButton) {
if let callback = callback {
callback(self)
} else {
self.dismiss(self)
}
}
@IBAction func didTapCancel(_ sender: Any) {
self.dismiss(self)
}
}
extension ChangeSegmentTaskViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return taskController.currentTasks.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let cell = tableView.make(withIdentifier: "textCell", owner: self) as? NSTableCellView else {
return nil
}
let task = taskController.currentTasks[row]
cell.textField?.stringValue = task.name
cell.objectValue = task
return cell
}
}
extension ChangeSegmentTaskViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
selectedTask = taskController.currentTasks[row]
btnOk.isEnabled = true
return true
}
}
| mit | d0cf4aef0422aa2bac5868f9d98708bd | 28.242105 | 154 | 0.61951 | 4.831304 | false | false | false | false |
mperovic/my41 | my41/Classes/Button.swift | 1 | 7618 | //
// Button.swift
// my41
//
// Created by Miroslav Perovic on 9/6/14.
// Copyright (c) 2014 iPera. All rights reserved.
//
import Foundation
import Cocoa
class Key: NSButton {
@IBOutlet weak var keygroup: KeyGroup!
var keyCode: NSNumber?
var pressed: Bool = false
override func acceptsFirstMouse(for theEvent: NSEvent?) -> Bool {
return true
}
override func mouseDown(with theEvent: NSEvent) {
if theEvent.modifierFlags.intersection(.control) == [] {
downKey()
}
highlight(true)
let appDelegate = NSApplication.shared.delegate as! AppDelegate
appDelegate.buttonPressed = true
}
override func mouseUp(with theEvent: NSEvent) {
if theEvent.modifierFlags.intersection(.control) == [] {
upKey()
}
highlight(false)
let appDelegate = NSApplication.shared.delegate as! AppDelegate
appDelegate.buttonPressed = false
}
func downKey() {
pressed = true
notifyKeyGroup()
}
func upKey() {
pressed = false
notifyKeyGroup()
}
func notifyKeyGroup() {
if keygroup != nil {
keygroup.key(key: self, pressed: pressed)
}
}
}
class ButtonCell: NSButtonCell {
@objc var lowerText: String?
@objc var upperText: NSMutableAttributedString?
@objc var shiftButton: String?
var switchButton: String?
required init(coder: NSCoder) {
super.init(coder: coder)
}
override func drawBezel(withFrame frame: NSRect, in controlView: NSView) {
let ctx = NSGraphicsContext.current()!
ctx.saveGraphicsState()
let roundedRadius: CGFloat = 3.0
// Outer stroke (drawn as gradient)
let outerClip: NSBezierPath = NSBezierPath(roundedRect: frame,
xRadius: roundedRadius,
yRadius: roundedRadius)
outerClip.setClip()
let outerGradient = NSGradient(colorsAndLocations:
(NSColor(deviceWhite: 0.20, alpha: 1.0), 0.0),
(NSColor(deviceWhite: 0.21, alpha: 1.0), 1.0)
)
outerGradient?.draw(in: outerClip.bounds, angle: 90.0)
ctx.restoreGraphicsState()
// Background gradient
ctx.saveGraphicsState()
let backgroundPath: NSBezierPath = NSBezierPath(roundedRect: NSInsetRect(frame, 2.0, 2.0),
xRadius: roundedRadius,
yRadius: roundedRadius)
backgroundPath.setClip()
var backgroundGradient: NSGradient?
if switchButton == "Y" {
backgroundGradient = NSGradient(colorsAndLocations:
(NSColor(deviceWhite: 0.30, alpha: 1.0), 0.0),
(NSColor(deviceWhite: 0.42, alpha: 1.0), 0.5),
(NSColor(deviceWhite: 0.50, alpha: 1.0), 1.0)
)
} else {
if shiftButton == "Y" {
backgroundGradient = NSGradient(colorsAndLocations:
(NSColor(calibratedRed: 0.4784, green: 0.2745, blue: 0.0471, alpha: 1.0), 0.0),
(NSColor(calibratedRed: 0.5804, green: 0.3961, blue: 0.1294, alpha: 1.0), 0.1),
(NSColor(calibratedRed: 0.6078, green: 0.3961, blue: 0.08235, alpha: 1.0), 0.49),
(NSColor(calibratedRed: 0.6745, green: 0.4235, blue: 0.0549, alpha: 1.0), 0.49),
(NSColor(calibratedRed: 0.7176, green: 0.4549, blue: 0.1765, alpha: 1.0), 0.9),
(NSColor(calibratedRed: 0.749, green: 0.4901, blue: 0.1765, alpha: 1.0), 1.0)
)
} else {
backgroundGradient = NSGradient(colorsAndLocations:
(NSColor(deviceWhite: 0.17, alpha: 1.0), 0.0),
(NSColor(deviceWhite: 0.20, alpha: 1.0), 0.12),
(NSColor(deviceWhite: 0.27, alpha: 1.0), 0.49),
(NSColor(deviceWhite: 0.30, alpha: 1.0), 0.49),
(NSColor(deviceWhite: 0.42, alpha: 1.0), 0.98),
(NSColor(deviceWhite: 0.50, alpha: 1.0), 1.0)
)
}
}
backgroundGradient?.draw(in: backgroundPath.bounds, angle: 270.0)
ctx.restoreGraphicsState()
// Dark stroke
// ctx.saveGraphicsState()
// NSColor(deviceWhite: 0.12, alpha: 1.0).setStroke()
// NSBezierPath(roundedRect: NSInsetRect(frame, 1.5, 1.5),
// xRadius: roundedRadius,
// yRadius: roundedRadius)
// ctx.restoreGraphicsState()
//
// // Inner light stroke
// ctx.saveGraphicsState()
// NSColor(deviceWhite: 1.0, alpha: 0.05).setStroke()
// NSBezierPath(roundedRect: NSInsetRect(frame, 2.5, 2.5),
// xRadius: roundedRadius,
// yRadius: roundedRadius)
// ctx.restoreGraphicsState()
// Draw darker overlay if button is pressed
if isHighlighted {
ctx.saveGraphicsState()
NSBezierPath(roundedRect: NSInsetRect(frame, 2.0, 2.0),
xRadius: roundedRadius,
yRadius: roundedRadius).setClip()
NSColor(calibratedWhite: 0.0, alpha: 0.35).setFill()
NSRectFillUsingOperation(frame, .sourceOver)
ctx.restoreGraphicsState()
}
// Text Drawing
if lowerText != nil {
var lowerTextRect: NSRect
if lowerText == "N" {
lowerTextRect = NSMakeRect(1.0, 17.0, 86.0, 12.0)
} else if lowerText == "R" || lowerText == "S" || lowerText == "T" {
lowerTextRect = NSMakeRect(1.0, 17.0, 40.0, 12.0)
} else if lowerText == "V" || lowerText == "W" || lowerText == "X" {
lowerTextRect = NSMakeRect(1.0, 17.0, 40.0, 12.0)
} else if lowerText == "Z" || lowerText == "=" || lowerText == "?" {
lowerTextRect = NSMakeRect(1.0, 17.0, 40.0, 12.0)
} else if lowerText == "," {
lowerTextRect = NSMakeRect(1.0, 14.0, 40.0, 15.0)
} else if lowerText == "SPACE" {
lowerTextRect = NSMakeRect(1.0, 18.0, 40.0, 12.0)
} else {
lowerTextRect = NSMakeRect(1.0, 17.0, 36.0, 12.0)
}
let textStyle: NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = .center
var font: NSFont
if (lowerText!).characters.count > 1 {
font = NSFont(name: "Helvetica", size: 9.0)!
} else {
font = NSFont(name: "Helvetica", size: 11.0)!
}
let lowerTextFontAttributes: Dictionary = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: NSColor(calibratedRed: 0.341, green: 0.643, blue: 0.78, alpha: 1.0),
NSAttributedString.Key.paragraphStyle: textStyle
]
lowerText?.draw(in: NSOffsetRect(lowerTextRect, 0, -1), withAttributes: lowerTextFontAttributes)
}
if upperText != nil {
let paragrapStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragrapStyle.alignment = .center
upperText!.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragrapStyle, range: NSMakeRange(0, upperText!.length))
var upperTextRect: NSRect
if upperText?.string == "ENTER ↑" || upperText?.string == "N" {
upperTextRect = NSMakeRect(1.0, 3.0, 86.0, 15.0)
} else if upperText?.string == "÷" || upperText?.string == "×" {
upperTextRect = NSMakeRect(1.0, 0.0, 36.0, 15.0)
} else if upperText?.string == "╋" || upperText?.string == "━" {
upperTextRect = NSMakeRect(1.0, 5.0, 36.0, 15.0)
} else if upperText?.string == "7" || upperText?.string == "8" || upperText?.string == "9" {
upperTextRect = NSMakeRect(1.0, 1.0, 40.0, 15.0)
} else if upperText?.string == "4" || upperText?.string == "5" || upperText?.string == "6" {
upperTextRect = NSMakeRect(1.0, 1.0, 40.0, 15.0)
} else if upperText?.string == "1" || upperText?.string == "2" || upperText?.string == "3" {
upperTextRect = NSMakeRect(1.0, 1.0, 40.0, 15.0)
} else if upperText?.string == "0" || upperText?.string == "•" || upperText?.string == "," {
upperTextRect = NSMakeRect(1.0, 2.0, 40.0, 14.0)
} else if upperText?.string == "SPACE" || upperText?.string == "R/S" {
upperTextRect = NSMakeRect(1.0, 3.0, 40.0, 14.0)
} else if upperText?.string == "ON" || upperText?.string == "USER" || upperText?.string == "PRGM" || upperText?.string == "ALPHA" {
upperTextRect = NSMakeRect(3.0, 4.0, 48.0, 14.0)
} else {
upperTextRect = NSMakeRect(1.0, 3.0, 40.0, 15.0)
}
upperText!.draw(in: NSOffsetRect(upperTextRect, 0, -1))
}
}
}
| bsd-3-clause | 3d7179cf3f598ec6cdb901015b57cc2f | 34.059908 | 134 | 0.660489 | 3.139909 | false | false | false | false |
donggaizhi/DHAudioPlayer | AudioPlayer/AudioPlayer/DHAudioPlayer/DHAudioPlayer.swift | 1 | 4858 | //
// AudioPlayer.swift
// AudioPlayer
//
// Created by MY on 2017/6/6.
// Copyright © 2017年 xxoo. All rights reserved.
//
import UIKit
import AVFoundation
@objc protocol DHAudioPlayerDelegate : class {
@objc optional func audioPlayer(audioPlayer : DHAudioPlayer, duration : Double, isSuccess : Bool)
@objc optional func audioPlayer(audioPlayer : DHAudioPlayer, completeUrl : String)
@objc optional func audioPlayer(audioPlayer : DHAudioPlayer, loadTime : Double, duration : Double)
}
enum DHAudioPlayState {
case none
case playing
case pause
case failed
}
class DHAudioPlayer: NSObject {
var state : DHAudioPlayState = .none
weak var delegate : DHAudioPlayerDelegate?
var duration : TimeInterval = 0
var currentTime : TimeInterval {
if player == nil {
return 0
}
return CMTimeGetSeconds(player!.currentTime())
}
fileprivate var player : AVPlayer?
fileprivate var oldItem : AVPlayerItem?
fileprivate var urlStr : String?
static let share = DHAudioPlayer()
private override init() {}
deinit {
oldItem?.removeObserver(self, forKeyPath: "status")
NotificationCenter.default.removeObserver(self)
oldItem = nil
player = nil
}
}
extension DHAudioPlayer {
func play(urlStr : String) {
guard let url = URL(string: urlStr)
else { return }
self.urlStr = urlStr
let item = AVPlayerItem(url: url)
if player == nil {
player = AVPlayer(playerItem: item)
} else {
oldItem?.removeObserver(self, forKeyPath: "status")
NotificationCenter.default.removeObserver(self)
state = .none
player?.replaceCurrentItem(with: item)
}
item.addObserver(self, forKeyPath: "status", options: .new, context: nil)
item.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil)
NotificationCenter.default.addObserver(self, selector: #selector(playToEndTime), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
oldItem = item
}
func pause() {
player?.pause()
state = .pause
}
func resume() {
player?.play()
state = .playing
}
}
extension DHAudioPlayer {
func seekTo(_ progress : Float) {
let time = Int64(duration * Double(progress))
let cmtime = CMTimeMake(time, 1)
player?.seek(to: cmtime)
}
}
/// KVO
extension DHAudioPlayer {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItemStatus
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
switch status {
case .readyToPlay:
guard let tmpDuration = player?.currentItem?.duration.value,
let tmpTimescale = player?.currentItem?.duration.timescale
else {
state = .none
return
}
let seconds = TimeInterval(tmpDuration) / TimeInterval(tmpTimescale)
print(state)
if state == .pause { return }
player?.play()
delegate?.audioPlayer?(audioPlayer: self, duration: seconds, isSuccess: true)
state = .playing
duration = seconds
case .failed:
delegate?.audioPlayer?(audioPlayer: self, duration: 0.0, isSuccess: false)
state = .failed
case .unknown:
delegate?.audioPlayer?(audioPlayer: self, duration: 0.0, isSuccess: false)
state = .failed
}
} else if keyPath == "loadedTimeRanges" {
guard let timeRanges = player?.currentItem?.loadedTimeRanges,
let timeRange = timeRanges.first as? CMTimeRange,
let duration = player?.currentItem?.duration
else {
return
}
let totalLoadTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration)
let durationSec = CMTimeGetSeconds(duration)
delegate?.audioPlayer?(audioPlayer: self, loadTime: totalLoadTime, duration: durationSec)
}
}
}
/// Notification
extension DHAudioPlayer {
/// 播放完成
func playToEndTime() {
guard let urlStr = urlStr else { return }
delegate?.audioPlayer?(audioPlayer: self, completeUrl: urlStr)
print("%@ 播放完成", urlStr)
}
}
| mit | fefe65d756e2d2ec188d36257b3e4ec4 | 32.372414 | 155 | 0.599711 | 5.045881 | false | false | false | false |
nuclearace/SwiftDiscord | Sources/SwiftDiscord/Guild/DiscordGuildMember.swift | 1 | 5649 | // The MIT License (MIT)
// Copyright (c) 2016 Erik Little
// 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
/// Represents a guild member.
public struct DiscordGuildMember {
// MARK: Properties
/// The id of the guild of this member.
public let guildId: GuildID
/// The date this member joined the guild.
public let joinedAt: Date
/// The user object for this member.
public let user: DiscordUser
/// Whether this member has been deafened.
/// Changing this will cause the client to attempt to change the deafen status on Discord.
public var deaf: Bool {
get {
return _deaf
}
set {
guild?.modifyMember(self, options: [.deaf(newValue)])
}
}
/// If this member has a guild object attached, this returns the `DiscordRoles` for the member.
/// If a guild is unavailable, you can call `roles(for:)` on this member's guild directly.
/// - returns: An Array of `DiscordRole` or nil if there is no guild attached to this member.
public var roles: [DiscordRole]? {
// TODO cache this
guard let guild = self.guild else { return nil }
return guild.roles(for: self)
}
/// Whether this member is muted.
/// Changing this will cause the client to attempt to change the deafen status on Discord.
public var mute: Bool {
get {
return _mute
}
set {
guild?.modifyMember(self, options: [.mute(newValue)])
}
}
/// This member's nickname, if they have one.
/// Changing this value will cause the client to attempt to change the nick on Discord.
public var nick: String? {
get {
return _nick
}
set {
guild?.modifyMember(self, options: [.nick(newValue)])
}
}
/// An array of role snowflake ids that this user has.
public var roleIds: [RoleID]
/// The guild this member is on
public internal(set) weak var guild: DiscordGuild?
private var _deaf: Bool
private var _mute: Bool
private var _nick: String?
init(guildMemberObject: [String: Any], guildId: GuildID, guild: DiscordGuild? = nil) {
self.guildId = guildId
user = DiscordUser(userObject: guildMemberObject.get("user", or: [String: Any]()))
_deaf = guildMemberObject.get("deaf", or: false)
_mute = guildMemberObject.get("mute", or: false)
_nick = guildMemberObject["nick"] as? String
roleIds = (guildMemberObject["roles"] as? [String])?.compactMap(Snowflake.init) ?? []
joinedAt = DiscordDateFormatter.format(guildMemberObject.get("joined_at", or: "")) ?? Date()
self.guild = guild
}
init(guildId: GuildID, user: DiscordUser, deaf: Bool, mute: Bool, nick: String?, roles: [RoleID], joinedAt: Date,
guild: DiscordGuild? = nil) {
self.user = user
self._deaf = deaf
self._mute = mute
self._nick = nick
self.roleIds = roles
self.joinedAt = joinedAt
self.guild = guild
self.guildId = guildId
}
static func guildMembersFromArray(_ guildMembersArray: [[String: Any]], withGuildId guildId: GuildID,
guild: DiscordGuild?) -> DiscordLazyDictionary<UserID, DiscordGuildMember> {
var guildMembers = DiscordLazyDictionary<UserID, DiscordGuildMember>()
for guildMember in guildMembersArray {
guard let user = guildMember["user"] as? [String: Any], let id = Snowflake(user["id"] as? String) else {
DefaultDiscordLogger.Logger.error("Couldn't extract userId from user JSON", type: "GuildMembersFromArray")
continue
}
guildMembers[lazy: id] = .lazy({[weak guild] in
DiscordGuildMember(guildMemberObject: guildMember, guildId: guildId, guild: guild)
})
}
return guildMembers
}
///
/// Searches this member for a role with a name that matches.
///
/// - parameter role: The role's name to look for.
/// - return: Whether or not they have this role.
///
public func hasRole(_ role: String) -> Bool {
guard let roles = self.roles else { return false }
return roles.contains(where: { $0.name == role })
}
mutating func updateMember(_ updateObject: [String: Any]) -> DiscordGuildMember {
if let roles = updateObject["roles"] as? [String] {
self.roleIds = roles.compactMap(Snowflake.init)
}
_nick = updateObject["nick"] as? String
return self
}
}
| mit | 89ee60679d168af95fc1934b68ef0243 | 36.410596 | 122 | 0.640998 | 4.476228 | false | false | false | false |
BergerBytes/BBSlideoutMenu | Pod/Classes/BBSlideoutMenu.swift | 1 | 16748 | //
// BBSlideoutMenu.swift
// BergerBytes.io
//
// Created by Michael Berger on 3/7/16.
// Copyright © 2016 bergerbytes. All rights reserved.
//
import UIKit
public enum Direction {
case left
case right
}
public protocol BBSlideoutMenuDelegate: class {
func didPresent(slideoutMenu menu: BBSlideoutMenu)
func willPresent(slideoutMenu menu: BBSlideoutMenu)
func didDismiss(slideoutMenu menu: BBSlideoutMenu)
func willDismiss(slideoutMenu menu: BBSlideoutMenu)
func didStartEdgePanFor(slideoutMenu menu: BBSlideoutMenu)
}
open class BBSlideoutMenu: UIView {
//MARK: - Inspectables
@IBInspectable var direction: String = "left" {
didSet {
switch direction {
case "left":
slideDirection = .left
case "right":
slideDirection = .right
default:
direction = "left"
slideDirection = .left
}
}
}
@IBInspectable open var slideTravelPercent: CGFloat = 0.8 {
didSet {
if slideTravelPercent > 1 {
slideTravelPercent = 1
} else if slideTravelPercent < 0.1 {
slideTravelPercent = 0.1
}
}
}
@IBInspectable open var shrinkAmount: CGFloat = 60 {
didSet {
if shrinkAmount < 0 {
shrinkAmount = 0
} else if shrinkAmount > UIScreen.main.bounds.height/2 {
print("BBSlideoutMenu: ShrinkAmount too high!!")
shrinkAmount = 60
}
}
}
@IBInspectable open var menuOffset: CGFloat = 150
@IBInspectable open var slideTime: Double = 0.5
@IBInspectable open var zoomFactor: CGFloat = 0.8
@IBInspectable open var springEnabled: Bool = true
/**
The damping ratio for the spring animation as it approaches its quiescent state.
To smoothly decelerate the animation without oscillation, use a value of 1. Employ a damping ratio closer to zero to increase oscillation.
*/
@IBInspectable open var springDamping: CGFloat = 0.5 {
didSet {
if springDamping < 0 {
springDamping = 0
} else if springDamping > 1 {
springDamping = 1
}
}
}
//MARK: - Properties
///The direction the view will travel to make room for the menu. Uses .Left or .Right
open var slideDirection: Direction = .left {
didSet {
edgePanGesture?.edges = slideDirection == .left ? .right : .left
}
}
open var backgroundImage: UIImage? {
didSet {
if backgroundImage == nil {
self.backgroundColor = savedBackgroundColor;
}
}
}
open var delegate: BBSlideoutMenuDelegate?
fileprivate
var menuAnchor: NSLayoutConstraint!
var viewImage: UIView?
var viewTopConstraint: NSLayoutConstraint!
var viewBottomConstraint: NSLayoutConstraint!
var viewSlideSideConstraint: NSLayoutConstraint!
var viewRatioConstraint: NSLayoutConstraint!
var edgePinConstraint: NSLayoutConstraint!
var coverView: UIImageView!
var keyWindow: UIWindow!
var slideAmount: CGFloat!
var edgePanGesture: UIScreenEdgePanGestureRecognizer?
var savedBackgroundColor: UIColor!
//MARK: - Functions
/**
Sets up a EdgePan gesture to open the Slide Menu. Must be called again if the slideDirection has been changed
*/
open func setupEdgePan() {
if savedBackgroundColor == nil {
savedBackgroundColor = self.backgroundColor;
}
if keyWindow == nil {
keyWindow = UIApplication.shared.keyWindow!
}
if let edgePan = edgePanGesture,
let index = self.keyWindow.gestureRecognizers?.index(of: edgePan) {
self.keyWindow.gestureRecognizers?.remove(at: index)
}
edgePanGesture = UIScreenEdgePanGestureRecognizer(target: self,
action: #selector(BBSlideoutMenu.edgeHandle(_:)))
edgePanGesture?.edges = slideDirection == .left ? .right : .left
keyWindow.gestureRecognizers?.append(edgePanGesture!)
}
/**
Shows the slide out menu
- parameter animate: A Bool that specifies whether to animate the transition
- parameter didPresentMenu: Calls when the animation is completed, Pass nil to ignore callback
*/
open func presentSlideMenu(animated: Bool, didPresentMenu: (() -> Void)?) {
if savedBackgroundColor == nil {
savedBackgroundColor = self.backgroundColor;
}
if keyWindow == nil {
keyWindow = UIApplication.shared.keyWindow!
}
let size = keyWindow.frame.size
edgePinConstraint = slideDirection == .left
? self.trailingAnchor.constraint(equalTo: keyWindow.trailingAnchor, constant: 0)
: self.leadingAnchor.constraint(equalTo: keyWindow.leadingAnchor, constant: 0)
//MARK: Image VIew
// Create, Configure and add a screenshot of the current view
self.viewImage?.removeFromSuperview()
guard let viewImage = keyWindow.snapshotView(afterScreenUpdates: false) else {
return
}
self.viewImage = viewImage
viewImage.frame = keyWindow.frame
viewImage.translatesAutoresizingMaskIntoConstraints = false
viewImage.clipsToBounds = true
viewTopConstraint = viewImage.topAnchor.constraint(equalTo: keyWindow.topAnchor, constant: 0)
viewBottomConstraint = viewImage.bottomAnchor.constraint(equalTo: keyWindow.bottomAnchor, constant: 0)
viewSlideSideConstraint = slideDirection == .left
? viewImage.trailingAnchor.constraint(equalTo: keyWindow.trailingAnchor, constant: 0)
: viewImage.leadingAnchor.constraint(equalTo: keyWindow.leadingAnchor, constant: 0)
viewRatioConstraint = NSLayoutConstraint(
item: viewImage,
attribute: .height,
relatedBy: .equal,
toItem: viewImage,
attribute: .width,
multiplier: (size.height / size.width),
constant: 0)
viewImage.addConstraint(viewRatioConstraint)
keyWindow.addSubview(viewImage)
viewRatioConstraint.isActive = true
viewTopConstraint.isActive = true
viewBottomConstraint.isActive = true
viewSlideSideConstraint.isActive = true
//MARK: Background View
coverView = UIImageView(frame: keyWindow.frame)
if let validBackgroundImage = backgroundImage {
coverView.image = validBackgroundImage
coverView.contentMode = .scaleAspectFill
backgroundColor = UIColor.clear
} else {
coverView.backgroundColor = self.backgroundColor
}
coverView.isHidden = false
keyWindow.insertSubview(coverView, belowSubview: viewImage)
//MARK: Slideout View
keyWindow.insertSubview(self, belowSubview: viewImage)
self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(equalToConstant: size.height).isActive = true
self.widthAnchor.constraint(equalToConstant: (size.width * slideTravelPercent)).isActive = true
self.centerYAnchor.constraint(equalTo: keyWindow.centerYAnchor).isActive = true
if slideDirection == .left {
menuAnchor = self.leadingAnchor.constraint(equalTo: viewImage.trailingAnchor)
} else {
menuAnchor = self.trailingAnchor.constraint(equalTo: viewImage.leadingAnchor)
}
menuAnchor.isActive = true
setupStartingValues()
slideAmount = slideDirection == .left ? -(keyWindow.bounds.width * slideTravelPercent) : keyWindow.bounds.width * slideTravelPercent
setupDestinationValues()
if animated {
animateSlideOpen { () -> Void in
didPresentMenu?()
}
} else {
delegate?.willPresent(slideoutMenu: self)
self.viewImage?.layer.cornerRadius = 5
self.transform = CGAffineTransform(scaleX: 1, y: 1)
didPresentMenu?()
delegate?.didPresent(slideoutMenu: self)
}
edgePinConstraint.isActive = true
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(BBSlideoutMenu.panHandle(_:)))
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(BBSlideoutMenu.tapHandle(_:)))
self.viewImage?.gestureRecognizers = [panGesture, tapGesture]
}
/**
Dismisses the slide menu
- parameter animated: A Bool that specifies whether to animate the transition
- parameter time: Time in seconds the animation will take. Pass nil to use default value setup in storyboard
*/
open func dismissSlideMenu(_ animated: Bool, time: Double?) {
if keyWindow == nil {
keyWindow = UIApplication.shared.keyWindow!
}
delegate?.willDismiss(slideoutMenu: self)
viewTopConstraint.constant = 0
viewBottomConstraint.constant = -viewTopConstraint.constant
viewSlideSideConstraint.constant = 0
menuAnchor.constant = menuOffset * (slideDirection == .right ? 1 : -1)
edgePinConstraint.isActive = false
UIView.animate(
withDuration: animated ? (time != nil ? time! : slideTime) : 0,
delay: 0.0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0.0,
options: UIView.AnimationOptions(),
animations: { () -> Void in
self.keyWindow.layoutIfNeeded()
self.viewImage!.layer.cornerRadius = 0
self.self.transform = CGAffineTransform(scaleX: self.zoomFactor, y: self.zoomFactor)
}) { (complete) -> Void in
self.coverView.removeFromSuperview()
self.removeFromSuperview()
UIView.animate(withDuration: 0.1,
animations: { () -> Void in
self.viewImage!.alpha = 0
}, completion: { (completed) -> Void in
self.viewImage!.removeFromSuperview()
if let epGesture = self.edgePanGesture {
if self.keyWindow.gestureRecognizers!.index(of: epGesture) == nil {
self.keyWindow.gestureRecognizers?.append(epGesture)
}
}
self.delegate?.didDismiss(slideoutMenu: self)
})
}
}
//MARK: Internal Functions
fileprivate func setupDestinationValues() {
viewTopConstraint.constant = shrinkAmount
viewBottomConstraint.constant = -viewTopConstraint.constant
viewSlideSideConstraint.constant = slideAmount
menuAnchor.constant = 0
}
fileprivate func setupStartingValues() {
menuAnchor.constant = menuOffset * (slideDirection == .right ? 1 : -1)
transform = CGAffineTransform(scaleX: zoomFactor, y: zoomFactor)
keyWindow.layoutIfNeeded()
}
fileprivate func animateSlideOpen(_ animationEnd: ( () -> Void )? = nil) {
if keyWindow == nil {
keyWindow = UIApplication.shared.keyWindow!
}
delegate?.willPresent(slideoutMenu: self)
if let epGesture = edgePanGesture,
let index = self.keyWindow.gestureRecognizers?.index(of: epGesture) {
self.keyWindow.gestureRecognizers?.remove(at: index)
}
setupDestinationValues()
UIView.animate(withDuration: slideTime,
delay: 0.0,
usingSpringWithDamping: springEnabled ? springDamping : 1,
initialSpringVelocity: 0.0,
options: .curveLinear,
animations: { () -> Void in
self.keyWindow.layoutIfNeeded()
self.viewImage!.layer.cornerRadius = 5
self.transform = CGAffineTransform(scaleX: 1, y: 1)
}) { (complete) -> Void in
self.delegate?.didPresent(slideoutMenu: self)
animationEnd?()
}
}
@objc func tapHandle(_ tap: UITapGestureRecognizer) {
dismissSlideMenu(true, time: nil)
}
@objc func panHandle(_ pan: UIPanGestureRecognizer) {
if keyWindow == nil {
keyWindow = UIApplication.shared.keyWindow!
}
let transition = pan.translation(in: self)
var percentage = transition.x / self.bounds.width * (slideDirection == .right ? -1 : 1)
switch pan.state {
case .changed:
edgePinConstraint.isActive = false
if percentage >= 1 { percentage = 1 }
viewSlideSideConstraint.constant = slideAmount - (slideAmount * percentage)
viewTopConstraint.constant = shrinkAmount - (shrinkAmount * percentage)
viewBottomConstraint.constant = -viewTopConstraint.constant
let scale = 1 - ((1 - zoomFactor) * percentage)
transform = CGAffineTransform(scaleX: scale, y: scale)
let offset = menuOffset * (slideDirection == .right ? 1 : -1)
menuAnchor.constant = (offset * percentage)
if percentage > 0 {
viewImage!.layer.cornerRadius = 5 - (5 * percentage)
}
keyWindow.layoutIfNeeded()
case .ended:
let v = pan.velocity(in: keyWindow).x
let shouldDismiss = (slideDirection == .left ? v : -v) > 500 || abs(percentage) > 0.8
edgePinConstraint.isActive = shouldDismiss
if shouldDismiss {
dismissSlideMenu(true, time: slideTime - abs((slideTime * Double(percentage))))
} else {
animateSlideOpen(nil)
}
default:
break
}
}
@objc func edgeHandle(_ edge: UIScreenEdgePanGestureRecognizer) {
if keyWindow == nil {
keyWindow = UIApplication.shared.keyWindow!
}
var transition = edge.translation(in: self)
var percentage = (transition.x / self.bounds.width)
switch edge.state {
case .began:
delegate?.didStartEdgePanFor(slideoutMenu: self)
transition = edge.translation(in: self)
presentSlideMenu(animated: false, didPresentMenu: nil)
edgePinConstraint.isActive = false
case .changed:
edgePinConstraint.isActive = false
percentage = transition.x / self.bounds.width * (slideDirection == .left ? -1 : 1)
if percentage < 0 { percentage = 0 }
viewSlideSideConstraint.constant = (slideAmount * percentage)
viewTopConstraint.constant = (shrinkAmount * percentage)
viewBottomConstraint.constant = -viewTopConstraint.constant
let offset = menuOffset * (slideDirection == .right ? 1 : -1)
menuAnchor.constant = offset - (offset * percentage)
viewImage!.layer.cornerRadius = (5 * percentage)
let scale = zoomFactor + ((1 - zoomFactor) * percentage)
transform = CGAffineTransform(scaleX: scale, y: scale)
case .ended:
let v = edge.velocity(in: keyWindow).x
let shouldPersist = (slideDirection == .right ? v : -v) > 500 || abs(percentage) > 0.5
edgePinConstraint.isActive = !shouldPersist
if shouldPersist {
animateSlideOpen()
} else {
dismissSlideMenu(true, time: 0.1)
}
default:
break
}
}
//MARK: -
}
public extension BBSlideoutMenuDelegate {
func didPresent(slideoutMenu menu: BBSlideoutMenu) {}
func willPresent(slideoutMenu menu: BBSlideoutMenu) {}
func didDismiss(slideoutMenu menu: BBSlideoutMenu) {}
func willDismiss(slideoutMenu menu: BBSlideoutMenu) {}
func didStartEdgePanFor(slideoutMenu menu: BBSlideoutMenu) {}
}
| mit | caa854c4949b011dd9db98f58977ec5c | 36.381696 | 143 | 0.590673 | 5.301361 | false | false | false | false |
JGiola/swift-package-manager | Sources/PackageGraph/DependencyResolver.swift | 1 | 59776 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import struct Utility.Version
import class Foundation.NSDate
public enum DependencyResolverError: Error, Equatable, CustomStringConvertible {
/// The resolver was unable to find a solution to the input constraints.
case unsatisfiable
/// The resolver found a dependency cycle.
case cycle(AnyPackageContainerIdentifier)
/// The resolver encountered a versioned container which has a revision dependency.
case incompatibleConstraints(
dependency: (AnyPackageContainerIdentifier, String),
revisions: [(AnyPackageContainerIdentifier, String)])
public static func == (lhs: DependencyResolverError, rhs: DependencyResolverError) -> Bool {
switch (lhs, rhs) {
case (.unsatisfiable, .unsatisfiable):
return true
case (.unsatisfiable, _):
return false
case (.cycle(let lhs), .cycle(let rhs)):
return lhs == rhs
case (.cycle, _):
return false
case (.incompatibleConstraints(let lDependency, let lRevisions),
.incompatibleConstraints(let rDependency, let rRevisions)):
return lDependency == rDependency && lRevisions == rRevisions
case (.incompatibleConstraints, _):
return false
}
}
public var description: String {
switch self {
case .unsatisfiable:
return "unable to resolve dependencies"
case .cycle(let package):
return "the package \(package.identifier) depends on itself"
case let .incompatibleConstraints(dependency, revisions):
let stream = BufferedOutputByteStream()
stream <<< "the package \(dependency.0.identifier) @ \(dependency.1) contains incompatible dependencies:\n"
for (i, revision) in revisions.enumerated() {
stream <<< " "
stream <<< "\(revision.0.identifier)" <<< " @ " <<< revision.1
if i != revisions.count - 1 {
stream <<< "\n"
}
}
return stream.bytes.asString!
}
}
}
/// An abstract definition for a set of versions.
public enum VersionSetSpecifier: Hashable, CustomStringConvertible {
/// The universal set.
case any
/// The empty set.
case empty
/// A non-empty range of version.
case range(Range<Version>)
/// The exact version that is required.
case exact(Version)
/// Compute the intersection of two set specifiers.
public func intersection(_ rhs: VersionSetSpecifier) -> VersionSetSpecifier {
switch (self, rhs) {
case (.any, _):
return rhs
case (_, .any):
return self
case (.empty, _):
return .empty
case (_, .empty):
return .empty
case (.range(let lhs), .range(let rhs)):
let start = Swift.max(lhs.lowerBound, rhs.lowerBound)
let end = Swift.min(lhs.upperBound, rhs.upperBound)
if start < end {
return .range(start..<end)
} else {
return .empty
}
case (.exact(let v), _):
if rhs.contains(v) {
return self
}
return .empty
case (_, .exact(let v)):
if contains(v) {
return rhs
}
return .empty
}
}
/// Check if the set contains a version.
public func contains(_ version: Version) -> Bool {
switch self {
case .empty:
return false
case .range(let range):
return range.contains(version: version)
case .any:
return true
case .exact(let v):
return v == version
}
}
public var description: String {
switch self {
case .any:
return "any"
case .empty:
return "empty"
case .range(let range):
var upperBound = range.upperBound
// Patch the version range representation. This shouldn't be
// required once we have custom version range structure.
if upperBound.minor == .max && upperBound.patch == .max {
upperBound = Version(upperBound.major + 1, 0, 0)
}
if upperBound.minor != .max && upperBound.patch == .max {
upperBound = Version(upperBound.major, upperBound.minor + 1, 0)
}
return range.lowerBound.description + "..<" + upperBound.description
case .exact(let version):
return version.description
}
}
public static func == (_ lhs: VersionSetSpecifier, _ rhs: VersionSetSpecifier) -> Bool {
switch (lhs, rhs) {
case (.any, .any):
return true
case (.any, _):
return false
case (.empty, .empty):
return true
case (.empty, _):
return false
case (.range(let lhs), .range(let rhs)):
return lhs == rhs
case (.range, _):
return false
case (.exact(let lhs), .exact(let rhs)):
return lhs == rhs
case (.exact, _):
return false
}
}
}
/// An identifier which unambiguously references a package container.
///
/// This identifier is used to abstractly refer to another container when
/// encoding dependencies across packages.
public protocol PackageContainerIdentifier: Hashable { }
/// A type-erased package container identifier.
public struct AnyPackageContainerIdentifier: PackageContainerIdentifier {
/// The underlying identifier, represented as AnyHashable.
public let identifier: AnyHashable
/// Creates a type-erased identifier that wraps up the given instance.
init<T: PackageContainerIdentifier>(_ identifier: T) {
self.identifier = AnyHashable(identifier)
}
}
/// A container of packages.
///
/// This is the top-level unit of package resolution, i.e. the unit at which
/// versions are associated.
///
/// It represents a package container (e.g., a source repository) which can be
/// identified unambiguously and which contains a set of available package
/// versions and the ability to retrieve the dependency constraints for each of
/// those versions.
///
/// We use the "container" terminology here to differentiate between two
/// conceptual notions of what the package is: (1) informally, the repository
/// containing the package, but from which a package cannot be loaded by itself
/// and (2) the repository at a particular version, at which point the package
/// can be loaded and dependencies enumerated.
///
/// This is also designed in such a way to extend naturally to multiple packages
/// being contained within a single repository, should we choose to support that
/// later.
public protocol PackageContainer {
/// The type of packages contained.
associatedtype Identifier: PackageContainerIdentifier
/// The identifier for the package.
var identifier: Identifier { get }
/// Get the list of versions which are available for the package.
///
/// The list will be returned in sorted order, with the latest version *first*.
/// All versions will not be requested at once. Resolver will request the next one only
/// if the previous one did not satisfy all constraints.
func versions(filter isIncluded: (Version) -> Bool) -> AnySequence<Version>
// FIXME: We should perhaps define some particularly useful error codes
// here, so the resolver can handle errors more meaningfully.
//
/// Fetch the declared dependencies for a particular version.
///
/// This property is expected to be efficient to access, and cached by the
/// client if necessary.
///
/// - Precondition: `versions.contains(version)`
/// - Throws: If the version could not be resolved; this will abort
/// dependency resolution completely.
func getDependencies(at version: Version) throws -> [PackageContainerConstraint<Identifier>]
/// Fetch the declared dependencies for a particular revision.
///
/// This property is expected to be efficient to access, and cached by the
/// client if necessary.
///
/// - Throws: If the revision could not be resolved; this will abort
/// dependency resolution completely.
func getDependencies(at revision: String) throws -> [PackageContainerConstraint<Identifier>]
/// Fetch the dependencies of an unversioned package container.
///
/// NOTE: This method should not be called on a versioned container.
func getUnversionedDependencies() throws -> [PackageContainerConstraint<Identifier>]
/// Get the updated identifier at a bound version.
///
/// This can be used by the containers to fill in the missing information that is obtained
/// after the container is available. The updated identifier is returned in result of the
/// dependency resolution.
func getUpdatedIdentifier(at boundVersion: BoundVersion) throws -> Identifier
}
/// An interface for resolving package containers.
public protocol PackageContainerProvider {
associatedtype Container: PackageContainer
/// Get the container for a particular identifier asynchronously.
func getContainer(
for identifier: Container.Identifier,
skipUpdate: Bool,
completion: @escaping (Result<Container, AnyError>) -> Void
)
}
/// An individual constraint onto a container.
public struct PackageContainerConstraint<T: PackageContainerIdentifier>: CustomStringConvertible, Equatable {
public typealias Identifier = T
/// The requirement of this constraint.
public enum Requirement: Hashable {
/// The requirement is specified by the version set.
case versionSet(VersionSetSpecifier)
/// The requirement is specified by the revision.
///
/// The revision string (identifier) should be valid and present in the
/// container. Only one revision requirement per container is possible
/// i.e. two revision requirements for same container will lead to
/// unsatisfiable resolution. The revision requirement can either come
/// from initial set of constraints or from dependencies of a revision
/// requirement.
case revision(String)
/// Un-versioned requirement i.e. a version should not resolved.
case unversioned
}
/// The identifier for the container the constraint is on.
public let identifier: Identifier
/// The constraint requirement.
public let requirement: Requirement
/// Create a constraint requiring the given `container` satisfying the
/// `requirement`.
public init(container identifier: Identifier, requirement: Requirement) {
self.identifier = identifier
self.requirement = requirement
}
/// Create a constraint requiring the given `container` satisfying the
/// `versionRequirement`.
public init(container identifier: Identifier, versionRequirement: VersionSetSpecifier) {
self.init(container: identifier, requirement: .versionSet(versionRequirement))
}
public var description: String {
return "Constraint(\(identifier), \(requirement))"
}
public static func == (lhs: PackageContainerConstraint, rhs: PackageContainerConstraint) -> Bool {
return lhs.identifier == rhs.identifier && lhs.requirement == rhs.requirement
}
}
/// Delegate interface for dependency resoler status.
public protocol DependencyResolverDelegate {
associatedtype Identifier: PackageContainerIdentifier
}
// FIXME: This should be nested, but cannot be currently.
//
/// A bound version for a package within an assignment.
public enum BoundVersion: Equatable, CustomStringConvertible {
/// The assignment should not include the package.
///
/// This is different from the absence of an assignment for a particular
/// package, which only indicates the assignment is agnostic to its
/// version. This value signifies the package *may not* be present.
case excluded
/// The version of the package to include.
case version(Version)
/// The package assignment is unversioned.
case unversioned
/// The package assignment is this revision.
case revision(String)
public var description: String {
switch self {
case .excluded:
return "excluded"
case .version(let version):
return version.description
case .unversioned:
return "unversioned"
case .revision(let identifier):
return identifier
}
}
}
// FIXME: Maybe each package should just return this, instead of a list of
// `PackageContainerConstraint`s. That won't work if we decide this should
// eventually map based on the `Container` rather than the `Identifier`, though,
// so they are separate for now.
//
/// A container for constraints for a set of packages.
///
/// This data structure is only designed to represent satisfiable constraint
/// sets, it cannot represent sets including containers which have an empty
/// constraint.
public struct PackageContainerConstraintSet<C: PackageContainer>: Collection, Hashable {
public typealias Container = C
public typealias Identifier = Container.Identifier
public typealias Requirement = PackageContainerConstraint<Identifier>.Requirement
public typealias Index = Dictionary<Identifier, Requirement>.Index
public typealias Element = Dictionary<Identifier, Requirement>.Element
/// The set of constraints.
private var constraints: [Identifier: Requirement]
/// Create an empty constraint set.
public init() {
self.constraints = [:]
}
/// Create an constraint set from known values.
///
/// The initial constraints should never be unsatisfiable.
init(_ constraints: [Identifier: Requirement]) {
assert(constraints.values.filter({ $0 == .versionSet(.empty) }).isEmpty)
self.constraints = constraints
}
/// The list of containers with entries in the set.
var containerIdentifiers: AnySequence<Identifier> {
return AnySequence<C.Identifier>(constraints.keys)
}
/// Get the version set specifier associated with the given package `identifier`.
public subscript(identifier: Identifier) -> Requirement {
return constraints[identifier] ?? .versionSet(.any)
}
/// Create a constraint set by merging the `requirement` for container `identifier`.
///
/// - Returns: The new set, or nil the resulting set is unsatisfiable.
private func merging(
requirement: Requirement, for identifier: Identifier
) -> PackageContainerConstraintSet<C>? {
switch (requirement, self[identifier]) {
case (.versionSet(let newSet), .versionSet(let currentSet)):
// Try to intersect two version set requirements.
let intersection = currentSet.intersection(newSet)
if intersection == .empty {
return nil
}
var result = self
result.constraints[identifier] = .versionSet(intersection)
return result
case (.unversioned, .unversioned):
return self
case (.unversioned, _):
// Unversioned requirements always *wins*.
var result = self
result.constraints[identifier] = requirement
return result
case (_, .unversioned):
// Unversioned requirements always *wins*.
return self
// The revision cases are deliberately placed below the unversioned
// cases because unversioned has more priority.
case (.revision(let lhs), .revision(let rhs)):
// We can merge two revisions if they have the same identifier.
if lhs == rhs { return self }
return nil
// We can merge the revision requiement if it currently does not have a requirement.
case (.revision, .versionSet(.any)):
var result = self
result.constraints[identifier] = requirement
return result
// Otherwise, we can't merge the revision requirement.
case (.revision, _):
return nil
// Exisiting revision requirements always *wins*.
case (_, .revision):
return self
}
}
/// Create a constraint set by merging `constraint`.
///
/// - Returns: The new set, or nil the resulting set is unsatisfiable.
public func merging(_ constraint: PackageContainerConstraint<Identifier>) -> PackageContainerConstraintSet<C>? {
return merging(requirement: constraint.requirement, for: constraint.identifier)
}
/// Create a new constraint set by merging the given constraint set.
///
/// - Returns: False if the merger has made the set unsatisfiable; i.e. true
/// when the resulting set is satisfiable, if it was already so.
func merging(
_ constraints: PackageContainerConstraintSet<Container>
) -> PackageContainerConstraintSet<C>? {
var result = self
for (key, requirement) in constraints {
guard let merged = result.merging(requirement: requirement, for: key) else {
return nil
}
result = merged
}
return result
}
// MARK: Collection Conformance
public var startIndex: Index {
return constraints.startIndex
}
public var endIndex: Index {
return constraints.endIndex
}
public func index(after index: Index) -> Index {
return constraints.index(after: index)
}
public subscript(position: Index) -> Element {
return constraints[position]
}
}
// FIXME: Actually make efficient.
//
/// A container for version assignments for a set of packages, exposed as a
/// sequence of `Container` to `BoundVersion` bindings.
///
/// This is intended to be an efficient data structure for accumulating a set of
/// version assignments along with efficient access to the derived information
/// about the assignment (for example, the unified set of constraints it
/// induces).
///
/// The set itself is designed to only ever contain a consistent set of
/// assignments, i.e. each assignment should satisfy the induced
/// `constraints`, but this invariant is not explicitly enforced.
struct VersionAssignmentSet<C: PackageContainer>: Equatable, Sequence {
typealias Container = C
typealias Identifier = Container.Identifier
// FIXME: Does it really make sense to key on the identifier here. Should we
// require referential equality of containers and use that to simplify?
//
/// The assignment records.
fileprivate var assignments: OrderedDictionary<Identifier, (container: Container, binding: BoundVersion)>
/// Create an empty assignment.
init() {
assignments = [:]
}
/// The assignment for the given container `identifier.
subscript(identifier: Identifier) -> BoundVersion? {
get {
return assignments[identifier]?.binding
}
}
/// The assignment for the given `container`.
subscript(container: Container) -> BoundVersion? {
get {
return self[container.identifier]
}
set {
// We disallow deletion.
let newBinding = newValue!
// Validate this is a valid assignment.
assert(isValid(binding: newBinding, for: container))
assignments[container.identifier] = (container: container, binding: newBinding)
}
}
/// Create a new assignment set by merging in the bindings from `assignment`.
///
/// - Returns: The new assignment, or nil if the merge cannot be made (the
/// assignments contain incompatible versions).
func merging(_ assignment: VersionAssignmentSet<Container>) -> VersionAssignmentSet<Container>? {
// In order to protect the assignment set, we first have to test whether
// the merged constraint sets are satisfiable.
//
// FIXME: This is very inefficient; we should decide whether it is right
// to handle it here or force the main resolver loop to handle the
// discovery of this property.
guard constraints.merging(assignment.constraints) != nil else {
return nil
}
// The induced constraints are satisfiable, so we *can* union the
// assignments without breaking our internal invariant on
// satisfiability.
var result = self
for (container, binding) in assignment {
if let existing = result[container] {
if existing != binding {
return nil
}
} else {
result[container] = binding
}
}
return result
}
// FIXME: We need to cache this.
//
/// The combined version constraints induced by the assignment.
///
/// This consists of the merged constraints which need to be satisfied on
/// each package as a result of the versions selected in the assignment.
///
/// The resulting constraint set is guaranteed to be non-empty for each
/// mapping, assuming the invariants on the set are followed.
var constraints: PackageContainerConstraintSet<Container> {
// Collect all of the constraints.
var result = PackageContainerConstraintSet<Container>()
/// Merge the provided constraints into result.
func merge(constraints: [PackageContainerConstraint<Identifier>]) {
for constraint in constraints {
guard let merged = result.merging(constraint) else {
preconditionFailure("unsatisfiable constraint set")
}
result = merged
}
}
for (_, (container: container, binding: binding)) in assignments {
switch binding {
case .unversioned, .excluded:
// If the package is unversioned or excluded, it doesn't contribute.
continue
case .revision(let identifier):
// FIXME: Need caching and error handling here. See the FIXME below.
merge(constraints: try! container.getDependencies(at: identifier))
case .version(let version):
// If we have a version, add the constraints from that package version.
//
// FIXME: We should cache this too, possibly at a layer
// different than above (like the entry record).
//
// FIXME: Error handling, except that we probably shouldn't have
// needed to refetch the dependencies at this point.
merge(constraints: try! container.getDependencies(at: version))
}
}
return result
}
// FIXME: This is currently very inefficient.
//
/// Check if the given `binding` for `container` is valid within the assignment.
func isValid(binding: BoundVersion, for container: Container) -> Bool {
switch binding {
case .excluded:
// A package can be excluded if there are no constraints on the
// package (it has not been requested by any other package in the
// assignment).
return constraints[container.identifier] == .versionSet(.any)
case .version(let version):
// A version is valid if it is contained in the constraints.
if case .versionSet(let versionSet) = constraints[container.identifier] {
return versionSet.contains(version)
}
return false
case .revision(let identifier):
// If we already have a revision constraint, it should be same as
// the one we're trying to set.
if case .revision(let existingRevision) = constraints[container.identifier] {
return existingRevision == identifier
}
// Otherwise, it is always valid to set a revision binding. Note
// that there are rules that prevents versioned constraints from
// having revision constraints, but that is handled by the resolver.
return true
case .unversioned:
// An unversioned binding is always valid.
return true
}
}
/// Check if the assignment is valid and complete.
func checkIfValidAndComplete() -> Bool {
// Validity should hold trivially, because it is an invariant of the collection.
for (_, assignment) in assignments {
if !isValid(binding: assignment.binding, for: assignment.container) {
return false
}
}
// Check completeness, by simply looking at all the entries in the induced constraints.
for identifier in constraints.containerIdentifiers {
// Verify we have a non-excluded entry for this key.
switch assignments[identifier]?.binding {
case .unversioned?, .version?, .revision?:
continue
case .excluded?, nil:
return false
}
}
return true
}
// MARK: Sequence Conformance
// FIXME: This should really be a collection, but that takes significantly
// more work given our current backing collection.
typealias Iterator = AnyIterator<(Container, BoundVersion)>
func makeIterator() -> Iterator {
var it = assignments.makeIterator()
return AnyIterator {
if let (_, next) = it.next() {
return (next.container, next.binding)
} else {
return nil
}
}
}
}
func == <C>(lhs: VersionAssignmentSet<C>, rhs: VersionAssignmentSet<C>) -> Bool {
if lhs.assignments.count != rhs.assignments.count { return false }
for (container, lhsBinding) in lhs {
switch rhs[container] {
case let rhsBinding? where lhsBinding == rhsBinding:
continue
default:
return false
}
}
return true
}
/// A general purpose package dependency resolver.
///
/// This is a general purpose solver for the problem of:
///
/// Given an input list of constraints, where each constraint identifies a
/// container and version requirements, and, where each container supplies a
/// list of additional constraints ("dependencies") for an individual version,
/// then, choose an assignment of containers to versions such that:
///
/// 1. The assignment is complete: there exists an assignment for each container
/// listed in the union of the input constraint list and the dependency list for
/// every container in the assignment at the assigned version.
///
/// 2. The assignment is correct: the assigned version satisfies each constraint
/// referencing its matching container.
///
/// 3. The assignment is maximal: there is no other assignment satisfying #1 and
/// #2 such that all assigned version are greater than or equal to the versions
/// assigned in the result.
///
/// NOTE: It does not follow from #3 that this solver attempts to give an
/// "optimal" result. There may be many possible solutions satisfying #1, #2,
/// and #3, and optimality requires additional information (e.g. a
/// prioritization among packages).
///
/// As described, this problem is NP-complete (*). This solver currently
/// implements a basic depth-first greedy backtracking algorithm, and honoring
/// the order of dependencies as specified in the manifest file. The solver uses
/// persistent data structures to manage the accumulation of state along the
/// traversal, so the backtracking is not explicit, rather it is an implicit
/// side effect of the underlying copy-on-write data structures.
///
/// The resolver will always merge the complete set of immediate constraints for
/// a package (i.e., the version ranges of its immediate dependencies) into the
/// constraint set *before* traversing into any dependency. This property allows
/// packages to manually work around performance issues in the resolution
/// algorithm by _lifting_ problematic dependency constraints up to be immediate
/// dependencies.
///
/// There is currently no external control offered by the solver over _which_
/// solution satisfying the properties above is selected, if more than one are
/// possible. In practice, the algorithm is designed such that it will
/// effectively prefer (i.e., optimize for the newest version of) dependencies
/// which are earliest in the depth-first, pre-order, traversal.
///
/// (*) Via reduction from 3-SAT: Introduce a package for each variable, with
/// two versions representing true and false. For each clause `C_n`, introduce a
/// package `P(C_n)` representing the clause, with three versions; one for each
/// satisfying assignment of values to a literal with the corresponding precise
/// constraint on the input packages. Finally, construct an input constraint
/// list including a dependency on each clause package `P(C_n)` and an
/// open-ended version constraint. The given input is satisfiable iff the input
/// 3-SAT instance is.
public class DependencyResolver<
P: PackageContainerProvider,
D: DependencyResolverDelegate
> where P.Container.Identifier == D.Identifier {
public typealias Provider = P
public typealias Delegate = D
public typealias Container = Provider.Container
public typealias Identifier = Container.Identifier
public typealias Binding = (container: Identifier, binding: BoundVersion)
/// The type of the constraints the resolver operates on.
///
/// Technically this is a container constraint, but that is currently the
/// only kind of constraints we operate on.
public typealias Constraint = PackageContainerConstraint<Identifier>
/// The type of constraint set the resolver operates on.
typealias ConstraintSet = PackageContainerConstraintSet<Container>
/// The type of assignment the resolver operates on.
typealias AssignmentSet = VersionAssignmentSet<Container>
/// The container provider used to load package containers.
public let provider: Provider
/// The resolver's delegate.
public let delegate: Delegate?
/// Should resolver prefetch the containers.
private let isPrefetchingEnabled: Bool
/// Skip updating containers while fetching them.
private let skipUpdate: Bool
// FIXME: @testable private
//
/// Contains any error encountered during dependency resolution.
var error: Swift.Error?
/// Key used to cache a resolved subtree.
private struct ResolveSubtreeCacheKey: Hashable {
let container: Container
let allConstraints: ConstraintSet
func hash(into hasher: inout Hasher) {
hasher.combine(container.identifier)
hasher.combine(allConstraints)
}
static func ==(lhs: ResolveSubtreeCacheKey, rhs: ResolveSubtreeCacheKey) -> Bool {
return lhs.container.identifier == rhs.container.identifier && lhs.allConstraints == rhs.allConstraints
}
}
/// Cache for subtree resolutions.
private var _resolveSubtreeCache: [ResolveSubtreeCacheKey: AnySequence<AssignmentSet>] = [:]
/// Puts the resolver in incomplete mode.
///
/// In this mode, no new containers will be requested from the provider.
/// Instead, if a container is not already present in the resolver, it will
/// skipped without raising an error. This is useful to avoid cloning
/// repositories from network when trying to partially resolve the constraints.
///
/// Note that the input constraints will always be fetched.
public var isInIncompleteMode = false
public init(
_ provider: Provider,
_ delegate: Delegate? = nil,
isPrefetchingEnabled: Bool = false,
skipUpdate: Bool = false
) {
self.provider = provider
self.delegate = delegate
self.isPrefetchingEnabled = isPrefetchingEnabled
self.skipUpdate = skipUpdate
}
/// The dependency resolver result.
public enum Result {
/// A valid and complete assignment was found.
case success([Binding])
/// The dependency graph was unsatisfiable.
///
/// The payload may contain conflicting constraints and pins.
///
/// - parameters:
/// - dependencies: The package dependencies which make the graph unsatisfiable.
/// - pins: The pins which make the graph unsatisfiable.
case unsatisfiable(dependencies: [Constraint], pins: [Constraint])
/// The resolver encountered an error during resolution.
case error(Swift.Error)
}
/// Execute the resolution algorithm to find a valid assignment of versions.
///
/// If a valid assignment is not found, the resolver will go into incomplete
/// mode and try to find the conflicting constraints.
public func resolve(
dependencies: [Constraint],
pins: [Constraint]
) -> Result {
do {
// Reset the incomplete mode and run the resolver.
self.isInIncompleteMode = false
let constraints = dependencies
return try .success(resolve(constraints: constraints, pins: pins))
} catch DependencyResolverError.unsatisfiable {
// FIXME: can we avoid this do..catch nesting?
do {
// If the result is unsatisfiable, try to debug.
let debugger = ResolverDebugger(self)
let badConstraints = try debugger.debug(dependencies: dependencies, pins: pins)
return .unsatisfiable(dependencies: badConstraints.dependencies, pins: badConstraints.pins)
} catch {
return .error(error)
}
} catch {
return .error(error)
}
}
/// Execute the resolution algorithm to find a valid assignment of versions.
///
/// - Parameters:
/// - constraints: The contraints to solve. It is legal to supply multiple
/// constraints for the same container identifier.
/// - Returns: A satisfying assignment of containers and their version binding.
/// - Throws: DependencyResolverError, or errors from the underlying package provider.
public func resolve(constraints: [Constraint], pins: [Constraint] = []) throws -> [(container: Identifier, binding: BoundVersion)] {
return try resolveAssignment(constraints: constraints, pins: pins).map({ assignment in
let (container, binding) = assignment
let identifier = try self.isInIncompleteMode ? container.identifier : container.getUpdatedIdentifier(at: binding)
// Get the updated identifier from the container.
return (identifier, binding)
})
}
/// Execute the resolution algorithm to find a valid assignment of versions.
///
/// - Parameters:
/// - constraints: The contraints to solve. It is legal to supply multiple
/// constraints for the same container identifier.
/// - Returns: A satisfying assignment of containers and versions.
/// - Throws: DependencyResolverError, or errors from the underlying package provider.
func resolveAssignment(constraints: [Constraint], pins: [Constraint] = []) throws -> AssignmentSet {
// Create a constraint set with the input pins.
var allConstraints = ConstraintSet()
for constraint in pins {
if let merged = allConstraints.merging(constraint) {
allConstraints = merged
} else {
// FIXME: We should issue a warning if the pins can't be merged
// for some reason.
}
}
// Create an assignment for the input constraints.
let mergedConstraints = merge(
constraints: constraints,
into: AssignmentSet(),
subjectTo: allConstraints,
excluding: [:])
// Prefetch the pins.
if !isInIncompleteMode && isPrefetchingEnabled {
prefetch(containers: pins.map({ $0.identifier }))
}
guard let assignment = mergedConstraints.first(where: { _ in true }) else {
// Throw any error encountered during resolution.
if let error = error {
throw error
}
throw DependencyResolverError.unsatisfiable
}
return assignment
}
// FIXME: This needs to a way to return information on the failure, or we
// will need to have it call the delegate directly.
//
// FIXME: @testable private
//
/// Resolve an individual container dependency tree.
///
/// This is the primary method in our bottom-up algorithm for resolving
/// dependencies. The inputs define an active set of constraints and set of
/// versions to exclude (conceptually the latter could be merged with the
/// former, but it is convenient to separate them in our
/// implementation). The result is a sequence of all valid assignments for
/// this container's subtree.
///
/// - Parameters:
/// - container: The container to resolve.
/// - constraints: The external constraints which must be honored by the solution.
/// - exclusions: The list of individually excluded package versions.
/// - Returns: A sequence of feasible solutions, starting with the most preferable.
func resolveSubtree(
_ container: Container,
subjectTo allConstraints: ConstraintSet,
excluding allExclusions: [Identifier: Set<Version>]
) -> AnySequence<AssignmentSet> {
// The key that is used to cache this assignement set.
let cacheKey = ResolveSubtreeCacheKey(container: container, allConstraints: allConstraints)
// Check if we have a cache hit for this subtree resolution.
//
// Note: We don't include allExclusions in the cache key so we ignore
// the cache if its non-empty.
//
// FIXME: We can improve the cache miss rate here if we have a cached
// entry with a broader constraint set. The cached sequence can be
// filtered according to the new narrower constraint set.
if allExclusions.isEmpty, let assignments = _resolveSubtreeCache[cacheKey] {
return assignments
}
func validVersions(_ container: Container, in versionSet: VersionSetSpecifier) -> AnySequence<Version> {
let exclusions = allExclusions[container.identifier] ?? Set()
return AnySequence(container.versions(filter: {
versionSet.contains($0) && !exclusions.contains($0)
}))
}
// Helper method to abstract passing common parameters to merge().
//
// FIXME: We must detect recursion here.
func merge(constraints: [Constraint], binding: BoundVersion) -> AnySequence<AssignmentSet> {
// Diagnose if this container depends on itself.
if constraints.contains(where: { $0.identifier == container.identifier }) {
error = DependencyResolverError.cycle(AnyPackageContainerIdentifier(container.identifier))
return AnySequence([])
}
// Create an assignment for the container.
var assignment = AssignmentSet()
assignment[container] = binding
return AnySequence(self.merge(
constraints: constraints,
into: assignment, subjectTo: allConstraints, excluding: allExclusions).lazy.map({ result in
// We might not have a complete result in incomplete mode.
if !self.isInIncompleteMode {
assert(result.checkIfValidAndComplete())
}
return result
}))
}
var result: AnySequence<AssignmentSet>
switch allConstraints[container.identifier] {
case .unversioned:
guard let constraints = self.safely({ try container.getUnversionedDependencies() }) else {
return AnySequence([])
}
// Merge the dependencies of unversioned constraint into the assignment.
result = merge(constraints: constraints, binding: .unversioned)
case .revision(let identifier):
guard let constraints = self.safely({ try container.getDependencies(at: identifier) }) else {
return AnySequence([])
}
result = merge(constraints: constraints, binding: .revision(identifier))
case .versionSet(let versionSet):
// The previous valid version that was picked.
var previousVersion: Version? = nil
// Attempt to select each valid version in the preferred order.
result = AnySequence(validVersions(container, in: versionSet).lazy
.flatMap({ version -> AnySequence<AssignmentSet> in
assert(previousVersion != nil ? previousVersion! > version : true,
"container versions are improperly ordered")
previousVersion = version
// If we had encountered any error, return early.
guard self.error == nil else { return AnySequence([]) }
// Get the constraints for this container version and update the assignment to include each one.
// FIXME: Making these methods throwing will kill the lazy behavior.
guard var constraints = self.safely({ try container.getDependencies(at: version) }) else {
return AnySequence([])
}
// Since we don't want to request additional containers in incomplete
// mode, remove any dependency that we don't already have.
if self.isInIncompleteMode {
constraints = constraints.filter({ self.containers[$0.identifier] != nil })
}
// Since this is a versioned container, none of its
// dependencies can have a revision constraints.
let incompatibleConstraints: [(AnyPackageContainerIdentifier, String)]
incompatibleConstraints = constraints.compactMap({
switch $0.requirement {
case .versionSet:
return nil
case .revision(let revision):
return (AnyPackageContainerIdentifier($0.identifier), revision)
case .unversioned:
// FIXME: Maybe we should have metadata inside unversion to signify
// if its a local or edited dependency. We add edited constraints
// as inputs so it shouldn't really matter because an edited
// requirement can't be specified in the manifest file.
return (AnyPackageContainerIdentifier($0.identifier), "local")
}
})
// If we have any revision constraints, set the error and abort.
guard incompatibleConstraints.isEmpty else {
self.error = DependencyResolverError.incompatibleConstraints(
dependency: (AnyPackageContainerIdentifier(container.identifier), version.description),
revisions: incompatibleConstraints)
return AnySequence([])
}
return merge(constraints: constraints, binding: .version(version))
}))
}
if allExclusions.isEmpty {
// Ensure we can cache this sequence.
result = AnySequence(CacheableSequence(result))
_resolveSubtreeCache[cacheKey] = result
}
return result
}
/// Find all solutions for `constraints` with the results merged into the `assignment`.
///
/// - Parameters:
/// - constraints: The input list of constraints to solve.
/// - assignment: The assignment to merge the result into.
/// - allConstraints: An additional set of constraints on the viable solutions.
/// - allExclusions: A set of package assignments to exclude from consideration.
/// - Returns: A sequence of all valid satisfying assignment, in order of preference.
private func merge(
constraints: [Constraint],
into assignment: AssignmentSet,
subjectTo allConstraints: ConstraintSet,
excluding allExclusions: [Identifier: Set<Version>]
) -> AnySequence<AssignmentSet> {
var allConstraints = allConstraints
// Never prefetch when running in incomplete mode.
if !isInIncompleteMode && isPrefetchingEnabled {
prefetch(containers: constraints.map({ $0.identifier }))
}
// Update the active constraint set to include all active constraints.
//
// We want to put all of these constraints in up front so that we are
// more likely to get back a viable solution.
//
// FIXME: We should have a test for this, probably by adding some kind
// of statistics on the number of backtracks.
for constraint in constraints {
guard let merged = allConstraints.merging(constraint) else {
return AnySequence([])
}
allConstraints = merged
}
// Perform an (eager) reduction merging each container into the (lazy)
// sequence of possible assignments.
//
// NOTE: What we are *accumulating* here is a lazy sequence (of
// solutions) satisfying some number of the constraints; the final lazy
// sequence is effectively one which has all of the constraints
// merged. Thus, the reduce itself can be eager since the result is
// lazy.
return AnySequence(constraints
.map({ $0.identifier })
.reduce(AnySequence([(assignment, allConstraints)]), {
(possibleAssignments, identifier) -> AnySequence<(AssignmentSet, ConstraintSet)> in
// If we had encountered any error, return early.
guard self.error == nil else { return AnySequence([]) }
// Get the container.
//
// Failures here will immediately abort the solution, although in
// theory one could imagine attempting to find a solution not
// requiring this container. It isn't clear that is something we
// would ever want to handle at this level.
//
// FIXME: Making these methods throwing will kill the lazy behavior,
guard let container = safely({ try getContainer(for: identifier) }) else {
return AnySequence([])
}
// Return a new lazy sequence merging all possible subtree solutions into all possible incoming
// assignments.
return AnySequence(possibleAssignments.lazy.flatMap({ value -> AnySequence<(AssignmentSet, ConstraintSet)> in
let (assignment, allConstraints) = value
let subtree = self.resolveSubtree(container, subjectTo: allConstraints, excluding: allExclusions)
return AnySequence(subtree.lazy.compactMap({ subtreeAssignment -> (AssignmentSet, ConstraintSet)? in
// We found a valid subtree assignment, attempt to merge it with the
// current solution.
guard let newAssignment = assignment.merging(subtreeAssignment) else {
// The assignment couldn't be merged with the current
// assignment, or the constraint sets couldn't be merged.
//
// This happens when (a) the subtree has a package overlapping
// with a previous subtree assignment, and (b) the subtrees
// needed to resolve different versions due to constraints not
// present in the top-down constraint set.
return nil
}
// Update the working assignment and constraint set.
//
// This should always be feasible, because all prior constraints
// were part of the input constraint request (see comment around
// initial `merge` outside the loop).
guard let merged = allConstraints.merging(subtreeAssignment.constraints) else {
preconditionFailure("unsatisfiable constraints while merging subtree")
}
// We found a valid assignment and updated constraint set.
return (newAssignment, merged)
}))
}))
})
.lazy
.map({ $0.0 }))
}
/// Executes the body and return the value if the body doesn't throw.
/// Returns nil if the body throws and save the error.
private func safely<T>(_ body: () throws -> T) -> T? {
do {
return try body()
} catch {
self.error = error
}
return nil
}
// MARK: Container Management
/// Condition for container management structures.
private let fetchCondition = Condition()
/// The active set of managed containers.
public var containers: [Identifier: Container] {
return fetchCondition.whileLocked({
_fetchedContainers.spm_flatMapValues({
try? $0.dematerialize()
})
})
}
/// The list of fetched containers.
private var _fetchedContainers: [Identifier: Basic.Result<Container, AnyError>] = [:]
/// The set of containers requested so far.
private var _prefetchingContainers: Set<Identifier> = []
/// Get the container for the given identifier, loading it if necessary.
fileprivate func getContainer(for identifier: Identifier) throws -> Container {
return try fetchCondition.whileLocked {
// Return the cached container, if available.
if let container = _fetchedContainers[identifier] {
return try container.dematerialize()
}
// If this container is being prefetched, wait for that to complete.
while _prefetchingContainers.contains(identifier) {
fetchCondition.wait()
}
// The container may now be available in our cache if it was prefetched.
if let container = _fetchedContainers[identifier] {
return try container.dematerialize()
}
// Otherwise, fetch the container synchronously.
let container = try await { provider.getContainer(for: identifier, skipUpdate: skipUpdate, completion: $0) }
self._fetchedContainers[identifier] = Basic.Result(container)
return container
}
}
/// Starts prefetching the given containers.
private func prefetch(containers identifiers: [Identifier]) {
fetchCondition.whileLocked {
// Process each container.
for identifier in identifiers {
// Skip if we're already have this container or are pre-fetching it.
guard _fetchedContainers[identifier] == nil,
!_prefetchingContainers.contains(identifier) else {
continue
}
// Otherwise, record that we're prefetching this container.
_prefetchingContainers.insert(identifier)
provider.getContainer(for: identifier, skipUpdate: skipUpdate) { container in
self.fetchCondition.whileLocked {
// Update the structures and signal any thread waiting
// on prefetching to finish.
self._fetchedContainers[identifier] = container
self._prefetchingContainers.remove(identifier)
self.fetchCondition.signal()
}
}
}
}
}
}
/// The resolver debugger.
///
/// Finds the constraints which results in graph being unresolvable.
private struct ResolverDebugger<
Provider: PackageContainerProvider,
Delegate: DependencyResolverDelegate
> where Provider.Container.Identifier == Delegate.Identifier {
typealias Identifier = Provider.Container.Identifier
typealias Constraint = PackageContainerConstraint<Identifier>
enum Error: Swift.Error {
/// Reached the time limit without completing the algorithm.
case reachedTimeLimit
}
/// Reference to the resolver.
unowned let resolver: DependencyResolver<Provider, Delegate>
/// Create a new debugger.
init(_ resolver: DependencyResolver<Provider, Delegate>) {
self.resolver = resolver
}
/// The time limit in seconds after which we abort finding a solution.
let timeLimit = 10.0
/// Returns the constraints which should be removed in order to make the
/// graph resolvable.
///
/// We use delta debugging algoritm to find the smallest set of constraints
/// which can be removed from the input in order to make the graph
/// satisfiable.
///
/// This algorithm can be exponential, so we abort after the predefined time limit.
func debug(
dependencies inputDependencies: [Constraint],
pins inputPins: [Constraint]
) throws -> (dependencies: [Constraint], pins: [Constraint]) {
// Form the dependencies array.
//
// We iterate over the inputs and fetch all the dependencies for
// unversioned requirements as the unversioned requirements are not
// relevant to the dependency resolution.
var dependencies = [Constraint]()
for constraint in inputDependencies {
if constraint.requirement == .unversioned {
// Ignore the errors here.
do {
let container = try resolver.getContainer(for: constraint.identifier)
dependencies += try container.getUnversionedDependencies()
} catch {}
} else {
dependencies.append(constraint)
}
}
// Form a set of all unversioned dependencies.
let unversionedDependencies = Set(inputDependencies.filter({ $0.requirement == .unversioned }).map({ $0.identifier }))
// Remove the unversioned constraints from dependencies and pins.
dependencies = dependencies.filter({ !unversionedDependencies.contains($0.identifier) })
let pins = inputPins.filter({ !unversionedDependencies.contains($0.identifier) })
// Put the resolver in incomplete mode to avoid cloning new repositories.
resolver.isInIncompleteMode = true
let deltaAlgo = DeltaAlgorithm<ResolverChange>()
let allPackages = Set(dependencies.map({ $0.identifier }))
// Compute the set of changes.
let allChanges: Set<ResolverChange> = {
var set = Set<ResolverChange>()
set.formUnion(dependencies.map({ ResolverChange.allowPackage($0.identifier) }))
set.formUnion(pins.map({ ResolverChange.allowPin($0.identifier) }))
return set
}()
// Compute the current time.
let startTime = NSDate().timeIntervalSince1970
var timeLimitReached = false
// Run the delta debugging algorithm.
let badChanges = try deltaAlgo.run(changes: allChanges) { changes in
// Check if we reached the time limits.
timeLimitReached = timeLimitReached || (NSDate().timeIntervalSince1970 - startTime) >= timeLimit
// If we reached the time limit, throw.
if timeLimitReached {
throw Error.reachedTimeLimit
}
// Find the set of changes we want to allow in this predicate.
let allowedChanges = allChanges.subtracting(changes)
// Find the packages which are allowed and disallowed to participate
// in this changeset.
let allowedPackages = Set(allowedChanges.compactMap({ $0.allowedPackage }))
let disallowedPackages = allPackages.subtracting(allowedPackages)
// Start creating constraints.
//
// First, add all the package dependencies.
var constraints = dependencies
// Set all disallowed packages to unversioned, so they stay out of resolution.
constraints += disallowedPackages.map({
Constraint(container: $0, requirement: .unversioned)
})
let allowedPins = Set(allowedChanges.compactMap({ $0.allowedPin }))
// It is always a failure if this changeset contains a pin of
// a disallowed package.
if allowedPins.first(where: disallowedPackages.contains) != nil {
return false
}
// Finally, add the allowed pins.
constraints += pins.filter({ allowedPins.contains($0.identifier) })
return try satisfies(constraints)
}
// Filter the input with found result and return.
let badDependencies = Set(badChanges.compactMap({ $0.allowedPackage }))
let badPins = Set(badChanges.compactMap({ $0.allowedPin }))
return (
dependencies: dependencies.filter({ badDependencies.contains($0.identifier) }),
pins: pins.filter({ badPins.contains($0.identifier) })
)
}
/// Returns true if the constraints are satisfiable.
func satisfies(_ constraints: [Constraint]) throws -> Bool {
do {
_ = try resolver.resolve(constraints: constraints, pins: [])
return true
} catch DependencyResolverError.unsatisfiable {
return false
}
}
/// Represents a single change which should introduced during delta debugging.
enum ResolverChange: Hashable {
/// Allow the package with the given identifier.
case allowPackage(Identifier)
/// Allow the pins with the given identifier.
case allowPin(Identifier)
/// Returns the allowed pin identifier.
var allowedPin: Identifier? {
if case let .allowPin(identifier) = self {
return identifier
}
return nil
}
// Returns the allowed package identifier.
var allowedPackage: Identifier? {
if case let .allowPackage(identifier) = self {
return identifier
}
return nil
}
}
}
| apache-2.0 | 68670e58e246380ff95e081ceb24cd94 | 39.998628 | 136 | 0.627693 | 5.346691 | false | false | false | false |
lkzhao/MotionAnimation | MotionAnimationExample/LZPanGestureRecognizer.swift | 1 | 1595 | //
// LZPanGestureRecognizer.swift
// DynamicView
//
// Created by YiLun Zhao on 2016-01-25.
// Copyright © 2016 lkzhao. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
open class LZPanGestureRecognizer: UIPanGestureRecognizer {
open var startViewCenterPoint:CGPoint?
open var translatedViewCenterPoint:CGPoint{
if let startViewCenterPoint = startViewCenterPoint{
var p = startViewCenterPoint + translation(in: self.view!.superview!)
p.x = clamp(p.x, range:xRange, overflowScale:xOverflowScale)
p.y = clamp(p.y, range:yRange, overflowScale:yOverflowScale)
return p
}else{
return self.view?.center ?? CGPoint.zero
}
}
open func clamp(_ element: CGFloat, range:ClosedRange<CGFloat>, overflowScale:CGFloat = 0) -> CGFloat {
if element < range.lowerBound{
return range.lowerBound - (range.lowerBound - element)*overflowScale
} else if element > range.upperBound{
return range.upperBound + (element - range.upperBound)*overflowScale
}
return element
}
open var xOverflowScale:CGFloat = 0.3
open var yOverflowScale:CGFloat = 0.3
open var xRange:ClosedRange<CGFloat> = CGFloat.leastNormalMagnitude...CGFloat.greatestFiniteMagnitude
open var yRange:ClosedRange<CGFloat> = CGFloat.leastNormalMagnitude...CGFloat.greatestFiniteMagnitude
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
if state == .failed{
return
}
startViewCenterPoint = self.view?.center
}
}
| mit | 57b929d3ff22d5a1e44edeac4c542063 | 29.653846 | 105 | 0.721455 | 4.239362 | false | false | false | false |
na4lapy/Na4LapyAPI | Sources/Na4LapyCore/SecUserController.swift | 2 | 5933 | //
// LoginController.swift
// Na4lapyAPI
//
// Created by scoot on 04.01.2017.
//
//
import Kitura
import LoggerAPI
import Foundation
import SwiftyJSON
import KituraSession
public class SecUserController: SessionCheckable {
public let router = Router()
private let db: DBLayer
public init(db: DBLayer) {
self.db = db
setup()
}
//
// MARK: konfiguracja routerów
//
private func setup() {
router.post("/login", handler: onLogin)
router.get("/logout", handler: onLogout)
router.post("/change_password", handler: onPasswordChange)
router.patch("/terms_of_use", handler: onTermsOfUseChange)
router.get("/terms_of_use", handler: onTermsOfUseGet)
}
//
// MARK: obsługa requestów
//
private func onLogin(request: RouterRequest, response: RouterResponse, next: () -> Void) {
do {
var data = Data()
_ = try request.read(into: &data)
let json = JSON(data: data).dictionaryObject ?? [:]
guard let email = json["email"] as? String,
let password = json["password"] as? String else {
response.status(.forbidden)
try? response.end()
Log.error("Zły login lub hasło")
return
}
let shelterId = try db.checkLogin(email: email, password: password)
let sess = request.session
sess?[SecUserDBKey.shelterid] = JSON(shelterId)
try response.status(.OK).end()
} catch (let error) {
Log.error(error.localizedDescription)
response.status(.forbidden)
try? response.end()
}
}
private func onLogout(request: RouterRequest, response: RouterResponse, next: () -> Void) {
let sess = request.session
sess?.destroy{ _ in }
do {
try response.status(.OK).end()
} catch (let error) {
Log.error(error.localizedDescription)
response.status(.internalServerError)
try? response.end()
}
}
private func onPasswordChange(request: RouterRequest, response: RouterResponse, next: () -> Void) {
//check sessions
do {
let shelterId = try checkSession(request: request, response: response)
var data = Data()
_ = try request.read(into: &data)
let json = JSON(data: data)
let secUser = try SecUser(withJSON: json)
if let secUser = secUser {
let updatedId = try db.updatePassword(forUser: secUser, withShelterId: shelterId)
try? response.status(.OK).send("\(updatedId)").end()
} else {
response.status(.unprocessableEntity).send("Could not create secUser")
}
} catch (let error) {
//MARK: error check
if let secUserError = error as? SecUserError {
var errorJson: JSON?
switch secUserError {
case .missingParams(let json):
errorJson = json
case .newPasswordAndRepeatNotTheSame(let json):
errorJson = json
case .newPasswordSameAsOld(let json):
errorJson = json
case .wrongOldPassword(let json):
errorJson = json
default:
break
}
Log.error(errorJson.debugDescription)
response.status(.unprocessableEntity)
if let errorJson = errorJson {
response.send(json: errorJson)
}
}
}
try? response.end()
}
/// Called when panel is trying to accepts terms of use, SECURED BY COOKIE CHECK
///
/// - Parameters:
/// - request: request should contain areTermsOfUseAccepted bool, value
/// - response: response
/// - next: func to call next
private func onTermsOfUseChange(request: RouterRequest, response: RouterResponse, next: () -> Void) {
do {
let shelterId = try checkSession(request: request, response: response)
var data = Data()
_ = try request.read(into: &data)
let json = JSON(data: data)
guard let areTermsOfUserAccepted = json["areTermsOfUseAccepted"].bool else {
throw SecUserError.missingParams(JSON(["areTermsOfUseAccepted", JSON.missingParamJsonErrorString]))
}
let updatedId = try db.update(areTermsOfUseAccepted: areTermsOfUserAccepted, forShelterId: shelterId)
try? response.status(.OK).send("\(updatedId)").end()
} catch (let error) {
if let secUserError = error as? SecUserError {
var errorJson: JSON?
switch secUserError {
case .missingParams(let json):
errorJson = json
default:
break
}
Log.error(error.localizedDescription)
response.status(.unprocessableEntity)
if let errorJson = errorJson {
response.send(json: errorJson)
}
}
try? response.end()
}
}
private func onTermsOfUseGet(request: RouterRequest, response: RouterResponse, next: () -> Void) {
do {
let shelterId = try checkSession(request: request, response: response)
let areTermsOfUseAccepterd = try db.areTermsOfUseAccepted(forShelterId: shelterId)
try? response.status(.OK).send("\(areTermsOfUseAccepterd)").end()
} catch (let error) {
Log.error(error.localizedDescription)
response.status(.internalServerError)
try? response.end()
}
}
}
| apache-2.0 | 6dd3b9c3788e09c7e0e369749ce9f943 | 30.036649 | 115 | 0.551282 | 4.697306 | false | false | false | false |
damoyan/BYRClient | FromScratch/Controller/SectionViewController.swift | 1 | 3783 | //
// SectionViewController.swift
// FromScratch
//
// Created by Yu Pengyang on 12/21/15.
// Copyright © 2015 Yu Pengyang. All rights reserved.
//
import UIKit
class SectionViewController: BaseTableViewController {
var section: Section?
override func viewDidLoad() {
super.viewDidLoad()
self.title = section?.desc
tableView.tableFooterView = UIView()
loadData()
}
var isLoading = false
private func loadData() {
if isLoading {
print("isloading or section is nil")
return
}
isLoading = true
guard let section = self.section else {
API.Sections.handleResponse({ [weak self] (_, _, data, error) -> () in
guard let strongSelf = self else {
return
}
strongSelf.isLoading = false
guard let data = data else {
// TODO: -
print(error?.localizedDescription)
return
}
strongSelf.content = Section.generateArray(data["section"])
strongSelf.tableView.reloadData()
})
return
}
guard let name = section.name else {
print("name is nil of section", section)
isLoading = false
return
}
API.Section(name: name).handleResponse { [weak self] (_, _, d, e) -> () in
guard let data = d else {
print(e!.localizedDescription)
self?.isLoading = false
return
}
self?.section = Section(data: data)
self?.isLoading = false
self?.display()
}
}
var content: [AnyObject] = []
private func display() {
content.removeAll(keepCapacity: false)
if let sections = section?.subSections {
content += sections as [AnyObject]
}
if let boards = section?.boards {
content += boards as [AnyObject]
}
self.title = section?.desc
tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return content.count
}
let cellID = "cell"
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(cellID)
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellID)
}
let data = content[indexPath.row]
switch data {
case let s as Section:
cell?.textLabel?.text = s.desc ?? s.name
cell?.detailTextLabel?.text = "[分区]"
case let b as Board:
cell?.textLabel?.text = b.desc ?? b.name
cell?.detailTextLabel?.text = nil
default:
break
}
cell?.detailTextLabel?.textColor = AppSharedInfo.sharedInstance.currentTheme.BoardNaviCellSubtitleColor
cell?.accessoryType = .DisclosureIndicator
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let data = content[indexPath.row]
switch data {
case let s as Section:
navigateToSectionDetail(s)
case let b as Board:
if let name = b.name {
navigateToBoard(name)
}
break
default:
break
}
}
}
| mit | d23694d5a57148b1eb984c499ca3b2fe | 30.483333 | 118 | 0.553997 | 5.269177 | false | false | false | false |
huahuasj/ios-charts | Charts/Classes/Charts/LineChartView.swift | 3 | 2727 | //
// LineChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
/// Chart that draws lines, surfaces, circles, ...
public class LineChartView: BarLineChartViewBase, LineChartRendererDelegate
{
private var _fillFormatter: ChartFillFormatter!
internal override func initialize()
{
super.initialize();
renderer = LineChartRenderer(delegate: self, animator: _animator, viewPortHandler: _viewPortHandler);
_fillFormatter = BarLineChartFillFormatter(chart: self);
}
internal override func calcMinMax()
{
super.calcMinMax();
if (_deltaX == 0.0 && _data.yValCount > 0)
{
_deltaX = 1.0;
}
}
public var fillFormatter: ChartFillFormatter!
{
get
{
return _fillFormatter;
}
set
{
if (newValue === nil)
{
_fillFormatter = BarLineChartFillFormatter(chart: self);
}
else
{
_fillFormatter = newValue;
}
}
}
// MARK: - LineChartRendererDelegate
public func lineChartRendererData(renderer: LineChartRenderer) -> LineChartData!
{
return _data as! LineChartData!;
}
public func lineChartRenderer(renderer: LineChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!
{
return self.getTransformer(which);
}
public func lineChartRendererFillFormatter(renderer: LineChartRenderer) -> ChartFillFormatter
{
return self.fillFormatter;
}
public func lineChartDefaultRendererValueFormatter(renderer: LineChartRenderer) -> NSNumberFormatter!
{
return self._defaultValueFormatter;
}
public func lineChartRendererChartYMax(renderer: LineChartRenderer) -> Float
{
return self.chartYMax;
}
public func lineChartRendererChartYMin(renderer: LineChartRenderer) -> Float
{
return self.chartYMin;
}
public func lineChartRendererChartXMax(renderer: LineChartRenderer) -> Float
{
return self.chartXMax;
}
public func lineChartRendererChartXMin(renderer: LineChartRenderer) -> Float
{
return self.chartXMin;
}
public func lineChartRendererMaxVisibleValueCount(renderer: LineChartRenderer) -> Int
{
return self.maxVisibleValueCount;
}
} | apache-2.0 | ffb1e6d261b20ef10d5c5c96beb43a14 | 24.735849 | 136 | 0.627429 | 5.553971 | false | false | false | false |
icylydia/PlayWithLeetCode | 63. Unique Paths II/solution.swift | 1 | 963 | class Solution {
func uniquePathsWithObstacles(obstacleGrid: [[Int]]) -> Int {
let m = obstacleGrid.count
let n = obstacleGrid[0].count
var ans = Array<Array<Int>>()
var firstLine = [Int](count: n, repeatedValue: 0)
for i in 0..<n {
if obstacleGrid[0][i] == 0 {
firstLine[i] = 1
} else {
break
}
}
ans.append(firstLine)
for i in 1..<m {
var line = [Int]()
if(ans[i-1][0] == 0 || obstacleGrid[i][0] == 1) {
line.append(0)
} else {
line.append(1)
}
for j in 1..<n {
if(obstacleGrid[i][j] == 1) {
line.append(0)
} else {
line.append(line[j-1] + ans[i-1][j])
}
}
ans.append(line)
}
return ans[m-1][n-1]
}
}
| mit | 3f15df47155b66b873bfb4e3f9a2edc3 | 28.181818 | 65 | 0.389408 | 3.852 | false | false | false | false |
hanhailong/practice-swift | Multimedia/Playing Audio Files/Playing Audio Files/ViewController.swift | 2 | 1780 | //
// ViewController.swift
// Playing Audio Files
//
// Created by Domenico on 23/05/15.
// License MIT
//
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
var queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue, {[weak self] in
var strongSelf = self!
let mainBundle = NSBundle.mainBundle()
// Location of the audio file
let filePath = mainBundle.pathForResource("MySong", ofType: "mp3")
if let path = filePath{
let fileData = NSData(contentsOfFile: path)
var error: NSError?
// Start the audio player
strongSelf.audioPlayer = AVAudioPlayer(data: fileData, error: &error)
if let player = strongSelf.audioPlayer{
// Set the delegate
player.delegate = self
if player.prepareToPlay() && player.play(){
println("Successfully started playing")
}else{
println("Failed to play")
}
}else{
println("Cannot instantiate an audio player")
}
}
})
}
//- MARK: AVAudioPlayerDelegate
// This delegate method will let us know when the audio player will finish playing
// the file
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
println("Finished playing....")
}
}
| mit | b24608baf920077e5ee717f3c7d5b406 | 30.22807 | 87 | 0.535955 | 5.779221 | false | false | false | false |
joseph-zhong/CommuterBuddy-iOS | SwiftSideMenu/Utility/DoubleExtensions.swift | 4 | 1560 | //
// DoubleExtensions.swift
// EZSwiftExtensionsExample
//
// Created by Goktug Yilmaz on 12/19/15.
// Copyright © 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
import Foundation
extension Double {
/// EZSE: Converts Double to String
public var toString: String { return String(self) }
/// EZSE: Converts Double to Int
public var toInt: Int { return Int(self) }
// TODO: castToDecimalByPlacesHelper & Darwiing.ceil are not the same behaviour
// TODO rename methods
/// EZSE: Returns a Double rounded to decimal
public func getRoundedByPlaces(_ places: Int) -> Double {
guard places >= 0 else { return self }
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
/// EZSE: Rounds the current Double rounded to decimal
public mutating func roundByPlaces(_ places: Int) {
self = getRoundedByPlaces(places)
}
/// EZSE: Returns a Double Ceil to decimal
public func getCeiledByPlaces(_ places: Int) -> Double {
return castToDecimalByPlacesHelper(places, function: ceil)
}
/// EZSE: Ceils current Double to number of places
public mutating func ceilByPlaces(_ places: Int) {
self = castToDecimalByPlacesHelper(places, function: ceil)
}
fileprivate func castToDecimalByPlacesHelper(_ places: Int, function: (Double) -> Double) -> Double {
guard places >= 0 else { return self }
let divisor = pow(10.0, Double(places))
return ceil(self * divisor) / divisor
}
}
| mit | 1d11f792bba77de7fc50d5c5bf268938 | 32.170213 | 105 | 0.666453 | 4.179625 | false | false | false | false |
4eleven7/Contacts | Contacts/Extensions/NSDate+LongAgo.swift | 1 | 3481 | //
// NSDate+LongAgo.swift
// Contacts
//
// Created by Daniel Love on 07/05/2015.
// Copyright (c) 2015 Daniel Love. All rights reserved.
//
import Foundation
extension NSDate
{
// MARK: Comparisons
func isWeekend() -> Bool
{
let calendar: NSCalendar = NSCalendar.currentCalendar()
return calendar.isDateInWeekend(self)
}
func isBetweenTime(start:Int = 9, end: Int = 17) -> Bool
{
let calendar: NSCalendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitHour, fromDate: self)
return components.hour > start && components.hour < end
}
func isSameWeekAsDate(date: NSDate) -> Bool
{
let calendar: NSCalendar = NSCalendar.currentCalendar()
return calendar.isDate(self, equalToDate: date, toUnitGranularity: NSCalendarUnit.CalendarUnitWeekOfYear)
}
func isLastWeek() -> Bool
{
let dayFlags: NSCalendarUnit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekday
let calendar: NSCalendar = NSCalendar.currentCalendar()
var components: NSDateComponents = calendar.components(dayFlags, fromDate: NSDate())
components.hour = 0
components.minute = 0
components.second = 0
components.day -= 8
var referenceDate: NSDate = calendar.dateFromComponents(components)!
return self.compare(referenceDate) == NSComparisonResult.OrderedDescending
}
// MARK: To string
func dateString() -> String
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM HH:mm"
return dateFormatter.stringFromDate(self)
}
func friendlyDayString() -> String
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.stringFromDate(self)
}
func toHumanisedString() -> String
{
let dayFlags: NSCalendarUnit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekday
let hourFlags: NSCalendarUnit = NSCalendarUnit.CalendarUnitHour
let calendar: NSCalendar = NSCalendar.currentCalendar()
// Is today?
if calendar.isDateInToday(self)
{
let hourComponent = calendar.components(hourFlags, fromDate: self)
if hourComponent.hour < 4 {
return NSLocalizedString("Last night", comment: "Date added between midnight and 4am")
}
else if hourComponent.hour > 4 && hourComponent.hour < 8 {
return NSLocalizedString("This morning", comment: "Date added after 4am, before 8am")
}
else {
return NSLocalizedString("Today", comment: "Date added after 8am")
}
}
// Was it Yesterday?
if calendar.isDateInYesterday(self)
{
let hourComponent = calendar.components(hourFlags, fromDate: self)
if hourComponent.hour > 20 {
return NSLocalizedString("Last night", comment: "Date added after 8pm yesterday")
}
else if hourComponent.hour > 4 && hourComponent.hour < 8 {
return NSLocalizedString("Yesterday morning", comment: "Date added after 4am, before 8am yesterday")
}
else {
return NSLocalizedString("Yesterday", comment: "Date added after 8am yesterday")
}
}
// Was it this week?
if self.isSameWeekAsDate(NSDate())
{
return self.friendlyDayString()
}
// Was it last week?
if self.isLastWeek()
{
return NSLocalizedString("Last %@", value: self.friendlyDayString(), comment: "A day last week, last {day name}, Last thursday")
}
return self.dateString()
}
}
| mit | 385ac75b3e44156f439e2eb04123e5b7 | 29.008621 | 169 | 0.729675 | 4.010369 | false | false | false | false |
geraldWilliam/Tenkay | Pod/Classes/JSON.swift | 1 | 912 | //
// JSON.swift
// Tenkay
//
// Created by Gerald Burke on 2/20/16.
// Copyright © 2016 Gerald Burke. All rights reserved.
//
import Foundation
let jsonErrorDomain = "json_error_domain"
public typealias JSON = [String : AnyObject]
/**
Get the raw data from the JSON object
*/
public extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject {
public func data() -> Result<NSData> {
do {
guard let dict = (self as? AnyObject) as? JSON else {
let error = NSError(domain: jsonErrorDomain, code: 999, userInfo: [
NSLocalizedDescriptionKey : "data() must be called on a value of type JSON (aka [String : AnyObject])"
]
)
return .Error(error)
}
let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)
return .Value(jsonData)
} catch {
return .Error(error)
}
}
} | mit | 11cfb764d16acc5787bc1a814b62bccb | 25.057143 | 112 | 0.648738 | 4.013216 | false | false | false | false |
almazrafi/Metatron | Sources/ID3v2/FrameStuffs/ID3v2LyricsValue.swift | 1 | 2566 | //
// ID3v2LyricsValue.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension ID3v2SyncedLyrics {
// MARK: Instance Properties
public var lyricsValue: TagLyrics {
get {
var pieces: [TagLyrics.Piece] = []
if self.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds {
for syllable in self.syllables {
pieces.append(TagLyrics.Piece(syllable.text, timeStamp: UInt(syllable.timeStamp)))
}
} else {
for syllable in self.syllables {
pieces.append(TagLyrics.Piece(syllable.text))
}
}
return TagLyrics(pieces: pieces)
}
set {
self.syllables.removeAll()
for piece in newValue.pieces {
let timeStamp = UInt32(min(UInt64(piece.timeStamp), UInt64(UInt32.max)))
self.syllables.append(Syllable(piece.text, timeStamp: timeStamp))
}
self.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
}
}
}
public extension ID3v2UnsyncedLyrics {
// MARK: Instance Properties
public var lyricsValue: TagLyrics {
get {
if !self.content.isEmpty {
return TagLyrics(pieces: [TagLyrics.Piece(self.content)])
}
return TagLyrics()
}
set {
self.content = newValue.description
}
}
}
| mit | c06ee1511ca1cc4aeb0faeb6b39f31d0 | 31.075 | 102 | 0.653936 | 4.341794 | false | false | false | false |
MagicTheGathering/mtg-sdk-swift | MTGSDKSwift/URLBuilder.swift | 1 | 1794 | //
// URLBuilder.swift
// MTGSDKSwift
//
// Created by Reed Carson on 4/5/18.
// Copyright © 2018 Reed Carson. All rights reserved.
//
import Foundation
final class URLBuilder {
static func buildURLWithParameters(_ parameters: [SearchParameter],
andConfig config: MTGSearchConfiguration = MTGSearchConfiguration.defaultConfiguration) -> URL? {
var urlComponents = URLComponents()
urlComponents.scheme = Constants.scheme
urlComponents.host = Constants.host
urlComponents.path = {
if parameters is [CardSearchParameter] {
return Constants.cardsEndpoint
} else {
return Constants.setsEndpoint
}
}()
urlComponents.queryItems = buildQueryItemsFromParameters(parameters, config)
debugPrint("MTGSDK URL: \(String(describing: urlComponents.url))\n")
return urlComponents.url
}
private static func buildQueryItemsFromParameters(_ parameters: [SearchParameter],
_ config: MTGSearchConfiguration = MTGSearchConfiguration.defaultConfiguration) -> [URLQueryItem] {
var queryItems = [URLQueryItem]()
let pageSizeQuery = URLQueryItem(name: "pageSize", value: String(config.pageSize))
let pageQuery = URLQueryItem(name: "page", value: String(config.pageTotal))
queryItems.append(pageQuery)
queryItems.append(pageSizeQuery)
for parameter in parameters {
let name = parameter.name
let value = parameter.value
let item = URLQueryItem(name: name, value: value)
queryItems.append(item)
}
return queryItems
}
}
| mit | 910eadbd151eb96360f1e4ae65e21d86 | 34.86 | 146 | 0.615728 | 5.304734 | false | true | false | false |
david1mdavis/IOS-nRF-Toolbox | nRF Toolbox/DFU/FileSelection/NORFolderFilesViewController.swift | 2 | 4851 | //
// NORFolderFilesViewController.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 12/05/16.
// Copyright © 2016 Nordic Semiconductor. All rights reserved.
//
import UIKit
class NORFolderFilesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//MARK: - Class Properties
var files : Array<URL>?
var directoryPath : String?
var directoryName : String?
var fileDelegate : NORFileSelectionDelegate?
var preselectionDelegate : NORFilePreselectionDelegate?
var selectedPath : URL?
//MARK: - View Outlets
@IBOutlet weak var emptyView: UIView!
@IBOutlet weak var tableView: UITableView!
//MARK: - View Actions
@IBAction func doneButtonTapped(_ sender: AnyObject) {
doneButtonTappedEventHandler()
}
//MARK: - UIViewDelegate
override func viewDidLoad() {
super.viewDidLoad()
if directoryName != nil {
self.navigationItem.title = directoryName!
}else{
self.navigationItem.title = "Files"
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let enabled = (selectedPath != nil)
self.navigationItem.rightBarButtonItem?.isEnabled = enabled
do {
try self.files = FileManager.default.contentsOfDirectory(at: selectedPath!, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
}catch{
print(error)
}
self.ensureDirectoryNotEmpty()
}
//MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (files?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let aCell = tableView.dequeueReusableCell(withIdentifier: "FolderFilesCell", for:indexPath)
let aFilePath = files?[indexPath.row]
let fileName = aFilePath?.lastPathComponent
//Configuring the cell
aCell.textLabel?.text = fileName
if fileName?.lowercased().contains(".hex") != false {
aCell.imageView?.image = UIImage(named: "ic_file")
}else if fileName?.lowercased().contains(".bin") != false {
aCell.imageView?.image = UIImage(named: "ic_file")
}else if fileName?.lowercased().contains(".zip") != false {
aCell.imageView?.image = UIImage(named: "ic_archive")
}else{
aCell.imageView?.image = UIImage(named: "ic_file")
}
if aFilePath == selectedPath {
aCell.accessoryType = UITableViewCellAccessoryType.checkmark
}else{
aCell.accessoryType = UITableViewCellAccessoryType.none
}
return aCell
}
//MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let filePath = files?[indexPath.row]
selectedPath = filePath
tableView.reloadData()
navigationItem.rightBarButtonItem!.isEnabled = true
self.preselectionDelegate?.onFilePreselected(withURL: filePath!)
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.delete
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == UITableViewCellEditingStyle.delete else {
return
}
let filePath = files?[indexPath.row]
do{
try FileManager.default.removeItem(at: filePath!)
}catch{
print("Error while deleting file: \(error)")
return
}
files?.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
if filePath == selectedPath {
selectedPath = nil
self.preselectionDelegate?.onFilePreselected(withURL: filePath!)
self.navigationItem.rightBarButtonItem?.isEnabled = false
}
self.ensureDirectoryNotEmpty()
}
//MARK: - NORFolderFilesViewController Implementation
func ensureDirectoryNotEmpty() {
if (files?.count)! == 0 {
emptyView.isHidden = false
}
}
func doneButtonTappedEventHandler(){
// Go back to DFUViewController
dismiss(animated: true) {
self.fileDelegate?.onFileSelected(withURL: self.selectedPath!)
}
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)
}
}
| bsd-3-clause | d7b3b1e9a66c528a2d2b80a3ea50d797 | 33.642857 | 144 | 0.639175 | 5.335534 | false | false | false | false |
marta-rodriguez/swift-learning | FlickrSearch-Starter/FlickrSearch/OrderedDictionary.swift | 1 | 2296 | //
// OrderedDictionary.swift
// FlickrSearch
//
// Created by Marta Rodriguez on 17/11/15.
// Copyright © 2015 Razeware. All rights reserved.
//
import Foundation
struct OrderedDictionary<KeyType: Hashable, ValueType> {
typealias ArrayType = [KeyType]
typealias DictionaryType = [KeyType: ValueType]
var array = ArrayType()
var dictionary = DictionaryType()
var count: Int {
return self.array.count
}
// 1
mutating func insert(value: ValueType, forKey key: KeyType, atIndex index: Int) -> ValueType? {
var adjustedIndex = index
// 2
let existingValue = self.dictionary[key]
if existingValue != nil {
// 3
let existingIndex = self.array.indexOf(key)!
// 4
if existingIndex < index {
adjustedIndex--
}
self.array.removeAtIndex(existingIndex)
}
// 5
self.array.insert(key, atIndex:adjustedIndex)
self.dictionary[key] = value
// 6
return existingValue
}
// 1
mutating func removeAtIndex(index: Int) -> (KeyType, ValueType) {
// 2
precondition(index < self.array.count, "Index out-of-bounds")
// 3
let key = self.array.removeAtIndex(index)
// 4
let value = self.dictionary.removeValueForKey(key)!
// 5
return (key, value)
}
// 1
subscript(key: KeyType) -> ValueType? {
// 2(a)
get {
// 3
return self.dictionary[key]
}
// 2(b)
set {
// 4
if let index = self.array.indexOf(key) {
} else {
self.array.append(key)
}
// 5
self.dictionary[key] = newValue
}
}
subscript(index: Int) -> (KeyType, ValueType) {
// 1
get {
// 2
precondition(index < self.array.count, "Index out-of-bounds")
// 3
let key = self.array[index]
// 4
let value = self.dictionary[key]!
// 5
return (key, value)
}
}
} | mit | 8659ce208422cb9107561193b4106ca3 | 26.011765 | 99 | 0.485839 | 4.645749 | false | false | false | false |
ahoppen/swift | test/SILGen/objc_async_from_swift.swift | 2 | 12008 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -I %S/Inputs/custom-modules -disable-availability-checking %s -verify | %FileCheck --implicit-check-not=hop_to_executor --check-prefix=CHECK --check-prefix=CHECK-%target-cpu %s
// REQUIRES: concurrency
// REQUIRES: objc_interop
import Foundation
import ObjCConcurrency
@objc protocol SlowServing {
func requestInt() async -> Int
func requestString() async -> String
func tryRequestString() async throws -> String
func requestIntAndString() async -> (Int, String)
func tryRequestIntAndString() async throws -> (Int, String)
}
// CHECK-LABEL: sil {{.*}}@{{.*}}15testSlowServing
func testSlowServing(p: SlowServing) async throws {
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK: objc_method {{.*}} $@convention(objc_method) <τ_0_0 where τ_0_0 : SlowServing> (@convention(block) (Int) -> (), τ_0_0) -> ()
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
let _: Int = await p.requestInt()
// CHECK: objc_method {{.*}} $@convention(objc_method) <τ_0_0 where τ_0_0 : SlowServing> (@convention(block) (NSString) -> (), τ_0_0) -> ()
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
let _: String = await p.requestString()
// CHECK: objc_method {{.*}} $@convention(objc_method) <τ_0_0 where τ_0_0 : SlowServing> (@convention(block) (Int, NSString) -> (), τ_0_0) -> ()
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
let _: (Int, String) = await p.requestIntAndString()
// CHECK: objc_method {{.*}} $@convention(objc_method) <τ_0_0 where τ_0_0 : SlowServing> (@convention(block) (Int, Optional<NSString>, Optional<NSError>) -> (), τ_0_0) -> ()
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK-NEXT: builtin "willThrow"
let _: (Int, String) = try await p.tryRequestIntAndString()
}
// CHECK-LABEL: sil {{.*}}@{{.*}}20testSlowServingAgain
func testSlowServingAgain(p: SlowServing) async throws {
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK: objc_method {{.*}} $@convention(objc_method) <τ_0_0 where τ_0_0 : SlowServing> (@convention(block) (Optional<NSString>, Optional<NSError>) -> (), τ_0_0) -> ()
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK-NEXT: builtin "willThrow"
let _: String = try await p.tryRequestString()
}
class SlowSwiftServer: NSObject, SlowServing {
// CHECK-LABEL: sil {{.*}} @$s21objc_async_from_swift15SlowSwiftServerC10requestIntSiyYaF
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK-LABEL: sil {{.*}} @${{.*}}10requestInt{{.*}}To :
// CHECK: [[BLOCK_COPY:%.*]] = copy_block %0
// CHECK: [[SELF:%.*]] = copy_value %1
// CHECK: [[CLOSURE_REF:%.*]] = function_ref [[CLOSURE_IMP:@\$.*10requestInt.*U_To]] :
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[CLOSURE_REF]]([[BLOCK_COPY]], [[SELF]])
// CHECK: [[RUN_TASK:%.*]] = function_ref @${{.*}}29_runTaskForBridgedAsyncMethod
// CHECK: apply [[RUN_TASK]]([[CLOSURE]])
// CHECK: sil {{.*}} [[CLOSURE_IMP]]
// CHECK: [[BLOCK_COPY:%.*]] = copy_block %0
// CHECK: [[NATIVE_RESULT:%.*]] = apply{{.*}}@async
// CHECK: [[BLOCK_BORROW:%.*]] = begin_borrow [[BLOCK_COPY]]
// CHECK: apply [[BLOCK_BORROW]]([[NATIVE_RESULT]])
func requestInt() async -> Int { return 0 }
func requestString() async -> String { return "" }
// CHECK-LABEL: sil {{.*}} @$s21objc_async_from_swift15SlowSwiftServerC13requestStringSSyYaF
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK-LABEL: sil {{.*}} @$s21objc_async_from_swift15SlowSwiftServerC16tryRequestStringSSyYaKF
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK-LABEL: sil {{.*}} @${{.*}}16tryRequestString{{.*}}U_To :
// CHECK: [[BLOCK_COPY:%.*]] = copy_block %0
// CHECK: try_apply{{.*}}@async{{.*}}, normal [[NORMAL:bb[0-9]+]], error [[ERROR:bb[0-9]+]]
// CHECK: [[NORMAL]]([[NATIVE_RESULT:%.*]] : @owned $String):
// CHECK: [[BLOCK_BORROW:%.*]] = begin_borrow [[BLOCK_COPY]]
// CHECK: [[NIL_ERROR:%.*]] = enum $Optional<NSError>, #Optional.none
// CHECK: apply [[BLOCK_BORROW]]({{%.*}}, [[NIL_ERROR]])
// CHECK: [[ERROR]]([[NATIVE_RESULT:%.*]] : @owned $Error):
// CHECK: [[BLOCK_BORROW:%.*]] = begin_borrow [[BLOCK_COPY]]
// CHECK: [[NIL_NSSTRING:%.*]] = enum $Optional<NSString>, #Optional.none
// CHECK: apply [[BLOCK_BORROW]]([[NIL_NSSTRING]], {{%.*}})
func tryRequestString() async throws -> String { return "" }
// CHECK-LABEL: sil {{.*}} @$s21objc_async_from_swift15SlowSwiftServerC19requestIntAndStringSi_SStyYaF
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
func requestIntAndString() async -> (Int, String) { return (0, "") }
// CHECK-LABEL: sil {{.*}} @$s21objc_async_from_swift15SlowSwiftServerC22tryRequestIntAndStringSi_SStyYaKF
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
func tryRequestIntAndString() async throws -> (Int, String) { return (0, "") }
}
protocol NativelySlowServing {
func doSomethingSlow(_: String) async -> Int
func findAnswer() async throws -> String
func serverRestart(_: String) async
func findMultipleAnswers() async throws -> (String, Int)
}
extension SlowServer: NativelySlowServing {}
class SlowServerlet: SlowServer {
// CHECK-LABEL: sil{{.*}}13SlowServerlet{{.*}}011doSomethingE8Nullably{{.*}}
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
override func doSomethingSlowNullably(_: String) async -> Int {
return 0
}
// CHECK-LABEL: sil{{.*}}13SlowServerlet{{.*}}18findAnswerNullably{{.*}}
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
override func findAnswerNullably(_ x: String) async -> String {
return x
}
// CHECK-LABEL: sil{{.*}}13SlowServerlet{{.*}}28doSomethingDangerousNullably{{.*}} :
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
override func doSomethingDangerousNullably(_ x: String) async throws -> String {
return x
}
// CHECK-LABEL: sil{{.*}}13SlowServerlet{{.*}}17doSomethingFlaggy{{.*}} :
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK-LABEL: sil{{.*}}13SlowServerlet{{.*}}17doSomethingFlaggy{{.*}}To :
// CHECK: try_apply{{.*}}, normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]({{.*}}):
// CHECK: integer_literal {{.*}}0
// CHECK: [[ERROR_BB]]({{.*}}):
// CHECK: integer_literal {{.*}}1
override func doSomethingFlaggy() async throws -> String {
return ""
}
// CHECK-LABEL: sil{{.*}}13SlowServerlet{{.*}}21doSomethingZeroFlaggy{{.*}} :
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK-LABEL: sil{{.*}}13SlowServerlet{{.*}}21doSomethingZeroFlaggy{{.*}}To :
// CHECK: try_apply{{.*}}, normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]({{.*}}):
// CHECK: integer_literal {{.*}}1
// CHECK: [[ERROR_BB]]({{.*}}):
// CHECK: integer_literal {{.*}}0
override func doSomethingZeroFlaggy() async throws -> String {
return ""
}
// CHECK-LABEL: sil{{.*}}13SlowServerlet{{.*}}28doSomethingMultiResultFlaggy{{.*}} :
// CHECK: [[GENERIC_EXECUTOR:%.*]] = enum $Optional<Builtin.Executor>, #Optional.none
// CHECK: hop_to_executor [[GENERIC_EXECUTOR]] :
// CHECK-LABEL: sil{{.*}}13SlowServerlet{{.*}}28doSomethingMultiResultFlaggy{{.*}}To :
// CHECK: try_apply{{.*}}, normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]({{.*}}):
// CHECK: integer_literal {{.*}}1
// CHECK: [[ERROR_BB]]({{.*}}):
// CHECK: integer_literal {{.*}}0
override func doSomethingMultiResultFlaggy() async throws -> (String, String) {
return ("", "")
}
}
@globalActor actor FooActor {
static var shared = FooActor()
}
@FooActor
class ActorConstrained: NSObject {
// ActorConstrained.foo()
// CHECK-LABEL: sil hidden [ossa] @$s{{.*}}16ActorConstrainedC3foo{{.*}} : $@convention(method) @async (@guaranteed ActorConstrained) -> Bool {
// CHECK: hop_to_executor {{%.*}} : $FooActor
// @objc ActorConstrained.foo()
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s{{.*}}16ActorConstrainedC3foo{{.*}}To : $@convention(objc_method) (@convention(block) (Bool) -> (), ActorConstrained) -> () {
// CHECK: [[ASYNC_CLOS:%[0-9]+]] = function_ref @$s{{.*}}16ActorConstrainedC3foo{{.*}}U_To : $@convention(thin) @Sendable @async (@convention(block) (Bool) -> (), ActorConstrained) -> ()
// CHECK: [[PRIMED_CLOS:%[0-9]+]] = partial_apply [callee_guaranteed] [[ASYNC_CLOS]](
// CHECK: [[TASK_RUNNER:%[0-9]+]] = function_ref @$ss29_runTaskForBridgedAsyncMethodyyyyYaYbcnF
// CHECK: apply [[TASK_RUNNER]]([[PRIMED_CLOS]])
// @objc closure #1 in ActorConstrained.foo()
// CHECK-LABEL: sil shared [thunk] [ossa] @$s{{.*}}16ActorConstrainedC3foo{{.*}}U_To : $@convention(thin) @Sendable @async (@convention(block) (Bool) -> (), ActorConstrained) -> () {
// CHECK: hop_to_executor {{%.*}} : $FooActor
@objc func foo() async -> Bool {
return true
}
}
actor Dril: NSObject {
// Dril.postTo(twitter:)
// CHECK-LABEL: sil hidden [ossa] @$s{{.*}}4DrilC6postTo7twitter{{.*}} : $@convention(method) @async (@guaranteed String, @guaranteed Dril) -> Bool {
// CHECK: hop_to_executor {{%.*}} : $Dril
// @objc Dril.postTo(twitter:)
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s{{.*}}4DrilC6postTo7twitter{{.*}}To : $@convention(objc_method) (NSString, @convention(block) (Bool) -> (), Dril) -> () {
// CHECK: [[ASYNC_CLOS:%[0-9]+]] = function_ref @$s{{.*}}4DrilC6postTo7twitter{{.*}}U_To : $@convention(thin) @Sendable @async (NSString, @convention(block) (Bool) -> (), Dril) -> ()
// CHECK: [[PRIMED_CLOS:%[0-9]+]] = partial_apply [callee_guaranteed] [[ASYNC_CLOS]](
// CHECK: [[TASK_RUNNER:%[0-9]+]] = function_ref @$ss29_runTaskForBridgedAsyncMethodyyyyYaYbcnF
// CHECK: apply [[TASK_RUNNER]]([[PRIMED_CLOS]])
@objc func postTo(twitter msg: String) async -> Bool {
return true
}
// this is known to not emit a hop in the objc thunk (rdar://80972126)
@MainActor
@objc func postFromMainActorTo(twitter msg: String) -> Bool {
return true
}
}
| apache-2.0 | eb678dcec872a3de6d9157574ef64916 | 54.523148 | 252 | 0.590845 | 3.713003 | false | false | false | false |
rsaenzi/MyCurrencyConverterApp | MyCurrencyConverterApp/MyCurrencyConverterApp/App/AccessControllers/AccessControllers.swift | 1 | 1619 | //
// AccessControllers.swift
// MyCurrencyConverterApp
//
// Created by Rigoberto Sáenz Imbacuán on 8/6/16.
// Copyright © 2016 Rigoberto Sáenz Imbacuán [https://www.linkedin.com/in/rsaenzi]. All rights reserved.
//
import UIKit
class AccessControllers {
// --------------------------------------------------
// Members
// --------------------------------------------------
var apiRequest = ApiRequest.getUniqueInstance()!
var apiResponse = ApiResponse.getUniqueInstance()!
var json = JsonParser.getUniqueInstance()!
var log = Logger.getUniqueInstance()!
var valid = Validation.getUniqueInstance()!
// --------------------------------------------------
// Singleton: Unique Instance
// --------------------------------------------------
private static let instance = AccessControllers()
private init() {}
// --------------------------------------------------
// Singleton: One-Time Access
// --------------------------------------------------
private static var instanceDelivered = false
/**
Creates and returns the unique allowed instance of this class
- returns: Unique instance the first time this method is called, nil otherwise
*/
static func getUniqueInstance() -> AccessControllers? {
// If this is the first time this method is called...
if instanceDelivered == false {
// Create and return the instance
instanceDelivered = true
return instance
}
return nil
}
} | mit | 2e87c7a7c1b7aa63b4d395242ef6ce01 | 31.3 | 105 | 0.5 | 5.933824 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Models/StyleViolation.swift | 1 | 921 | public struct StyleViolation: CustomStringConvertible, Equatable {
public let ruleDescription: RuleDescription
public let severity: ViolationSeverity
public let location: Location
public let reason: String
public var description: String {
return XcodeReporter.generateForSingleViolation(self)
}
public init(ruleDescription: RuleDescription, severity: ViolationSeverity = .warning,
location: Location, reason: String? = nil) {
self.ruleDescription = ruleDescription
self.severity = severity
self.location = location
self.reason = reason ?? ruleDescription.description
}
}
// MARK: Equatable
public func == (lhs: StyleViolation, rhs: StyleViolation) -> Bool {
return lhs.ruleDescription == rhs.ruleDescription &&
lhs.location == rhs.location &&
lhs.severity == rhs.severity &&
lhs.reason == rhs.reason
}
| mit | 9de1f7ff3cd3cef6545716131804eaad | 34.423077 | 89 | 0.690554 | 5.116667 | false | false | false | false |
parkera/swift | stdlib/public/Concurrency/AsyncStream.swift | 1 | 9659 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-2021 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 Swift
/// An ordered, asynchronously generated sequence of elements.
///
/// AsyncStream is an interface type to adapt from code producing values to an
/// asynchronous context iterating them. This is intended to be used to allow
/// callback or delegation based APIs to participate with async/await.
///
/// When values are produced from a non async/await source there is a
/// consideration that must be made on behavioral characteristics of how that
/// production of values interacts with the iteration. AsyncStream offers a
/// initialization strategy that provides a method of yielding values into
/// iteration.
///
/// AsyncStream can be initialized with the option to buffer to a given limit.
/// The default value for this limit is Int.max. The buffering is only for
/// values that have yet to be consumed by iteration. Values can be yielded in
/// case to the continuation passed into the build closure. That continuation
/// is Sendable, in that it is intended to be used from concurrent contexts
/// external to the iteration of the AsyncStream.
///
/// A trivial use case producing values from a detached task would work as such:
///
/// let digits = AsyncStream(Int.self) { continuation in
/// detach {
/// for digit in 0..<10 {
/// continuation.yield(digit)
/// }
/// continuation.finish()
/// }
/// }
///
/// for await digit in digits {
/// print(digit)
/// }
///
@available(SwiftStdlib 5.5, *)
public struct AsyncStream<Element> {
public struct Continuation: Sendable {
/// Indication of the type of termination informed to
/// `onTermination`.
public enum Termination {
/// The stream was finished via the `finish` method
case finished
/// The stream was cancelled
case cancelled
}
/// A result of yielding values.
public enum YieldResult {
/// When a value is successfully enqueued, either buffered
/// or immediately consumed to resume a pending call to next
/// and a count of remaining slots available in the buffer at
/// the point in time of yielding. Note: transacting upon the
/// remaining count is only valid when then calls to yield are
/// mutually exclusive.
case enqueued(remaining: Int)
/// Yielding resulted in not buffering an element because the
/// buffer was full. The element is the dropped value.
case dropped(Element)
/// Indication that the continuation was yielded when the
/// stream was already in a terminal state: either by cancel or
/// by finishing.
case terminated
}
/// A strategy that handles exhaustion of a buffer’s capacity.
public enum BufferingPolicy {
case unbounded
/// When the buffer is full, discard the newly received element.
/// This enforces keeping the specified amount of oldest values.
case bufferingOldest(Int)
/// When the buffer is full, discard the oldest element in the buffer.
/// This enforces keeping the specified amount of newest values.
case bufferingNewest(Int)
}
let storage: _Storage
/// Resume the task awaiting the next iteration point by having it return
/// normally from its suspension point or buffer the value if no awaiting
/// next iteration is active.
///
/// - Parameter value: The value to yield from the continuation.
///
/// This can be called more than once and returns to the caller immediately
/// without blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield(_ value: __owned Element) -> YieldResult {
storage.yield(value)
}
/// Resume the task awaiting the next iteration point by having it return
/// nil which signifies the end of the iteration.
///
/// Calling this function more than once is idempotent; i.e. finishing more
/// than once does not alter the state beyond the requirements of
/// AsyncSequence; which claims that all values past a terminal state are
/// nil.
public func finish() {
storage.finish()
}
/// A callback to invoke when iteration of a AsyncStream is cancelled.
///
/// If an `onTermination` callback is set, when iteration of a AsyncStream is
/// cancelled via task cancellation that callback is invoked. The callback
/// is disposed of after any terminal state is reached.
///
/// Cancelling an active iteration will first invoke the onTermination callback
/// and then resume yielding nil. This means that any cleanup state can be
/// emitted accordingly in the cancellation handler
public var onTermination: (@Sendable (Termination) -> Void)? {
get {
return storage.getOnTermination()
}
nonmutating set {
storage.setOnTermination(newValue)
}
}
}
let produce: () async -> Element?
/// Construct a AsyncStream buffering given an Element type.
///
/// - Parameter elementType: The type the AsyncStream will produce.
/// - Parameter maxBufferedElements: The maximum number of elements to
/// hold in the buffer past any checks for continuations being resumed.
/// - Parameter build: The work associated with yielding values to the
/// AsyncStream.
///
/// The maximum number of pending elements limited by dropping the oldest
/// value when a new value comes in if the buffer would exceed the limit
/// placed upon it. By default this limit is unlimited.
///
/// The build closure passes in a Continuation which can be used in
/// concurrent contexts. It is thread safe to send and finish; all calls are
/// to the continuation are serialized, however calling this from multiple
/// concurrent contexts could result in out of order delivery.
public init(
_ elementType: Element.Type = Element.self,
bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded,
_ build: (Continuation) -> Void
) {
let storage: _Storage = .create(limit: limit)
self.init(unfolding: storage.next)
build(Continuation(storage: storage))
}
public init(
unfolding produce: @escaping () async -> Element?,
onCancel: (@Sendable () -> Void)? = nil
) {
let storage: _AsyncStreamCriticalStorage<Optional<() async -> Element?>>
= .create(produce)
self.produce = {
return await Task.withCancellationHandler {
storage.value = nil
onCancel?()
} operation: {
guard let result = await storage.value?() else {
storage.value = nil
return nil
}
return result
}
}
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncStream: AsyncSequence {
/// The asynchronous iterator for iterating a AsyncStream.
///
/// This type is specifically not Sendable. It is not intended to be used
/// from multiple concurrent contexts. Any such case that next is invoked
/// concurrently and contends with another call to next is a programmer error
/// and will fatalError.
public struct Iterator: AsyncIteratorProtocol {
let produce: () async -> Element?
/// The next value from the AsyncStream.
///
/// When next returns nil this signifies the end of the AsyncStream. Any
/// such case that next is invoked concurrently and contends with another
/// call to next is a programmer error and will fatalError.
///
/// If the task this iterator is running in is canceled while next is
/// awaiting a value, this will terminate the AsyncStream and next may return nil
/// immediately (or will return nil on subsequent calls)
public mutating func next() async -> Element? {
await produce()
}
}
/// Construct an iterator.
public func makeAsyncIterator() -> Iterator {
return Iterator(produce: produce)
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncStream.Continuation {
/// Resume the task awaiting the next iteration point by having it return
/// normally from its suspension point or buffer the value if no awaiting
/// next iteration is active.
///
/// - Parameter result: A result to yield from the continuation.
///
/// This can be called more than once and returns to the caller immediately
/// without blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield(
with result: Result<Element, Never>
) -> YieldResult {
switch result {
case .success(let val):
return storage.yield(val)
}
}
/// Resume the task awaiting the next iteration point by having it return
/// normally from its suspension point or buffer the value if no awaiting
/// next iteration is active where the `Element` is `Void`.
///
/// This can be called more than once and returns to the caller immediately
/// without blocking for any awaiting consumption from the iteration.
/// without blocking for any awaiting consuption from the iteration.
@discardableResult
public func yield() -> YieldResult where Element == Void {
return storage.yield(())
}
}
| apache-2.0 | 7ce2c593dd35793c161af2cb7fefad48 | 37.019685 | 85 | 0.671637 | 4.952308 | false | false | false | false |
ilucas/TVShows | Vendor/OpenEmu/Categories/NSImage+DrawingAdditions.swift | 1 | 9840 | /*
Copyright (c) 2015, OpenEmu Team
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the OpenEmu Team nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY OpenEmu Team ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL OpenEmu Team BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Cocoa
class ThreePartImage: NSImage {
/// Array of the three different parts.
var parts: [NSImage?]!
/// Image should be rendered vertically.
var vertical = false
convenience init(imageParts: [NSImage?], vertical: Bool) {
self.init()
self.parts = imageParts
self.vertical = vertical
let start = parts[0]?.size ?? NSZeroSize
let center = parts[1]?.size ?? NSZeroSize
let end = parts[2]?.size ?? NSZeroSize
var size = NSZeroSize
if vertical {
size.width = max(max(start.width, center.width), end.width)
size.height = start.height + center.height + end.height
} else {
size.width = start.width + center.width + end.width
size.height = max(max(start.height, center.height), end.height)
}
self.size = size
}
override func drawInRect(rect: NSRect,
fromRect: NSRect,
operation op: NSCompositingOperation,
fraction delta: CGFloat) {
drawInRect(rect,
fromRect: fromRect,
operation: op,
fraction: delta,
respectFlipped: false,
hints: nil)
}
override func drawInRect(dstSpacePortionRect: NSRect,
fromRect srcSpacePortionRect: NSRect,
operation op: NSCompositingOperation,
fraction requestedAlpha: CGFloat,
respectFlipped respectContextIsFlipped: Bool,
hints: [String : AnyObject]?) {
if (!vertical && dstSpacePortionRect.height != size.height) ||
(vertical && dstSpacePortionRect.width != size.width) {
//DLog("WARNING: Drawing a 3-part image at wrong size.")
}
let startCap = parts[0]
let centerFill = parts[1]
let endCap = parts[2]
NSDrawThreePartImage(dstSpacePortionRect,
startCap,
centerFill,
endCap,
vertical,
op,
requestedAlpha,
NSGraphicsContext.currentContext()?.flipped ?? false)
}
}
class NinePartImage: NSImage {
/// Array of the nine different parts.
var parts: [NSImage?]!
convenience init(imageParts: [NSImage?]) {
self.init()
self.parts = imageParts
let topLeft = parts[0]?.size ?? NSZeroSize
let topCenter = parts[1]?.size ?? NSZeroSize
let topRight = parts[2]?.size ?? NSZeroSize
let leftEdge = parts[3]?.size ?? NSZeroSize
let centerFill = parts[4]?.size ?? NSZeroSize
let rightEdge = parts[5]?.size ?? NSZeroSize
let bottomLeft = parts[6]?.size ?? NSZeroSize
let bottomCenter = parts[7]?.size ?? NSZeroSize
let bottomRight = parts[8]?.size ?? NSZeroSize
let width1 = topLeft.width + topCenter.width + topRight.width
let width2 = leftEdge.width + centerFill.width + rightEdge.width
let width3 = bottomLeft.width + bottomCenter.width + bottomRight.width
let height1 = topLeft.height + leftEdge.height + bottomLeft.height
let height2 = topCenter.height + centerFill.height + bottomCenter.height
let height3 = topRight.height + rightEdge.height + bottomRight.height
size = NSSize(width: max(max(width1, width2), width3),
height: max(max(height1, height2), height3))
}
override func drawInRect(rect: NSRect,
fromRect: NSRect,
operation op: NSCompositingOperation,
fraction delta: CGFloat) {
drawInRect(rect,
fromRect: fromRect,
operation: op,
fraction: delta,
respectFlipped: false,
hints: nil)
}
override func drawInRect(dstSpacePortionRect: NSRect,
fromRect srcSpacePortionRect: NSRect,
operation op: NSCompositingOperation,
fraction requestedAlpha: CGFloat,
respectFlipped respectContextIsFlipped: Bool,
hints: [String : AnyObject]?) {
let topLeftCorner = parts[0]!
let topEdgeFill = parts[1]!
let topRightCorner = parts[2]!
let leftEdgeFill = parts[3]!
let centerFill = parts[4]!
let rightEdgeFill = parts[5]!
let bottomLeftCorner = parts[6]!
let bottomEdgeFill = parts[7]!
let bottomRightCorner = parts[8]!
NSDrawNinePartImage(dstSpacePortionRect,
topLeftCorner,
topEdgeFill,
topRightCorner,
leftEdgeFill,
centerFill,
rightEdgeFill,
bottomLeftCorner,
bottomEdgeFill,
bottomRightCorner,
op,
requestedAlpha,
respectContextIsFlipped && NSGraphicsContext.currentContext()?.flipped ?? false)
}
}
public extension NSImage {
func subImageFromRect(rect: NSRect) -> NSImage {
return NSImage(size: rect.size, flipped: false) { [unowned self] dstRect in
self.drawInRect(dstRect,
fromRect: rect,
operation: .CompositeSourceOver,
fraction: 1)
return true
}
}
func imageFromParts(parts: [AnyObject], vertical: Bool) -> NSImage {
guard !parts.isEmpty else {
return self
}
let count: Int = {
switch parts.count {
case 9..<Int.max:
return 9
case 3..<9:
return 3
case 1..<3:
return 1
default:
return 0
}
}()
let imageParts: [NSImage?] = parts.map { part in
let rect: NSRect
switch part {
case let part as String:
rect = NSRectFromString(part)
case let part as NSValue:
rect = part.rectValue
default:
NSLog("Unable to parse NSRect from part: \(part)")
rect = NSZeroRect
}
if !rect.isEmpty {
var subImageRect = rect
subImageRect.origin.y = size.height - rect.origin.y - rect.height
return self.subImageFromRect(subImageRect)
} else {
return nil
}
}
switch count {
case 9:
return NinePartImage(imageParts: imageParts)
case 3:
return ThreePartImage(imageParts: imageParts, vertical: vertical)
case 1:
fallthrough
default:
return imageParts.last!!
}
}
func ninePartImageWithStretchedRect(rect: NSRect) -> NSImage {
let top = NSRect(x: 0, y: rect.maxY, width: size.width, height: size.height - rect.maxY)
let middle = NSRect(x: 0, y: rect.minY, width: size.width, height: rect.height)
let bottom = NSRect(x: 0, y: 0, width: size.width, height: rect.minY)
let left = NSRect(x: 0, y: 0, width: rect.minX, height: size.height)
let center = NSRect(x: rect.minX, y: 0, width: rect.width, height: size.height)
let right = NSRect(x: rect.maxX, y: 0, width: size.width - rect.maxX, height: size.height)
let parts = [bottom.intersect(left),
bottom.intersect(center),
bottom.intersect(right),
middle.intersect(left),
middle.intersect(center),
middle.intersect(right),
top.intersect(left),
top.intersect(center),
top.intersect(right)]
return imageFromParts(parts.map { String($0) }, vertical: false)
}
}
| gpl-3.0 | 51d4df6511900e109c26715300d890ac | 34.142857 | 99 | 0.553354 | 5.046154 | false | false | false | false |
dexafree/SayCheese | SayCheese/BackgroundApplication.swift | 2 | 8199 | //
// BackgroundApplication.swift
// SayCheese
//
// Created by Arasthel on 15/06/14.
// Copyright (c) 2014 Jorge Martín Espinosa. All rights reserved.
//
import Foundation
class BackgroundApplication: NSObject, ChangeHotKeysDelegate, UploadDelegate {
var statusItem: NSStatusItem?
var deleteLastImageItem: NSMenuItem?
var screenshotWindow: ScreenshotWindow?
var settingsController: PreferencesWindowController?
var showing = false
var flags: NSEventModifierFlags?
var keyCode: UInt16?
var imgurClient: ImgurClient?
override init() {
super.init()
// Configure statusbar
var statusBar = NSStatusBar.systemStatusBar()
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
statusItem!.image = NSImage(named: "menubar_icon_inactive")
statusItem!.toolTip = "SayCheese"
statusItem!.highlightMode = true
// Add menu to statusbar icon
let menu = NSMenu()
menu.autoenablesItems = false
statusItem!.menu = menu
// Add take pic item
var takePicItem = menu.addItemWithTitle("Take screenshot", action: "takePicture:", keyEquivalent:"<")
takePicItem!.keyEquivalentModifierMask = (Int(NSEventModifierFlags.CommandKeyMask.rawValue) | Int(NSEventModifierFlags.ShiftKeyMask.rawValue))
takePicItem!.target = self
var settingsItem = menu.addItemWithTitle("Settings", action: "openSettings:", keyEquivalent:"")
settingsItem!.target = self
deleteLastImageItem = menu.addItemWithTitle("Delete last image", action: "deleteLastImage", keyEquivalent: "")
deleteLastImageItem!.enabled = false
deleteLastImageItem!.target = self
// Add quit app item
var quitAppItem = menu.addItemWithTitle("Quit", action: "quitApp:", keyEquivalent:"")
quitAppItem!.target = self
// Load saved keyCode and flags
_loadDefaults(nil)
// Check if the app has accessibility permissions
if AXIsProcessTrustedWithOptions(nil) == 1 {
let userDefaults = NSUserDefaults.standardUserDefaults()
// If first boot, show info alert
if !userDefaults.boolForKey("tutorial_passed") {
let alert = NSAlert()
alert.addButtonWithTitle("Accept")
alert.messageText = "Hi! Thanks for using SayCheese."
alert.informativeText = "To take a screenshot use ⌘+⇧+<. You can change the hotkeys later in Settings."
alert.alertStyle = NSAlertStyle.InformationalAlertStyle
alert.runModal()
userDefaults.setBool(true, forKey: "tutorial_passed")
userDefaults.synchronize()
}
// If it can access, register listeners
NSEvent.addGlobalMonitorForEventsMatchingMask(NSEventMask.KeyUpMask, handler: takePictureKeyPressed)
NSEvent.addLocalMonitorForEventsMatchingMask(NSEventMask.KeyUpMask, handler: quitScreenWindow)
} else {
// Else, open dialog and close app
let alert = NSAlert()
alert.messageText = "SayCheese needs permission to use the accessibility API."
alert.informativeText = "Once you have permission, please launch the application again."
alert.addButtonWithTitle("Accept")
alert.runModal()
NSWorkspace.sharedWorkspace().openFile("/System/Library/PreferencePanes/Security.prefPane")
NSApplication.sharedApplication().terminate(self)
}
imgurClient = ImgurClient(uploadDelegate: self)
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC));
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
if self.imgurClient!.hasAccount() == true {
self.imgurClient!.authenticate(true)
}
})
}
func openSettings(sender: AnyObject?) {
if settingsController == nil {
settingsController = PreferencesWindowController(windowNibName: "PreferencesWindowController")
settingsController!.imgurClient = imgurClient
imgurClient!.authenticationDoneDelegate = settingsController
}
settingsController!.showWindow(self)
settingsController!.hotKeyTextField.hotKeysDelegate = self
_loadDefaults(settingsController)
}
func _loadDefaults(settingsController: PreferencesWindowController?) {
let defaults = NSUserDefaults.standardUserDefaults()
if (defaults.objectForKey("keyCode") != nil && defaults.objectForKey("flags") != nil) {
var intKeyCode = defaults.integerForKey("keyCode")
var flagsData = defaults.integerForKey("flags")
keyCode = UInt16(intKeyCode)
flags = NSEventModifierFlags(UInt(flagsData))
} else {
// If there aren't custom hotkeys, use Cmd+Alt+<
keyCode = UInt16(50)
flags = NSEventModifierFlags(1179914)
}
if settingsController != nil {
settingsController!.hotKeyTextField.setTextWithKeyCode(Int(keyCode!), andFlags: flags!.rawValue, eventType: nil)
}
}
func changeHotKeysToKeyCode(keyCode: UInt16, flags: UInt) {
self.keyCode = keyCode
self.flags = NSEventModifierFlags(flags)
let defaults = NSUserDefaults.standardUserDefaults()
let intKeyCode = Int(keyCode)
let flagsData = Int(flags)
defaults.setInteger(intKeyCode, forKey: "keyCode")
defaults.setInteger(flagsData, forKey: "flags")
defaults.synchronize()
}
func quitApp(sender: AnyObject!) {
NSApplication.sharedApplication().terminate(sender)
}
func quitScreenWindow(event: NSEvent!) -> NSEvent {
let modifierFlags = event.modifierFlags
if modifierFlags == flags {
if event.keyCode == keyCode {
takePicture(nil)
}
} else if event.keyCode == 53 {
self.screenshotWindow?.close()
}
return event
}
func takePictureKeyPressed(event: NSEvent!) {
let modifierFlags = event.modifierFlags
if (modifierFlags == flags) {
if event.keyCode == keyCode {
takePicture(nil)
}
} else if event.keyCode == 53 {
self.screenshotWindow?.close()
}
}
func uploadStarted(){
statusItem!.image = NSImage(named: "menubar_icon")
}
func uploadFinished(){
statusItem!.image = NSImage(named: "menubar_icon_inactive")
if !deleteLastImageItem!.enabled {
deleteLastImageItem!.enabled = true
}
}
func deleteLastImage(){
imgurClient!.deleteLastImage()
}
func imageDeleted(){
deleteLastImageItem!.enabled = false
}
func takePicture(object: AnyObject?) {
system("screencapture -c -x");
let imageFromClipboard = NSImage(pasteboard: NSPasteboard.generalPasteboard())
let windowRect = NSMakeRect(0, 0, NSScreen.mainScreen()!.frame.size.width, NSScreen.mainScreen()!.frame.size.height)
if screenshotWindow == nil {
screenshotWindow = ScreenshotWindow(window: NSWindow(contentRect: windowRect, styleMask: NSBorderlessWindowMask, backing: NSBackingStoreType.Buffered, defer: false))
screenshotWindow!.imgurClient = imgurClient
}
screenshotWindow!.showWindow(self)
NSApp.activateIgnoringOtherApps(true)
let windowSize = NSSizeFromCGSize(CGSize(width: NSScreen.mainScreen()!.frame.size.width, height: NSScreen.mainScreen()!.frame.size.height))
self.screenshotWindow!.paintImage(imageFromClipboard!, withSize: windowSize)
}
}
| apache-2.0 | 0cfc90e8e697eb1afe7fc9e35c991871 | 35.90991 | 177 | 0.618379 | 5.419312 | false | false | false | false |
1amageek/Bleu | Sample/NotifyViewController.swift | 1 | 2301 | //
// NotifyViewController.swift
// Bleu
//
// Created by 1amageek on 2017/03/14.
// Copyright © 2017年 Stamp inc. All rights reserved.
//
import UIKit
import CoreBluetooth
class NotifyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Bleu.removeAllReceivers()
Bleu.addReceiver(Receiver(communication: NotifyUserID(), get: { [weak self] (manager, request) in
guard let text: String = self?.peripheralTextField.text else {
manager.respond(to: request, withResult: .attributeNotFound)
return
}
request.value = text.data(using: .utf8)
manager.respond(to: request, withResult: .success)
}, post: nil, subscribe: { (peripheralManager, central, characteristic) in
print("subscribe", characteristic.isNotifying, characteristic)
self.characteristic = characteristic as? CBMutableCharacteristic
}, unsubscribe: { (peripheralManager, central, characteristic) in
print("unsubscribe", characteristic.isNotifying)
}))
Bleu.startAdvertising()
}
deinit {
print("deinit notify ViewController")
Bleu.stopAdvertising()
}
var characteristic: CBMutableCharacteristic?
@IBOutlet weak var centralTextField: UITextField!
@IBOutlet weak var peripheralTextField: UITextField!
@IBAction func notify(_ sender: Any) {
let request: Request = Request(communication: NotifyUserID()) { (peripheral, characteristic, error) in
if let error = error {
debugPrint(error)
return
}
guard let data: Data = characteristic.value else {
return
}
self.centralTextField.text = String(data: data, encoding: .utf8)
}
Bleu.send([request]) { completedRequests, error in
print("timeout")
}
}
@IBAction func update(_ sender: Any) {
guard let text: String = self.peripheralTextField.text else {
return
}
let data: Data = text.data(using: .utf8)!
Bleu.updateValue(data, for: self.characteristic!, onSubscribedCentrals: nil)
}
}
| mit | dca22df912015653ea224b15b3c2570b | 31.366197 | 110 | 0.60879 | 4.868644 | false | false | false | false |
brokenhandsio/vapor-oauth | Tests/VaporOAuthTests/Fakes/FakeCodeManager.swift | 1 | 808 | import VaporOAuth
import Foundation
import Node
class FakeCodeManager: CodeManager {
private(set) var usedCodes: [String] = []
var codes: [String: OAuthCode] = [:]
var generatedCode = UUID().uuidString
func getCode(_ code: String) -> OAuthCode? {
return codes[code]
}
func generateCode(userID: Identifier, clientID: String, redirectURI: String, scopes: [String]?) throws -> String {
let code = OAuthCode(codeID: generatedCode, clientID: clientID, redirectURI: redirectURI, userID: userID, expiryDate: Date().addingTimeInterval(60), scopes: scopes)
codes[generatedCode] = code
return generatedCode
}
func codeUsed(_ code: OAuthCode) {
usedCodes.append(code.codeID)
codes.removeValue(forKey: code.codeID)
}
}
| mit | c6e48d092010a8d480575f3dc2a5ff29 | 31.32 | 172 | 0.668317 | 4.275132 | false | false | false | false |
xin-wo/kankan | kankan/Pods/Kingfisher/Sources/KingfisherManager.swift | 5 | 11000 | //
// KingfisherManager.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(OSX)
import AppKit
#else
import UIKit
#endif
public typealias DownloadProgressBlock = ((receivedSize: Int64, totalSize: Int64) -> ())
public typealias CompletionHandler = ((image: Image?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ())
/// RetrieveImageTask represents a task of image retrieving process.
/// It contains an async task of getting image from disk and from network.
public class RetrieveImageTask {
static let emptyTask = RetrieveImageTask()
// If task is canceled before the download task started (which means the `downloadTask` is nil),
// the download task should not begin.
var cancelledBeforeDownloadStarting: Bool = false
/// The disk retrieve task in this image task. Kingfisher will try to look up in cache first. This task represent the cache search task.
public var diskRetrieveTask: RetrieveImageDiskTask?
/// The network retrieve task in this image task.
public var downloadTask: RetrieveImageDownloadTask?
/**
Cancel current task. If this task does not begin or already done, do nothing.
*/
public func cancel() {
// From Xcode 7 beta 6, the `dispatch_block_cancel` will crash at runtime.
// It fixed in Xcode 7.1.
// See https://github.com/onevcat/Kingfisher/issues/99 for more.
if let diskRetrieveTask = diskRetrieveTask {
dispatch_block_cancel(diskRetrieveTask)
}
if let downloadTask = downloadTask {
downloadTask.cancel()
} else {
cancelledBeforeDownloadStarting = true
}
}
}
/// Error domain of Kingfisher
public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
private let instance = KingfisherManager()
/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache.
/// You can use this class to retrieve an image via a specified URL from web or cache.
public class KingfisherManager {
/// Shared manager used by the extensions across Kingfisher.
public class var sharedManager: KingfisherManager {
return instance
}
/// Cache used by this manager
public var cache: ImageCache
/// Downloader used by this manager
public var downloader: ImageDownloader
/**
Default init method
- returns: A Kingfisher manager object with default cache, default downloader, and default prefetcher.
*/
public convenience init() {
self.init(downloader: ImageDownloader.defaultDownloader, cache: ImageCache.defaultCache)
}
init(downloader: ImageDownloader, cache: ImageCache) {
self.downloader = downloader
self.cache = cache
}
/**
Get an image with resource.
If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`.
These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
- parameter completionHandler: Called when the whole retrieving process finished.
- returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
*/
public func retrieveImageWithResource(resource: Resource,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
let task = RetrieveImageTask()
if let optionsInfo = optionsInfo where optionsInfo.forceRefresh {
downloadAndCacheImageWithURL(resource.downloadURL,
forKey: resource.cacheKey,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: optionsInfo)
} else {
tryToRetrieveImageFromCacheForKey(resource.cacheKey,
withURL: resource.downloadURL,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: optionsInfo)
}
return task
}
/**
Get an image with `URL.absoluteString` as the key.
If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
If not found, it will download the image at URL and cache it with `URL.absoluteString` value as its key.
If you need to specify the key other than `URL.absoluteString`, please use resource version of this API with `resource.cacheKey` set to what you want.
These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
- parameter URL: The image URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
- parameter completionHandler: Called when the whole retrieving process finished.
- returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
*/
public func retrieveImageWithURL(URL: NSURL,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return retrieveImageWithResource(Resource(downloadURL: URL), optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler)
}
func downloadAndCacheImageWithURL(URL: NSURL,
forKey key: String,
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
options: KingfisherOptionsInfo?) -> RetrieveImageDownloadTask?
{
let downloader = options?.downloader ?? self.downloader
return downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options,
progressBlock: { receivedSize, totalSize in
progressBlock?(receivedSize: receivedSize, totalSize: totalSize)
},
completionHandler: { image, error, imageURL, originalData in
let targetCache = options?.targetCache ?? self.cache
if let error = error where error.code == KingfisherError.NotModified.rawValue {
// Not modified. Try to find the image from cache.
// (The image should be in cache. It should be guaranteed by the framework users.)
targetCache.retrieveImageForKey(key, options: options, completionHandler: { (cacheImage, cacheType) -> () in
completionHandler?(image: cacheImage, error: nil, cacheType: cacheType, imageURL: URL)
})
return
}
if let image = image, originalData = originalData {
targetCache.storeImage(image, originalData: originalData, forKey: key, toDisk: !(options?.cacheMemoryOnly ?? false), completionHandler: nil)
}
completionHandler?(image: image, error: error, cacheType: .None, imageURL: URL)
})
}
func tryToRetrieveImageFromCacheForKey(key: String,
withURL URL: NSURL,
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
options: KingfisherOptionsInfo?)
{
let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in
// Break retain cycle created inside diskTask closure below
retrieveImageTask.diskRetrieveTask = nil
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
let targetCache = options?.targetCache ?? cache
let diskTask = targetCache.retrieveImageForKey(key, options: options,
completionHandler: { image, cacheType in
if image != nil {
diskTaskCompletionHandler(image: image, error: nil, cacheType:cacheType, imageURL: URL)
} else if let options = options where options.onlyFromCache {
let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.NotCached.rawValue, userInfo: nil)
diskTaskCompletionHandler(image: nil, error: error, cacheType:.None, imageURL: URL)
} else {
self.downloadAndCacheImageWithURL(URL,
forKey: key,
retrieveImageTask: retrieveImageTask,
progressBlock: progressBlock,
completionHandler: diskTaskCompletionHandler,
options: options)
}
}
)
retrieveImageTask.diskRetrieveTask = diskTask
}
}
| mit | f0e06735983466955a121dc6a8a43e14 | 45.808511 | 162 | 0.653182 | 5.678885 | false | false | false | false |
yongju-hong/thrift | lib/swift/Sources/TStreamTransport.swift | 12 | 4375 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 CoreFoundation
#if !swift(>=4.2)
// Swift 3/4 compatibility
fileprivate extension RunLoopMode {
static let `default` = defaultRunLoopMode
}
#endif
#if os(Linux)
/// Currently unavailable in Linux
/// Remove comments and build to fix
/// Currently kConstants for CFSockets don't exist in linux and not all have been moved
/// to property structs yet
#else
// Must inherit NSObject for NSStreamDelegate conformance
public class TStreamTransport : NSObject, TTransport {
public var input: InputStream? = nil
public var output: OutputStream? = nil
public init(inputStream: InputStream?, outputStream: OutputStream?) {
input = inputStream
output = outputStream
}
public convenience init(inputStream: InputStream?) {
self.init(inputStream: inputStream, outputStream: nil)
}
public convenience init(outputStream: OutputStream?) {
self.init(inputStream: nil, outputStream: outputStream)
}
deinit {
close()
}
public func readAll(size: Int) throws -> Data {
guard let input = input else {
throw TTransportError(error: .unknown)
}
var read = Data()
while read.count < size {
var buffer = Array<UInt8>(repeating: 0, count: size - read.count)
let bytesRead = buffer.withUnsafeMutableBufferPointer { bufferPtr in
return input.read(bufferPtr.baseAddress!, maxLength: size - read.count)
}
if bytesRead <= 0 {
throw TTransportError(error: .notOpen)
}
read.append(Data(buffer))
}
return read
}
public func read(size: Int) throws -> Data {
guard let input = input else {
throw TTransportError(error: .unknown)
}
var read = Data()
while read.count < size {
var buffer = Array<UInt8>(repeating: 0, count: size - read.count)
let bytesRead = buffer.withUnsafeMutableBufferPointer {
input.read($0.baseAddress!, maxLength: size - read.count)
}
if bytesRead <= 0 {
break
}
read.append(Data(buffer))
}
return read
}
public func write(data: Data) throws {
guard let output = output else {
throw TTransportError(error: .unknown)
}
var bytesWritten = 0
while bytesWritten < data.count {
bytesWritten = data.withUnsafeBytes { output.write($0.bindMemory(to: UInt8.self).baseAddress!, maxLength: data.count) }
if bytesWritten == -1 {
throw TTransportError(error: .notOpen)
} else if bytesWritten == 0 {
throw TTransportError(error: .endOfFile)
}
}
}
public func flush() throws {
return
}
public func close() {
if input != nil {
// Close and reset inputstream
if let cf: CFReadStream = input {
CFReadStreamSetProperty(cf, .shouldCloseNativeSocket, kCFBooleanTrue)
}
input?.delegate = nil
input?.close()
input?.remove(from: .current, forMode: .default)
input = nil
}
if output != nil {
// Close and reset output stream
if let cf: CFWriteStream = output {
CFWriteStreamSetProperty(cf, .shouldCloseNativeSocket, kCFBooleanTrue)
}
output?.delegate = nil
output?.close()
output?.remove(from: .current, forMode: .default)
output = nil
}
}
}
#endif
| apache-2.0 | ffa49f02735ae91a20b2186b52306898 | 28.761905 | 127 | 0.626057 | 4.689175 | false | false | false | false |
rbryan06/LigaManager | BasketballGM/BasketballGM/DummyPossessionEngine.swift | 1 | 5594 | //
// DummyPossessionEngine.swift
// BasketballGM
//
// Created by Raymond Brion on 23/11/2016.
// Copyright © 2016 Raymond Brion. All rights reserved.
//
import Foundation
class DummyPossessionEngine: PossessionEngine
{
static func runPossession(game: Game, possession: Possession) -> PossessionResult
{
var result: PossessionResult
let playerPair = randomPlayerPair(game: game, possession: possession)
let offensePlayer = playerPair.offense
let defensePlayer = playerPair.defense
print("\(offensePlayer) matched up against \(defensePlayer)")
let playerAction = randomAction(player: offensePlayer)
switch playerAction
{
case .drive:
print("\(offensePlayer) decides to drive")
let dribbleResult = simulateAction(offensiveRating: offensePlayer.dribbleRating,
defensiveRating: defensePlayer.stealRating,
isShot: false)
if (dribbleResult.defenseSuccess)
{
//STEAL!
result = .turnover(.steal)
}
else if (!dribbleResult.offenseSuccess)
{
//STEAL!
result = .turnover(.steal)
}
else
{
let driveResult = simulateAction(offensiveRating: offensePlayer.closeRangeRating,
defensiveRating: defensePlayer.blockRating,
isShot: true)
if (driveResult.defenseSuccess)
{
//BLOCK!
result = .turnover(.block)
}
else if (!dribbleResult.offenseSuccess)
{
//MISSED!
result = .missedFieldGoal
}
else
{
//SCORE!
result = .scored(2)
}
}
case .midRangeShot:
print("\(offensePlayer) decides to shoot a mid-range shot")
let shotResult = simulateAction(offensiveRating: offensePlayer.midRangeRating,
defensiveRating: defensePlayer.blockRating,
isShot: true)
if (shotResult.defenseSuccess)
{
//BLOCK!
result = .turnover(.block)
}
else if (!shotResult.offenseSuccess)
{
//MISSED!
result = .missedFieldGoal
}
else
{
//SCORE!
result = .scored(2)
}
case .threePointShot:
print("\(offensePlayer) decides to shoot a long-range shot")
let shotResult = simulateAction(offensiveRating: offensePlayer.longRangeRating,
defensiveRating: defensePlayer.blockRating,
isShot: true)
if (shotResult.defenseSuccess)
{
//BLOCK!
result = .turnover(.block)
}
else if (!shotResult.offenseSuccess)
{
//MISSED!
result = .missedFieldGoal
}
else
{
//SCORE!
result = .scored(3)
}
case .pass:
print("\(offensePlayer) decides to pass")
let passResult = simulateAction(offensiveRating: offensePlayer.longRangeRating,
defensiveRating: defensePlayer.stealRating,
isShot: false)
if (passResult.defenseSuccess)
{
//STEAL!
result = .turnover(.block)
}
else if (!passResult.offenseSuccess)
{
//TURNOVER! //TODO: Self turnover or steal
result = .turnover(.steal)
}
else
{
//SCORE!
// TODO: Let's make sure the player does not end up again on the next possession
result = runPossession(game: game, possession: possession)
}
}
return result
}
private static func randomPlayerPair(game: Game, possession: Possession) -> (offense: Player, defense: Player)
{
let magicNumber = RandomNumberGenerator.randomInt(max: 4)
if (possession == .home)
{
return (game.homeTeam.onCourtPlayers[magicNumber], game.awayTeam.onCourtPlayers[magicNumber])
}
else
{
return (game.awayTeam.onCourtPlayers[magicNumber], game.homeTeam.onCourtPlayers[magicNumber])
}
}
private static func randomAction(player: Player) -> PossessionAction
{
let magicNumber = RandomNumberGenerator.randomInt(max: 3)
let action: PossessionAction
// TODO base it on the tendencies
switch magicNumber
{
case 0:
action = .drive
case 1:
action = .midRangeShot
case 2:
action = .threePointShot
default:
action = .pass
}
return action
}
private static func simulateAction(offensiveRating: Int, defensiveRating: Int, isShot: Bool) -> (offenseSuccess:Bool, defenseSuccess:Bool)
{
let wildcard = isShot ? Float(0.7) : Float(0.95)
let offensiveChances = ceil(Float(offensiveRating) * wildcard)
let defensiveChances = ceil(Float(defensiveRating) * 0.2) //20% Chances
let randomDefenseShit = Float(RandomNumberGenerator.randomInt(max: 100))
let randomOffenseShit = Float(RandomNumberGenerator.randomInt(max: 100))
// TODO: Let's make it an enum rather than a tuple
if (randomDefenseShit <= defensiveChances)
{
return (false, true)
}
else if (randomOffenseShit <= offensiveChances)
{
return (true, false)
}
else
{
return (false, false)
}
}
}
| mit | e028291f1e024b2d5f29ac09f846d04c | 28.130208 | 140 | 0.567674 | 4.400472 | false | false | false | false |
infinitedg/SwiftDDP | Examples/CoreData/Pods/SwiftDDP/SwiftDDP/DDPClient.swift | 1 | 22321 | //
//
// A DDP Client written in Swift
//
// Copyright (c) 2016 Peter Siegesmund <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// This software uses CryptoSwift: https://github.com/krzyzanowskim/CryptoSwift/
//
import Foundation
import SwiftWebSocket
import XCGLogger
let log = XCGLogger(identifier: "DDP")
public typealias DDPMethodCallback = (result:AnyObject?, error:DDPError?) -> ()
public typealias DDPConnectedCallback = (session:String) -> ()
public typealias DDPCallback = () -> ()
/**
DDPDelegate provides an interface to react to user events
*/
public protocol SwiftDDPDelegate {
func ddpUserDidLogin(user:String)
func ddpUserDidLogout(user:String)
}
/**
DDPClient is the base class for communicating with a server using the DDP protocol
*/
public class DDPClient: NSObject {
// included for storing login id and token
internal let userData = NSUserDefaults.standardUserDefaults()
let background: NSOperationQueue = {
let queue = NSOperationQueue()
queue.name = "DDP Background Data Queue"
queue.qualityOfService = .Background
return queue
}()
// Callbacks execute in the order they're received
internal let callbackQueue: NSOperationQueue = {
let queue = NSOperationQueue()
queue.name = "DDP Callback Queue"
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .UserInitiated
return queue
}()
// Document messages are processed in the order that they are received,
// separately from callbacks
internal let documentQueue: NSOperationQueue = {
let queue = NSOperationQueue()
queue.name = "DDP Background Queue"
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .Background
return queue
}()
// Hearbeats get a special queue so that they're not blocked by
// other operations, causing the connection to close
internal let heartbeat: NSOperationQueue = {
let queue = NSOperationQueue()
queue.name = "DDP Heartbeat Queue"
queue.qualityOfService = .Utility
return queue
}()
let userBackground: NSOperationQueue = {
let queue = NSOperationQueue()
queue.name = "DDP High Priority Background Queue"
queue.qualityOfService = .UserInitiated
return queue
}()
let userMainQueue: NSOperationQueue = {
let queue = NSOperationQueue.mainQueue()
queue.name = "DDP High Priorty Main Queue"
queue.qualityOfService = .UserInitiated
return queue
}()
private var socket:WebSocket!{
didSet{ socket.allowSelfSignedSSL = self.allowSelfSignedSSL }
}
private var server:(ping:NSDate?, pong:NSDate?) = (nil, nil)
internal var resultCallbacks:[String:Completion] = [:]
internal var subCallbacks:[String:Completion] = [:]
internal var unsubCallbacks:[String:Completion] = [:]
public var url:String!
private var subscriptions = [String:(id:String, name:String, ready:Bool)]()
internal var events = DDPEvents()
internal var connection:(ddp:Bool, session:String?) = (false, nil)
public var delegate:SwiftDDPDelegate?
// MARK: Settings
/**
Boolean value that determines whether the
*/
public var allowSelfSignedSSL:Bool = false {
didSet{
guard let currentSocket = socket else { return }
currentSocket.allowSelfSignedSSL = allowSelfSignedSSL
}
}
/**
Sets the log level. The default value is .None.
Possible values: .Verbose, .Debug, .Info, .Warning, .Error, .Severe, .None
*/
public var logLevel = XCGLogger.LogLevel.None {
didSet {
log.setup(logLevel, showLogIdentifier: true, showFunctionName: true, showThreadName: true, showLogLevel: true, showFileNames: false, showLineNumbers: true, showDate: false, writeToFile: nil, fileLogLevel: .None)
}
}
internal override init() {
super.init()
}
/**
Creates a random String id
*/
public func getId() -> String {
let numbers = Set<Character>(["0","1","2","3","4","5","6","7","8","9"])
let uuid = NSUUID().UUIDString.stringByReplacingOccurrencesOfString("-", withString: "")
var id = ""
for character in uuid.characters {
if (!numbers.contains(character) && (round(Float(arc4random()) / Float(UINT32_MAX)) == 1)) {
id += String(character).lowercaseString
} else {
id += String(character)
}
}
return id
}
/**
Makes a DDP connection to the server
- parameter url: The String url to connect to, ex. "wss://todos.meteor.com/websocket"
- parameter callback: A closure that takes a String argument with the value of the websocket session token
*/
public func connect(url:String, callback:DDPConnectedCallback?) {
self.url = url
// capture the thread context in which the function is called
let executionQueue = NSOperationQueue.currentQueue()
socket = WebSocket(url)
//Create backoff
let backOff:DDPExponentialBackoff = DDPExponentialBackoff()
socket.event.close = {code, reason, clean in
//Use backoff to slow reconnection retries
backOff.createBackoff({
log.info("Web socket connection closed with code \(code). Clean: \(clean). \(reason)")
let event = self.socket.event
self.socket = WebSocket(url)
self.socket.event = event
self.ping()
})
}
socket.event.error = events.onWebsocketError
socket.event.open = {
self.heartbeat.addOperationWithBlock() {
// Add a subscription to loginServices to each connection event
let callbackWithServiceConfiguration = { (session:String) in
// let loginServicesSubscriptionCollection = "meteor_accounts_loginServiceConfiguration"
let loginServiceConfiguration = "meteor.loginServiceConfiguration"
self.sub(loginServiceConfiguration, params: nil) // /tools/meteor-services/auth.js line 922
// Resubscribe to existing subs on connection to ensure continuity
self.subscriptions.forEach({ (subscription: (String, (id: String, name: String, ready: Bool))) -> () in
if subscription.1.name != loginServiceConfiguration {
self.sub(subscription.1.id, name: subscription.1.name, params: nil, callback: nil)
}
})
callback?(session: session)
}
var completion = Completion(callback: callbackWithServiceConfiguration)
//Reset the backoff to original values
backOff.reset()
completion.executionQueue = executionQueue
self.events.onConnected = completion
self.sendMessage(["msg":"connect", "version":"1", "support":["1"]])
}
}
socket.event.message = { message in
self.background.addOperationWithBlock() {
if let text = message as? String {
do { try self.ddpMessageHandler(DDPMessage(message: text)) }
catch { log.debug("Message handling error. Raw message: \(text)")}
}
}
}
}
private func ping() {
heartbeat.addOperationWithBlock() {
self.sendMessage(["msg":"ping", "id":self.getId()])
}
}
// Respond to a server ping
private func pong(ping: DDPMessage) {
heartbeat.addOperationWithBlock() {
self.server.ping = NSDate()
var response = ["msg":"pong"]
if let id = ping.id { response["id"] = id }
self.sendMessage(response)
}
}
// Parse DDP messages and dispatch to the appropriate function
internal func ddpMessageHandler(message: DDPMessage) throws {
log.debug("Received message: \(message.json)")
switch message.type {
case .Connected:
self.connection = (true, message.session!)
self.events.onConnected.execute(message.session!)
case .Result: callbackQueue.addOperationWithBlock() {
if let id = message.id, // Message has id
let completion = self.resultCallbacks[id], // There is a callback registered for the message
let result = message.result {
completion.execute(result, error: message.error)
self.resultCallbacks[id] = nil
} else if let id = message.id,
let completion = self.resultCallbacks[id] {
completion.execute(nil, error:message.error)
self.resultCallbacks[id] = nil
}
}
// Principal callbacks for managing data
// Document was added
case .Added: documentQueue.addOperationWithBlock() {
if let collection = message.collection,
let id = message.id {
self.documentWasAdded(collection, id: id, fields: message.fields)
}
}
// Document was changed
case .Changed: documentQueue.addOperationWithBlock() {
if let collection = message.collection,
let id = message.id {
self.documentWasChanged(collection, id: id, fields: message.fields, cleared: message.cleared)
}
}
// Document was removed
case .Removed: documentQueue.addOperationWithBlock() {
if let collection = message.collection,
let id = message.id {
self.documentWasRemoved(collection, id: id)
}
}
// Notifies you when the result of a method changes
case .Updated: documentQueue.addOperationWithBlock() {
if let methods = message.methods {
self.methodWasUpdated(methods)
}
}
// Callbacks for managing subscriptions
case .Ready: documentQueue.addOperationWithBlock() {
if let subs = message.subs {
self.ready(subs)
}
}
// Callback that fires when subscription has been completely removed
//
case .Nosub: documentQueue.addOperationWithBlock() {
if let id = message.id {
self.nosub(id, error: message.error)
}
}
case .Ping: heartbeat.addOperationWithBlock() { self.pong(message) }
case .Pong: heartbeat.addOperationWithBlock() { self.server.pong = NSDate() }
case .Error: background.addOperationWithBlock() {
self.didReceiveErrorMessage(DDPError(json: message.json))
}
default: log.error("Unhandled message: \(message.json)")
}
}
private func sendMessage(message:NSDictionary) {
if let m = message.stringValue() {
self.socket.send(m)
}
}
/**
Executes a method on the server. If a callback is passed, the callback is asynchronously
executed when the method has completed. The callback takes two arguments: result and error. It
the method call is successful, result contains the return value of the method, if any. If the method fails,
error contains information about the error.
- parameter name: The name of the method
- parameter params: An object containing method arguments, if any
- parameter callback: The closure to be executed when the method has been executed
*/
public func method(name: String, params: AnyObject?, callback: DDPMethodCallback?) -> String {
let id = getId()
let message = ["msg":"method", "method":name, "id":id] as NSMutableDictionary
if let p = params { message["params"] = p }
if let completionCallback = callback {
let completion = Completion(callback: completionCallback)
self.resultCallbacks[id] = completion
}
userBackground.addOperationWithBlock() {
self.sendMessage(message)
}
return id
}
//
// Subscribe
//
internal func sub(id: String, name: String, params: [AnyObject]?, callback: DDPCallback?) -> String {
if let completionCallback = callback {
let completion = Completion(callback: completionCallback)
self.subCallbacks[id] = completion
}
self.subscriptions[id] = (id, name, false)
let message = ["msg":"sub", "name":name, "id":id] as NSMutableDictionary
if let p = params { message["params"] = p }
userBackground.addOperationWithBlock() {
self.sendMessage(message)
}
return id
}
/**
Sends a subscription request to the server.
- parameter name: The name of the subscription
- parameter params: An object containing method arguments, if any
*/
public func sub(name: String, params: [AnyObject]?) -> String {
let id = String(name.hashValue)
return sub(id, name: name, params: params, callback:nil)
}
/**
Sends a subscription request to the server. If a callback is passed, the callback asynchronously
runs when the client receives a 'ready' message indicating that the initial subset of documents contained
in the subscription has been sent by the server.
- parameter name: The name of the subscription
- parameter params: An object containing method arguments, if any
- parameter callback: The closure to be executed when the server sends a 'ready' message
*/
public func sub(name:String, params: [AnyObject]?, callback: DDPCallback?) -> String {
let id = String(name.hashValue)
if let subData = findSubscription(name) {
log.info("You are already subscribed to \(name)")
return subData.id
}
return sub(id, name: name, params: params, callback: callback)
}
// Iterates over the Dictionary of subscriptions to find a subscription by name
internal func findSubscription(name:String) -> (id:String, name:String, ready:Bool)? {
for subscription in subscriptions.values {
if (name == subscription.name) {
return subscription
}
}
return nil
}
//
// Unsubscribe
//
/**
Sends an unsubscribe request to the server.
- parameter name: The name of the subscription
*/
public func unsub(name: String) -> String? {
return unsub(name, callback: nil)
}
/**
Sends an unsubscribe request to the server. If a callback is passed, the callback asynchronously
runs when the client receives a 'ready' message indicating that the subset of documents contained
in the subscription have been removed.
- parameter name: The name of the subscription
- parameter callback: The closure to be executed when the server sends a 'ready' message
*/
public func unsub(name: String, callback: DDPCallback?) -> String? {
if let sub = findSubscription(name) {
unsub(withId: sub.id, callback: callback)
background.addOperationWithBlock() { self.sendMessage(["msg":"unsub", "id":sub.id]) }
return sub.id
}
return nil
}
internal func unsub(withId id: String, callback: DDPCallback?) {
if let completionCallback = callback {
let completion = Completion(callback: completionCallback)
unsubCallbacks[id] = completion
}
background.addOperationWithBlock() { self.sendMessage(["msg":"unsub", "id":id]) }
}
//
// Responding to server subscription messages
//
private func ready(subs: [String]) {
for id in subs {
if let completion = subCallbacks[id] {
completion.execute() // Run the callback
subCallbacks[id] = nil // Delete the callback after running
} else { // If there is no callback, execute the method
if var sub = subscriptions[id] {
sub.ready = true
subscriptions[id] = sub
subscriptionIsReady(sub.id, subscriptionName: sub.name)
}
}
}
}
private func nosub(id: String, error: DDPError?) {
if let e = error where (e.isValid == true) {
log.error("\(e)")
} else {
if let completion = unsubCallbacks[id],
let _ = subscriptions[id] {
completion.execute()
unsubCallbacks[id] = nil
subscriptions[id] = nil
} else {
if let subscription = subscriptions[id] {
subscriptions[id] = nil
subscriptionWasRemoved(subscription.id, subscriptionName: subscription.name)
}
}
}
}
//
// public callbacks: should be overridden
//
/**
Executes when a subscription is ready.
- parameter subscriptionId: A String representation of the hash of the subscription name
- parameter subscriptionName: The name of the subscription
*/
public func subscriptionIsReady(subscriptionId: String, subscriptionName:String) {}
/**
Executes when a subscription is removed.
- parameter subscriptionId: A String representation of the hash of the subscription name
- parameter subscriptionName: The name of the subscription
*/
public func subscriptionWasRemoved(subscriptionId:String, subscriptionName:String) {}
/**
Executes when the server has sent a new document.
- parameter collection: The name of the collection that the document belongs to
- parameter id: The document's unique id
- parameter fields: The documents properties
*/
public func documentWasAdded(collection:String, id:String, fields:NSDictionary?) {
if let added = events.onAdded { added(collection: collection, id: id, fields: fields) }
}
/**
Executes when the server sends a message to remove a document.
- parameter collection: The name of the collection that the document belongs to
- parameter id: The document's unique id
*/
public func documentWasRemoved(collection:String, id:String) {
if let removed = events.onRemoved { removed(collection: collection, id: id) }
}
/**
Executes when the server sends a message to update a document.
- parameter collection: The name of the collection that the document belongs to
- parameter id: The document's unique id
- parameter fields: Optional object with EJSON values containing the fields to update
- parameter cleared: Optional array of strings (field names to delete)
*/
public func documentWasChanged(collection:String, id:String, fields:NSDictionary?, cleared:[String]?) {
if let changed = events.onChanged { changed(collection:collection, id:id, fields:fields, cleared:cleared) }
}
/**
Executes when the server sends a message indicating that the result of a method has changed.
- parameter methods: An array of strings (ids passed to 'method', all of whose writes have been reflected in data messages)
*/
public func methodWasUpdated(methods:[String]) {
if let updated = events.onUpdated { updated(methods: methods) }
}
/**
Executes when the client receives an error message from the server. Such a message is used to represent errors raised by the method or subscription, as well as an attempt to subscribe to an unknown subscription or call an unknown method.
- parameter message: A DDPError object with information about the error
*/
public func didReceiveErrorMessage(message: DDPError) {
if let error = events.onError { error(message: message) }
}
}
| mit | bca180be4d4b097e3fd8374844e5a531 | 36.832203 | 242 | 0.59509 | 5.147832 | false | false | false | false |
interstateone/Fresh | Fresh/Common/Models/JSON.swift | 1 | 5817 | //
// JSON.swift
// Fresh
//
// Created by Brandon Evans on 2016-01-10.
// Copyright © 2016 Brandon Evans. All rights reserved.
//
import Foundation
class JSON {
let object: AnyObject
let path: String
init(_ object: AnyObject, path: String = "") {
self.object = object
self.path = path
}
func get<Value: Decodable>(keys: String...) throws -> Value {
return try get(keys: keys)
}
func get<Value: Decodable>(keys: String...) throws -> [Value] {
return try get(keys: keys)
}
func getJSON(keys: String...) throws -> JSON {
return try getJSON(keys: keys)
}
func getJSON(keys keys: [String]) throws -> JSON {
var value: JSON = self
for key in keys {
do {
value = try value.getSourceValue(key)
}
catch let error as JSONError {
throw JSONError(path: value.path + "." + key, underlyingError: error.underlyingError)
}
}
return value
}
func get<Value: Decodable>(keys keys: [String]) throws -> Value {
if keys.count == 0 {
return try Value.decode(self)
}
do {
return try Value.decode(getJSON(keys: keys))
}
catch let error as JSONError {
throw JSONError(path: keys.joinWithSeparator("."), underlyingError: error.underlyingError)
}
}
func get<Value: Decodable>(keys keys: [String]) throws -> [Value] {
if keys.count == 0 {
return try [Value].decode(self)
}
do {
return try [Value].decode(getJSON(keys: keys))
}
catch let error as JSONError {
throw JSONError(path: keys.joinWithSeparator("."), underlyingError: error.underlyingError)
}
}
func decode<Value>(decode: (JSON) throws -> Value) throws -> Value {
do {
return try decode(self)
}
catch let error as JSONError {
throw JSONError(path: path, underlyingError: error.underlyingError)
}
}
private func getSourceValue(key: String) throws -> JSON {
guard let object = object as? [String: AnyObject] else {
throw DecodingError.NotAnObject
}
guard let sourceValue = object[key] else {
throw DecodingError.MissingKey(key: key)
}
return JSON(sourceValue, path: self.path + "." + key)
}
}
/// Decodable allows simple JSON value types to be turned into native Swift primitives or more complex types like URLs or structs and objects
protocol Decodable {
static func decode(json: JSON) throws -> Self
}
extension Decodable {
static func decode(json: JSON) throws -> Self {
if let value = json.object as? Self {
return value
}
throw DecodingError.TypeMismatch(expected: self, actual: json.object.dynamicType)
}
}
extension String: Decodable {}
extension Int: Decodable {}
extension Double: Decodable {}
extension Bool: Decodable {
static func decode(json: JSON) throws -> Bool {
if let boolValue = json.object as? Bool {
return boolValue
}
// SoundCloud sometimes encodes booleans as numbers (0, 1, null)
if let numberValue = json.object as? NSNumber {
return numberValue.boolValue
}
if json.object is NSNull {
return false
}
throw DecodingError.TypeMismatch(expected: self, actual: json.object.dynamicType)
}
}
extension NSURL: Decodable {
static func decode(json: JSON) throws -> Self {
guard let JSONString = json.object as? String else {
throw DecodingError.TypeMismatch(expected: String.self, actual: json.object.dynamicType)
}
// It's not currently possible to handle the failure case of a failable initializer when delegating from a convenience initializer, so this inefficiently works around that
guard NSURLComponents(string: JSONString) != nil else {
throw DecodingError.Undecodable(explanation: "Unable to create a NSURL from the string \"\(JSONString)\"")
}
return self.init(string: JSONString)!
}
}
extension Array where Element: Decodable {
static func decode(json: JSON) throws -> [Element] {
guard let JSONArray = json.object as? [AnyObject] else {
throw DecodingError.TypeMismatch(expected: [AnyObject].self, actual: json.object.dynamicType)
}
return JSONArray.map { try? Element.decode(JSON($0)) }.flatMap { $0 }
}
}
struct JSONError: ErrorType, CustomStringConvertible {
let path: String
let underlyingError: ErrorType
var description: String {
return "JSONError at path: \(path). \(underlyingError)"
}
}
enum DecodingError: ErrorType, CustomStringConvertible {
/// A property was attempted to be accessed on a value that wasn't an object.
case NotAnObject
/// The provided key wasn't found in the object.
case MissingKey(key: String)
/// The expected type wasn't found. Provides both types for examination.
case TypeMismatch(expected: Any.Type, actual: Any.Type)
/// Decoding failed for a reason beyond an unexpected type. An explanation is provided.
case Undecodable(explanation: String)
var description: String {
switch self {
case .NotAnObject: return "A property was attempted to be accessed on a value that wasn't an object."
case .MissingKey(let key): return "The key \"\(key)\" wasn't found in the object."
case .TypeMismatch(let expected, let actual): return "Expected a value of type \(expected) but found one of type \(actual)."
case .Undecodable(let explanation): return "Value was undecodable: \(explanation)."
}
}
} | mit | 1678426cea091c57090c538f7bc0a20c | 33.017544 | 179 | 0.625516 | 4.593997 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 14--A-New-HIG/cosa.playground/Contents.swift | 1 | 262 | //: Playground - noun: a place where people can play
import UIKit
var putoSwift = "ijoputaSwift"
var str:String = "Hello, playground"
var cosa = Array(str.characters)// as Array
var sss = cosa.removeAtIndex(0)
putoSwift += "\(sss)"
print(putoSwift)
| cc0-1.0 | 5ff369789bf07f4d304d946317c74ce3 | 12.1 | 52 | 0.694656 | 3.156627 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Library/CookieRefTagFunctions.swift | 1 | 2234 | import Foundation
import KsApi
private let cookieSeparator = "?"
private let escapedCookieSeparator = "%3F"
// Extracts the ref tag stored in cookies for a particular project. Returns `nil` if no such cookie has
// been previously set.
public func cookieRefTagFor(project: Project) -> RefTag? {
return AppEnvironment.current.cookieStorage.cookies?
.filter { cookie in cookie.name == cookieName(project) }
.first
.map(refTagName(fromCookie:))
.flatMap(RefTag.init(code:))
}
// Derives the name of the ref cookie from the project.
private func cookieName(_ project: Project) -> String {
return "ref_\(project.id)"
}
// Tries to extract the name of the ref tag from a cookie. It has to do double work in case the cookie
// is accidentally encoded with a `%3F` instead of a `?`.
private func refTagName(fromCookie cookie: HTTPCookie) -> String {
return cleanUp(refTagString: cookie.value)
}
// Tries to remove cruft from a ref tag.
public func cleanUp(refTag: RefTag) -> RefTag {
return RefTag(code: cleanUp(refTagString: refTag.stringTag))
}
// Tries to remove cruft from a ref tag string.
private func cleanUp(refTagString: String) -> String {
let secondPass = refTagString.components(separatedBy: escapedCookieSeparator)
if let name = secondPass.first, secondPass.count == 2 {
return String(name)
}
let firstPass = refTagString.components(separatedBy: cookieSeparator)
if let name = firstPass.first, firstPass.count == 2 {
return String(name)
}
return refTagString
}
// Constructs a cookie from a ref tag and project.
public func cookieFrom(refTag: RefTag, project: Project) -> HTTPCookie? {
let timestamp = Int(AppEnvironment.current.scheduler.currentDate.timeIntervalSince1970)
var properties: [HTTPCookiePropertyKey: Any] = [:]
properties[.name] = cookieName(project)
properties[.value] = "\(refTag.stringTag)\(cookieSeparator)\(timestamp)"
properties[.domain] = URL(string: project.urls.web.project)?.host
properties[.path] = URL(string: project.urls.web.project)?.path
properties[.version] = 0
properties[.expires] = AppEnvironment.current.dateType
.init(timeIntervalSince1970: project.dates.deadline).date
return HTTPCookie(properties: properties)
}
| apache-2.0 | 1224eb4b1f81ecf08b97ca0b8733328b | 35.032258 | 103 | 0.741719 | 3.898778 | false | false | false | false |
apple/swift-nio | Tests/NIOHTTP1Tests/HTTPServerPipelineHandlerTest.swift | 1 | 47976 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import NIOCore
import NIOEmbedded
@testable import NIOHTTP1
private final class ReadRecorder: ChannelInboundHandler {
typealias InboundIn = HTTPServerRequestPart
enum Event: Equatable {
case channelRead(InboundIn)
case halfClose
static func ==(lhs: Event, rhs: Event) -> Bool {
switch (lhs, rhs) {
case (.channelRead(let b1), .channelRead(let b2)):
return b1 == b2
case (.halfClose, .halfClose):
return true
default:
return false
}
}
}
public var reads: [Event] = []
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
self.reads.append(.channelRead(self.unwrapInboundIn(data)))
context.fireChannelRead(data)
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
switch event {
case let evt as ChannelEvent where evt == ChannelEvent.inputClosed:
self.reads.append(.halfClose)
default:
context.fireUserInboundEventTriggered(event)
}
}
}
private final class WriteRecorder: ChannelOutboundHandler {
typealias OutboundIn = HTTPServerResponsePart
public var writes: [HTTPServerResponsePart] = []
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
self.writes.append(self.unwrapOutboundIn(data))
context.write(data, promise: promise)
}
}
private final class ReadCountingHandler: ChannelOutboundHandler {
typealias OutboundIn = Any
typealias OutboundOut = Any
public var readCount = 0
func read(context: ChannelHandlerContext) {
self.readCount += 1
context.read()
}
}
private final class QuiesceEventRecorder: ChannelInboundHandler {
typealias InboundIn = Any
typealias InboundOut = Any
public var quiesceCount = 0
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
if event is ChannelShouldQuiesceEvent {
quiesceCount += 1
}
context.fireUserInboundEventTriggered(event)
}
}
class HTTPServerPipelineHandlerTest: XCTestCase {
var channel: EmbeddedChannel! = nil
var requestHead: HTTPRequestHead! = nil
var responseHead: HTTPResponseHead! = nil
fileprivate var readRecorder: ReadRecorder! = nil
fileprivate var readCounter: ReadCountingHandler! = nil
fileprivate var writeRecorder: WriteRecorder! = nil
fileprivate var pipelineHandler: HTTPServerPipelineHandler! = nil
fileprivate var quiesceEventRecorder: QuiesceEventRecorder! = nil
override func setUp() {
self.channel = EmbeddedChannel()
self.readRecorder = ReadRecorder()
self.readCounter = ReadCountingHandler()
self.writeRecorder = WriteRecorder()
self.pipelineHandler = HTTPServerPipelineHandler()
self.quiesceEventRecorder = QuiesceEventRecorder()
XCTAssertNoThrow(try channel.pipeline.addHandler(self.readCounter).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(HTTPResponseEncoder()).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(self.writeRecorder).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(self.pipelineHandler).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(self.readRecorder).wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(self.quiesceEventRecorder).wait())
self.requestHead = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/path")
self.requestHead.headers.add(name: "Host", value: "example.com")
self.responseHead = HTTPResponseHead(version: .http1_1, status: .ok)
self.responseHead.headers.add(name: "Server", value: "SwiftNIO")
// this activates the channel
XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 1)).wait())
}
override func tearDown() {
if let channel = self.channel {
XCTAssertNoThrow(try channel.finish(acceptAlreadyClosed: true))
self.channel = nil
}
self.requestHead = nil
self.responseHead = nil
self.readRecorder = nil
self.readCounter = nil
self.writeRecorder = nil
self.pipelineHandler = nil
self.quiesceEventRecorder = nil
}
func testBasicBufferingBehaviour() throws {
// Send in 3 requests at once.
for _ in 0..<3 {
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
}
// Only one request should have made it through.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
// Unblock by sending a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// Two requests should have made it through now.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
// Now send the last response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// Now all three.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
}
func testReadCallsAreSuppressedWhenPipelining() throws {
// First, call read() and check it makes it through.
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send in a request.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
// Call read again, twice. This should not change the number.
self.channel.read()
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// This should have automatically triggered a call to read(), but only one.
XCTAssertEqual(self.readCounter.readCount, 2)
}
func testReadCallsAreSuppressedWhenUnbufferingIfThereIsStillBufferedData() throws {
// First, call read() and check it makes it through.
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send in two requests.
for _ in 0..<2 {
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
}
// Call read again, twice. This should not change the number.
self.channel.read()
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// This should have not triggered a call to read.
XCTAssertEqual(self.readCounter.readCount, 1)
// Try calling read some more.
self.channel.read()
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Now send in the last response, and see the read go through.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
XCTAssertEqual(self.readCounter.readCount, 2)
}
func testServerCanRespondEarly() throws {
// Send in the first part of a request.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
// This is still moving forward: we can read.
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Now the server sends a response immediately.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// We're still moving forward and can read.
XCTAssertEqual(self.readCounter.readCount, 1)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 2)
// The client response completes.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
// We can still read.
XCTAssertEqual(self.readCounter.readCount, 2)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 3)
}
func testPipelineHandlerWillBufferHalfClose() throws {
// Send in 2 requests at once.
for _ in 0..<3 {
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
}
// Now half-close the connection.
self.channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
// Only one request should have made it through, no half-closure yet.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
// Unblock by sending a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// Two requests should have made it through now.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
// Now send the last response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// Now the half-closure should be delivered.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.halfClose])
}
func testPipelineHandlerWillDeliverHalfCloseEarly() throws {
// Send in a request.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
// Now send a new request but half-close the connection before we get .end.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
self.channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
// Only one request should have made it through, no half-closure yet.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
// Unblock by sending a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// The second request head, followed by the half-close, should have made it through.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.halfClose])
}
func testAReadIsNotIssuedWhenUnbufferingAHalfCloseAfterRequestComplete() throws {
// First, call read() and check it makes it through.
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send in two requests and then half-close.
for _ in 0..<2 {
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
}
self.channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
// Call read again, twice. This should not change the number.
self.channel.read()
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// This should have not triggered a call to read.
XCTAssertEqual(self.readCounter.readCount, 1)
// Now send in the last response. This should also not issue a read.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
XCTAssertEqual(self.readCounter.readCount, 1)
}
func testHalfCloseWhileWaitingForResponseIsPassedAlongIfNothingElseBuffered() throws {
// Send in 2 requests at once.
for _ in 0..<2 {
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
}
// Only one request should have made it through, no half-closure yet.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
// Unblock by sending a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// Two requests should have made it through now. Still no half-closure.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
// Now send the half-closure.
self.channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
// The half-closure should be delivered immediately.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.halfClose])
}
func testRecursiveChannelReadInvocationsDoNotCauseIssues() throws {
func makeRequestHead(uri: String) -> HTTPRequestHead {
var requestHead = HTTPRequestHead(version: .http1_1, method: .GET, uri: uri)
requestHead.headers.add(name: "Host", value: "example.com")
return requestHead
}
class VerifyOrderHandler: ChannelInboundHandler {
typealias InboundIn = HTTPServerRequestPart
typealias OutboundOut = HTTPServerResponsePart
enum NextExpectedMessageType {
case head
case end
}
enum State {
case req1HeadExpected
case req1EndExpected
case req2HeadExpected
case req2EndExpected
case req3HeadExpected
case req3EndExpected
case reqBoomHeadExpected
case reqBoomEndExpected
case done
}
var state: State = .req1HeadExpected
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let req = self.unwrapInboundIn(data)
switch req {
case .head(let head):
// except for "req_1", we always send the .end straight away
var sendEnd = true
switch head.uri {
case "/req_1":
XCTAssertEqual(.req1HeadExpected, self.state)
self.state = .req1EndExpected
// for req_1, we don't send the end straight away to force the others to be buffered
sendEnd = false
case "/req_2":
XCTAssertEqual(.req2HeadExpected, self.state)
self.state = .req2EndExpected
case "/req_3":
XCTAssertEqual(.req3HeadExpected, self.state)
self.state = .req3EndExpected
case "/req_boom":
XCTAssertEqual(.reqBoomHeadExpected, self.state)
self.state = .reqBoomEndExpected
default:
XCTFail("didn't expect \(head)")
}
context.write(self.wrapOutboundOut(.head(HTTPResponseHead(version: .http1_1, status: .ok))), promise: nil)
if sendEnd {
context.write(self.wrapOutboundOut(.end(nil)), promise: nil)
}
context.flush()
case .end:
switch self.state {
case .req1EndExpected:
self.state = .req2HeadExpected
case .req2EndExpected:
self.state = .req3HeadExpected
// this will cause `channelRead` to be recursively called and we need to make sure everything then still works
try! (context.channel as! EmbeddedChannel).writeInbound(HTTPServerRequestPart.head(HTTPRequestHead(version: .http1_1, method: .GET, uri: "/req_boom")))
try! (context.channel as! EmbeddedChannel).writeInbound(HTTPServerRequestPart.end(nil))
case .req3EndExpected:
self.state = .reqBoomHeadExpected
case .reqBoomEndExpected:
self.state = .done
default:
XCTFail("illegal state for end: \(self.state)")
}
case .body:
XCTFail("we don't send any bodies")
}
}
}
let handler = VerifyOrderHandler()
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
for f in 1...3 {
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(makeRequestHead(uri: "/req_\(f)"))))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
}
// now we should have delivered the first request, with the second and third buffered because req_1's .end
// doesn't get sent by the handler (instead we'll do that below)
XCTAssertEqual(.req2HeadExpected, handler.state)
// finish 1st request, that will send through the 2nd one which will then write the 'req_boom' request
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
XCTAssertEqual(.done, handler.state)
}
func testQuiescingEventWhenInitiallyIdle() throws {
XCTAssertTrue(self.channel.isActive)
self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
}
func testQuiescingEventWhenIdleAfterARequest() throws {
// Send through one request.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
// The request should have made it through.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
// Now send a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// No further events should have happened.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
XCTAssertTrue(self.channel.isActive)
self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
}
func testQuiescingInTheMiddleOfARequestNoResponseBitsYet() throws {
// Send through only the head.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead))])
XCTAssertTrue(self.channel.isActive)
self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
XCTAssertTrue(self.channel.isActive)
// Now send a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// still missing the request .end
XCTAssertTrue(self.channel.isActive)
var reqWithConnectionClose: HTTPResponseHead = self.responseHead
reqWithConnectionClose.headers.add(name: "connection", value: "close")
XCTAssertEqual([HTTPServerResponsePart.head(reqWithConnectionClose),
HTTPServerResponsePart.end(nil)],
self.writeRecorder.writes)
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
}
func testQuiescingAfterHavingReceivedRequestButBeforeResponseWasSent() throws {
// Send through a full request.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
XCTAssertTrue(self.channel.isActive)
self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
XCTAssertTrue(self.channel.isActive)
// Now send a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
XCTAssertFalse(self.channel.isActive)
var reqWithConnectionClose: HTTPResponseHead = self.responseHead
reqWithConnectionClose.headers.add(name: "connection", value: "close")
XCTAssertEqual([HTTPServerResponsePart.head(reqWithConnectionClose),
HTTPServerResponsePart.end(nil)],
self.writeRecorder.writes)
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
}
func testQuiescingAfterHavingReceivedRequestAndResponseHeadButNoResponseEndYet() throws {
// Send through a full request.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
// Now send the response .head.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertTrue(self.channel.isActive)
self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
XCTAssertTrue(self.channel.isActive)
// Now send the response .end.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual([HTTPServerResponsePart.head(self.responseHead),
HTTPServerResponsePart.end(nil)],
self.writeRecorder.writes)
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
}
func testQuiescingAfterRequestAndResponseHeadsButBeforeAnyEndsThenRequestEndBeforeResponseEnd() throws {
// Send through a request .head.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead))])
// Now send the response .head.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertTrue(self.channel.isActive)
self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
XCTAssertTrue(self.channel.isActive)
// Request .end.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
XCTAssertTrue(self.channel.isActive)
// Response .end.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual([HTTPServerResponsePart.head(self.responseHead),
HTTPServerResponsePart.end(nil)],
self.writeRecorder.writes)
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
}
func testQuiescingAfterRequestAndResponseHeadsButBeforeAnyEndsThenRequestEndAfterResponseEnd() throws {
// Send through a request .head.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead))])
// Now send the response .head.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertTrue(self.channel.isActive)
self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
XCTAssertTrue(self.channel.isActive)
// Response .end.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
XCTAssertTrue(self.channel.isActive)
// Request .end.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual([HTTPServerResponsePart.head(self.responseHead),
HTTPServerResponsePart.end(nil)],
self.writeRecorder.writes)
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
}
func testQuiescingAfterHavingReceivedOneRequestButBeforeResponseWasSentWithMoreRequestsInTheBuffer() throws {
// Send through a full request and buffer a few more
for _ in 0..<3 {
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
}
// Check that only one request came through
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
XCTAssertTrue(self.channel.isActive)
self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
XCTAssertTrue(self.channel.isActive)
// Now send a response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
XCTAssertFalse(self.channel.isActive)
var reqWithConnectionClose: HTTPResponseHead = self.responseHead
reqWithConnectionClose.headers.add(name: "connection", value: "close")
// check that only one response (with connection: close) came through
XCTAssertEqual([HTTPServerResponsePart.head(reqWithConnectionClose),
HTTPServerResponsePart.end(nil)],
self.writeRecorder.writes)
// Check that only one request came through
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
XCTAssertFalse(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
}
func testParserErrorOnly() throws {
class VerifyOrderHandler: ChannelInboundHandler {
typealias InboundIn = HTTPServerRequestPart
typealias OutboundOut = HTTPServerResponsePart
enum State {
case errorExpected
case done
}
var state: State = .errorExpected
func errorCaught(context: ChannelHandlerContext, error: Error) {
XCTAssertEqual(HTTPParserError.unknown, error as? HTTPParserError)
XCTAssertEqual(.errorExpected, self.state)
self.state = .done
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
XCTFail("no requests expected")
}
}
let handler = VerifyOrderHandler()
XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTPServerProtocolErrorHandler()).wait())
XCTAssertNoThrow(try self.channel.pipeline.addHandler(handler).wait())
self.channel.pipeline.fireErrorCaught(HTTPParserError.unknown)
XCTAssertEqual(.done, handler.state)
}
func testLegitRequestFollowedByParserErrorArrivingWhilstResponseOutstanding() throws {
func makeRequestHead(uri: String) -> HTTPRequestHead {
var requestHead = HTTPRequestHead(version: .http1_1, method: .GET, uri: uri)
requestHead.headers.add(name: "Host", value: "example.com")
return requestHead
}
class VerifyOrderHandler: ChannelInboundHandler {
typealias InboundIn = HTTPServerRequestPart
typealias OutboundOut = HTTPServerResponsePart
enum State {
case reqHeadExpected
case reqEndExpected
case errorExpected
case done
}
var state: State = .reqHeadExpected
func errorCaught(context: ChannelHandlerContext, error: Error) {
XCTAssertEqual(HTTPParserError.closedConnection, error as? HTTPParserError)
XCTAssertEqual(.errorExpected, self.state)
self.state = .done
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch self.unwrapInboundIn(data) {
case .head:
// We dispatch this to the event loop so that it doesn't happen immediately but rather can be
// run from the driving test code whenever it wants by running the EmbeddedEventLoop.
context.eventLoop.execute {
context.writeAndFlush(self.wrapOutboundOut(.head(.init(version: .http1_1,
status: .ok))),
promise: nil)
}
XCTAssertEqual(.reqHeadExpected, self.state)
self.state = .reqEndExpected
case .body:
XCTFail("no body expected")
case .end:
// We dispatch this to the event loop so that it doesn't happen immediately but rather can be
// run from the driving test code whenever it wants by running the EmbeddedEventLoop.
context.eventLoop.execute {
context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
}
XCTAssertEqual(.reqEndExpected, self.state)
self.state = .errorExpected
}
}
}
let handler = VerifyOrderHandler()
XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTPServerProtocolErrorHandler()).wait())
XCTAssertNoThrow(try self.channel.pipeline.addHandler(handler).wait())
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(makeRequestHead(uri: "/one"))))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
self.channel.pipeline.fireErrorCaught(HTTPParserError.closedConnection)
// let's now run the HTTP responses that we enqueued earlier on.
(self.channel.eventLoop as! EmbeddedEventLoop).run()
XCTAssertEqual(.done, handler.state)
}
func testRemovingWithResponseOutstandingTriggersRead() throws {
// First, call read() and check it makes it through.
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send in a request.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
// Call read again, twice. This should not change the number.
self.channel.read()
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Remove the handler.
XCTAssertNoThrow(try channel.pipeline.removeHandler(self.pipelineHandler).wait())
// This should have automatically triggered a call to read(), but only one.
XCTAssertEqual(self.readCounter.readCount, 2)
// Incidentally we shouldn't have fired a quiesce event.
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
}
func testRemovingWithPartialResponseOutstandingTriggersRead() throws {
// First, call read() and check it makes it through.
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send in a request.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
// Call read again, twice. This should not change the number.
self.channel.read()
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send a partial response, which should not trigger a read.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertEqual(self.readCounter.readCount, 1)
// Remove the handler.
XCTAssertNoThrow(try channel.pipeline.removeHandler(self.pipelineHandler).wait())
// This should have automatically triggered a call to read(), but only one.
XCTAssertEqual(self.readCounter.readCount, 2)
// Incidentally we shouldn't have fired a quiesce event.
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
}
func testRemovingWithBufferedRequestForwards() throws {
// Send in a request, and part of another.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
// Only one request should have made it through.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
// Remove the handler.
XCTAssertNoThrow(try channel.pipeline.removeHandler(self.pipelineHandler).wait())
// The extra data should have been forwarded.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil)),
.channelRead(HTTPServerRequestPart.head(self.requestHead))])
}
func testQuiescingInAResponseThenRemovedFiresEventAndReads() throws {
// First, call read() and check it makes it through.
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send through a request and part of another.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
// Only one request should have made it through.
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead)),
.channelRead(HTTPServerRequestPart.end(nil))])
XCTAssertTrue(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
XCTAssertEqual(self.readCounter.readCount, 1)
// Now quiesce the channel.
self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
XCTAssertTrue(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
XCTAssertEqual(self.readCounter.readCount, 1)
// Call read again, twice. This should not lead to reads, as we're waiting for the end.
self.channel.read()
self.channel.read()
XCTAssertTrue(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
XCTAssertEqual(self.readCounter.readCount, 1)
// Now remove the handler.
XCTAssertNoThrow(try channel.pipeline.removeHandler(self.pipelineHandler).wait())
// Channel should be open, but the quiesce event should have fired, and read
// shouldn't have been called as we aren't expecting more data.
XCTAssertTrue(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 1)
XCTAssertEqual(self.readCounter.readCount, 1)
}
func testQuiescingInAResponseThenRemovedFiresEventAndDoesntRead() throws {
// First, call read() and check it makes it through.
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 1)
// Send through just the head.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertEqual(self.readRecorder.reads,
[.channelRead(HTTPServerRequestPart.head(self.requestHead))])
XCTAssertTrue(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
XCTAssertEqual(self.readCounter.readCount, 1)
self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
XCTAssertTrue(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
XCTAssertEqual(self.readCounter.readCount, 1)
// Call read again, twice. This should pass through.
self.channel.read()
self.channel.read()
XCTAssertTrue(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 0)
XCTAssertEqual(self.readCounter.readCount, 3)
// Now remove the handler.
XCTAssertNoThrow(try channel.pipeline.removeHandler(self.pipelineHandler).wait())
// Channel should be open, but the quiesce event should have fired, and read
// shouldn't be (as it passed through.
XCTAssertTrue(self.channel.isActive)
XCTAssertEqual(self.quiesceEventRecorder.quiesceCount, 1)
XCTAssertEqual(self.readCounter.readCount, 3)
}
func testServerCanRespondContinue() throws {
// Send in the first part of a request.
var expect100ContinueHead = self.requestHead!
expect100ContinueHead.headers.replaceOrAdd(name: "expect", value: "100-continue")
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(expect100ContinueHead)))
var continueResponse = self.responseHead
continueResponse!.status = .continue
// Now the server sends a continue response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(continueResponse!)).wait())
// The client response completes.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
// Now the server sends the final response.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
}
func testServerCanRespondProcessingMultipleTimes() throws {
// Send in a request.
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.head(self.requestHead)))
XCTAssertNoThrow(try self.channel.writeInbound(HTTPServerRequestPart.end(nil)))
// We haven't completed our response, so no more reading
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 0)
var processResponse: HTTPResponseHead = self.responseHead!
processResponse.status = .processing
// Now the server sends multiple processing responses.
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(processResponse)).wait())
// We are processing... Reading not allowed
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 0)
// Continue processing...
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(processResponse)).wait())
// We are processing... Reading not allowed
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 0)
// Continue processing...
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(processResponse)).wait())
// We are processing... Reading not allowed
XCTAssertEqual(self.readCounter.readCount, 0)
self.channel.read()
XCTAssertEqual(self.readCounter.readCount, 0)
// Now send the actual response!
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.head(self.responseHead)).wait())
XCTAssertNoThrow(try channel.writeAndFlush(HTTPServerResponsePart.end(nil)).wait())
// This should have triggered a read
XCTAssertEqual(self.readCounter.readCount, 1)
}
}
| apache-2.0 | 62876cd4433f16f6c30e6879f3f812fe | 45.086455 | 175 | 0.664916 | 5.098948 | false | false | false | false |
realm/SwiftLint | Tests/SwiftLintFrameworkTests/ConditionalReturnsOnNewlineRuleTests.swift | 1 | 1289 | @testable import SwiftLintFramework
import XCTest
class ConditionalReturnsOnNewlineRuleTests: XCTestCase {
func testConditionalReturnsOnNewlineWithIfOnly() {
// Test with `if_only` set to true
let nonTriggeringExamples = [
Example("guard true else {\n return true\n}"),
Example("guard true,\n let x = true else {\n return true\n}"),
Example("if true else {\n return true\n}"),
Example("if true,\n let x = true else {\n return true\n}"),
Example("if textField.returnKeyType == .Next {"),
Example("if true { // return }"),
Example("/*if true { */ return }"),
Example("guard true else { return }")
]
let triggeringExamples = [
Example("↓if true { return }"),
Example("↓if true { break } else { return }"),
Example("↓if true { break } else { return }"),
Example("↓if true { return \"YES\" } else { return \"NO\" }")
]
let description = ConditionalReturnsOnNewlineRule.description
.with(triggeringExamples: triggeringExamples)
.with(nonTriggeringExamples: nonTriggeringExamples)
verifyRule(description, ruleConfiguration: ["if_only": true])
}
}
| mit | 4c761e962d7b6423effe88b702622411 | 41.7 | 74 | 0.582358 | 5.043307 | false | true | false | false |
lucas34/SwiftQueue | Sources/SwiftQueue/SwiftQueueLogger.swift | 1 | 3258 | // The MIT License (MIT)
//
// Copyright (c) 2022 Lucas Nelaupe
//
// 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
/// Specify different importance of logging
public enum LogLevel: Int {
/// Basic information about scheduling, running job and completion
case verbose = 1
/// Important but non fatal information
case warning = 2
/// Something went wrong during the scheduling or the execution
case error = 3
}
public extension LogLevel {
/// Describe type of level in human-way
var description: String {
switch self {
case .verbose:
return "verbose"
case .warning:
return "warning"
case .error:
return "error"
}
}
}
/// Protocol to implement for implementing your custom logger
public protocol SwiftQueueLogger {
/// Function called by the library to log an event
func log(_ level: LogLevel, jobId: @autoclosure () -> String?, message: @autoclosure () -> String)
}
/// Class to compute the log and print to the console
open class ConsoleLogger: SwiftQueueLogger {
private let min: LogLevel
/// Define minimum level to log. By default, it will log everything
public init(min: LogLevel = .verbose) {
self.min = min
}
/// Check for log level and create the output message
public final func log(_ level: LogLevel, jobId: @autoclosure () -> String?, message: @autoclosure () -> String) {
if min.rawValue <= level.rawValue {
printComputed(output: "[SwiftQueue] level=\(level.description) jobId=\(jobId() ?? "nil") message=\(message())")
}
}
/// Print with default `print()` function. Can be override to changed the output
open func printComputed(output: String) {
print(output)
}
}
/// Class to ignore all kind of logs
public class NoLogger: SwiftQueueLogger {
/// Singleton instance to avoid multiple instance across all queues
public static let shared = NoLogger()
private init() {}
/// Default implementation that will not log anything
public func log(_ level: LogLevel, jobId: @autoclosure () -> String?, message: @autoclosure () -> String) {
// Nothing to do
}
}
| mit | b1f5c476ddf86115a1c543c565ffbc17 | 32.9375 | 123 | 0.687231 | 4.621277 | false | false | false | false |
kirakik/EZSwiftExtensions | Sources/StringExtensions.swift | 2 | 21340 | //
// StringExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
// swiftlint:disable line_length
// swiftlint:disable trailing_whitespace
#if os(OSX)
import AppKit
#else
import UIKit
#endif
extension String {
/// EZSE: Init string with a base64 encoded string
init ? (base64: String) {
let pad = String(repeating: "=", count: base64.length % 4)
let base64Padded = base64 + pad
if let decodedData = Data(base64Encoded: base64Padded, options: NSData.Base64DecodingOptions(rawValue: 0)), let decodedString = NSString(data: decodedData, encoding: String.Encoding.utf8.rawValue) {
self.init(decodedString)
return
}
return nil
}
/// EZSE: base64 encoded of string
var base64: String {
let plainData = (self as NSString).data(using: String.Encoding.utf8.rawValue)
let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return base64String
}
/// EZSE: Cut string from integerIndex to the end
public subscript(integerIndex: Int) -> Character {
let index = characters.index(startIndex, offsetBy: integerIndex)
return self[index]
}
/// EZSE: Cut string from range
public subscript(integerRange: Range<Int>) -> String {
let start = characters.index(startIndex, offsetBy: integerRange.lowerBound)
let end = characters.index(startIndex, offsetBy: integerRange.upperBound)
return self[start..<end]
}
/// EZSE: Cut string from closedrange
public subscript(integerClosedRange: ClosedRange<Int>) -> String {
return self[integerClosedRange.lowerBound..<(integerClosedRange.upperBound + 1)]
}
/// EZSE: Character count
public var length: Int {
return self.characters.count
}
/// EZSE: Counts number of instances of the input inside String
public func count(_ substring: String) -> Int {
return components(separatedBy: substring).count - 1
}
/// EZSE: Capitalizes first character of String
public mutating func capitalizeFirst() {
guard characters.count > 0 else { return }
self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized)
}
/// EZSE: Capitalizes first character of String, returns a new string
public func capitalizedFirst() -> String {
guard characters.count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized)
return result
}
/// EZSE: Uppercases first 'count' characters of String
public mutating func uppercasePrefix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased())
}
/// EZSE: Uppercases first 'count' characters of String, returns a new string
public func uppercasedPrefix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased())
return result
}
/// EZSE: Uppercases last 'count' characters of String
public mutating func uppercaseSuffix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased())
}
/// EZSE: Uppercases last 'count' characters of String, returns a new string
public func uppercasedSuffix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased())
return result
}
/// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex)
public mutating func uppercase(range: CountableRange<Int>) {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return }
self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to),
with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).uppercased())
}
/// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex), returns new string
public func uppercased(range: CountableRange<Int>) -> String {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return self }
var result = self
result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to),
with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).uppercased())
return result
}
/// EZSE: Lowercases first character of String
public mutating func lowercaseFirst() {
guard characters.count > 0 else { return }
self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased())
}
/// EZSE: Lowercases first character of String, returns a new string
public func lowercasedFirst() -> String {
guard characters.count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased())
return result
}
/// EZSE: Lowercases first 'count' characters of String
public mutating func lowercasePrefix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).lowercased())
}
/// EZSE: Lowercases first 'count' characters of String, returns a new string
public func lowercasedPrefix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex..<characters.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<characters.index(startIndex, offsetBy: min(count, length))]).lowercased())
return result
}
/// EZSE: Lowercases last 'count' characters of String
public mutating func lowercaseSuffix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased())
}
/// EZSE: Lowercases last 'count' characters of String, returns a new string
public func lowercasedSuffix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased())
return result
}
/// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex)
public mutating func lowercase(range: CountableRange<Int>) {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return }
self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to),
with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).lowercased())
}
/// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex), returns new string
public func lowercased(range: CountableRange<Int>) -> String {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return self }
var result = self
result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to),
with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).lowercased())
return result
}
/// EZSE: Counts whitespace & new lines
@available(*, deprecated: 1.6, renamed: "isBlank")
public func isOnlyEmptySpacesAndNewLineCharacters() -> Bool {
let characterSet = CharacterSet.whitespacesAndNewlines
let newText = self.trimmingCharacters(in: characterSet)
return newText.isEmpty
}
/// EZSE: Checks if string is empty or consists only of whitespace and newline characters
public var isBlank: Bool {
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty
}
/// EZSE: Trims white space and new line characters
public mutating func trim() {
self = self.trimmed()
}
/// EZSE: Trims white space and new line characters, returns a new string
public func trimmed() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// EZSE: Position of begining character of substing
public func positionOfSubstring(_ subString: String, caseInsensitive: Bool = false, fromEnd: Bool = false) -> Int {
if subString.isEmpty {
return -1
}
var searchOption = fromEnd ? NSString.CompareOptions.anchored : NSString.CompareOptions.backwards
if caseInsensitive {
searchOption.insert(NSString.CompareOptions.caseInsensitive)
}
if let range = self.range(of: subString, options: searchOption), !range.isEmpty {
return self.characters.distance(from: self.startIndex, to: range.lowerBound)
}
return -1
}
/// EZSE: split string using a spearator string, returns an array of string
public func split(_ separator: String) -> [String] {
return self.components(separatedBy: separator).filter {
!$0.trimmed().isEmpty
}
}
/// EZSE: split string with delimiters, returns an array of string
public func split(_ characters: CharacterSet) -> [String] {
return self.components(separatedBy: characters).filter {
!$0.trimmed().isEmpty
}
}
/// EZSE : Returns count of words in string
public var countofWords: Int {
let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpression.Options())
return regex?.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.length)) ?? 0
}
/// EZSE : Returns count of paragraphs in string
public var countofParagraphs: Int {
let regex = try? NSRegularExpression(pattern: "\\n", options: NSRegularExpression.Options())
let str = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return (regex?.numberOfMatches(in: str, options: NSRegularExpression.MatchingOptions(), range: NSRange(location:0, length: str.length)) ?? -1) + 1
}
internal func rangeFromNSRange(_ nsRange: NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advanced(by: nsRange.location)
let to16 = from16.advanced(by: nsRange.length)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
/// EZSE: Find matches of regular expression in string
public func matchesForRegexInText(_ regex: String!) -> [String] {
let regex = try? NSRegularExpression(pattern: regex, options: [])
let results = regex?.matches(in: self, options: [], range: NSRange(location: 0, length: self.length)) ?? []
return results.map { self.substring(with: self.rangeFromNSRange($0.range)!) }
}
/// EZSE: Checks if String contains Email
public var isEmail: Bool {
let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length))
return (firstMatch?.range.location != NSNotFound && firstMatch?.url?.scheme == "mailto")
}
/// EZSE: Returns if String is a number
public func isNumber() -> Bool {
if let _ = NumberFormatter().number(from: self) {
return true
}
return false
}
/// EZSE: Extracts URLS from String
public var extractURLs: [URL] {
var urls: [URL] = []
let detector: NSDataDetector?
do {
detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
} catch _ as NSError {
detector = nil
}
let text = self
if let detector = detector {
detector.enumerateMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), using: {
(result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let result = result, let url = result.url {
urls.append(url)
}
})
}
return urls
}
/// EZSE: Checking if String contains input with comparing options
public func contains(_ find: String, compareOption: NSString.CompareOptions) -> Bool {
return self.range(of: find, options: compareOption) != nil
}
/// EZSE: Converts String to Int
public func toInt() -> Int? {
if let num = NumberFormatter().number(from: self) {
return num.intValue
} else {
return nil
}
}
/// EZSE: Converts String to Double
public func toDouble() -> Double? {
if let num = NumberFormatter().number(from: self) {
return num.doubleValue
} else {
return nil
}
}
/// EZSE: Converts String to Float
public func toFloat() -> Float? {
if let num = NumberFormatter().number(from: self) {
return num.floatValue
} else {
return nil
}
}
/// EZSE: Converts String to Bool
public func toBool() -> Bool? {
let trimmedString = trimmed().lowercased()
if trimmedString == "true" || trimmedString == "false" {
return (trimmedString as NSString).boolValue
}
return nil
}
///EZSE: Returns the first index of the occurency of the character in String
public func getIndexOf(_ char: Character) -> Int? {
for (index, c) in characters.enumerated() {
if c == char {
return index
}
}
return nil
}
/// EZSE: Converts String to NSString
public var toNSString: NSString { return self as NSString }
#if os(iOS)
///EZSE: Returns bold NSAttributedString
public func bold() -> NSAttributedString {
let boldString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
return boldString
}
#endif
///EZSE: Returns underlined NSAttributedString
public func underline() -> NSAttributedString {
let underlineString = NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue])
return underlineString
}
#if os(iOS)
///EZSE: Returns italic NSAttributedString
public func italic() -> NSAttributedString {
let italicString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
return italicString
}
#endif
#if os(iOS)
///EZSE: Returns hight of rendered string
func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
var attrib: [String: AnyObject] = [NSFontAttributeName: font]
if lineBreakMode != nil {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode!
attrib.updateValue(paragraphStyle, forKey: NSParagraphStyleAttributeName)
}
let size = CGSize(width: width, height: CGFloat(DBL_MAX))
return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height)
}
#endif
///EZSE: Returns NSAttributedString
public func color(_ color: UIColor) -> NSAttributedString {
let colorString = NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color])
return colorString
}
///EZSE: Returns NSAttributedString
public func colorSubString(_ subString: String, color: UIColor) -> NSMutableAttributedString {
var start = 0
var ranges: [NSRange] = []
while true {
let range = (self as NSString).range(of: subString, options: NSString.CompareOptions.literal, range: NSRange(location: start, length: (self as NSString).length - start))
if range.location == NSNotFound {
break
} else {
ranges.append(range)
start = range.location + range.length
}
}
let attrText = NSMutableAttributedString(string: self)
for range in ranges {
attrText.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
}
return attrText
}
/// EZSE: Checks if String contains Emoji
public func includesEmoji() -> Bool {
for i in 0...length {
let c: unichar = (self as NSString).character(at: i)
if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) {
return true
}
}
return false
}
#if os(iOS)
/// EZSE: copy string to pasteboard
public func addToPasteboard() {
let pasteboard = UIPasteboard.general
pasteboard.string = self
}
#endif
// EZSE: URL encode a string (percent encoding special chars)
public func urlEncoded() -> String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
// EZSE: URL encode a string (percent encoding special chars) mutating version
mutating func urlEncode() {
self = urlEncoded()
}
// EZSE: Removes percent encoding from string
public func urlDecoded() -> String {
return removingPercentEncoding ?? self
}
// EZSE : Mutating versin of urlDecoded
mutating func urlDecode() {
self = urlDecoded()
}
}
extension String {
init(_ value: Float, precision: Int) {
let nFormatter = NumberFormatter()
nFormatter.numberStyle = .decimal
nFormatter.maximumFractionDigits = precision
self = nFormatter.string(from: NSNumber(value: value))!
}
init(_ value: Double, precision: Int) {
let nFormatter = NumberFormatter()
nFormatter.numberStyle = .decimal
nFormatter.maximumFractionDigits = precision
self = nFormatter.string(from: NSNumber(value: value))!
}
}
/// EZSE: Pattern matching of strings via defined functions
public func ~=<T> (pattern: ((T) -> Bool), value: T) -> Bool {
return pattern(value)
}
/// EZSE: Can be used in switch-case
public func hasPrefix(_ prefix: String) -> (_ value: String) -> Bool {
return { (value: String) -> Bool in
value.hasPrefix(prefix)
}
}
/// EZSE: Can be used in switch-case
public func hasSuffix(_ suffix: String) -> (_ value: String) -> Bool {
return { (value: String) -> Bool in
value.hasSuffix(suffix)
}
}
| mit | af71baf881d939d92f990a04a4516390 | 40.679688 | 206 | 0.634396 | 4.873259 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/core/TKCrossPlatform.swift | 1 | 410 | //
// TKCrossPlatform.swift
// TripKit
//
// Created by Adrian Schoenig on 27/9/16.
//
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
public typealias TKColor = UIColor
public typealias TKImage = UIImage
public typealias TKFont = UIFont
#elseif os(OSX)
import Cocoa
public typealias TKColor = NSColor
public typealias TKImage = NSImage
public typealias TKFont = NSFont
#endif
| apache-2.0 | b1c0bfb23f6bfc0ea9998986f385b534 | 18.52381 | 42 | 0.717073 | 3.831776 | false | false | false | false |
gb-6k-house/YsSwift | Sources/Peacock/Utils/YSColor.swift | 1 | 2171 | /******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: 说明
** Copyright © 2017年 尧尚信息科技(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import UIKit
@objc public enum YSColor: Int {
case line
case c101 //背景色
case c102 //
case c103 //placehold字体颜色
case c104
case c201 //蓝色
case c301 //
case c401
case c501
case none
//白色主题
fileprivate static let lightTheme: [Int: UIColor] = {
var theme = [Int: UIColor]()
theme[YSColor.line.rawValue] = UIColor(0xA4A4A4FF)
theme[YSColor.c101.rawValue] = UIColor(0xFAFAFAFF)
theme[YSColor.c102.rawValue] = UIColor(0x9D9D9DFF)
theme[YSColor.c103.rawValue] = UIColor(0x8C8C8CFF)
theme[YSColor.c104.rawValue] = UIColor(0xF2F2F2FF)
theme[YSColor.c201.rawValue] = UIColor(0x00051FFF)
theme[YSColor.c301.rawValue] = UIColor(0x0071FDFF)
theme[YSColor.c401.rawValue] = UIColor(0xECECECFF)
theme[YSColor.c501.rawValue] = UIColor(0x898f98FF)
theme[YSColor.none.rawValue] = UIColor(0xFFFFFF00)
return theme
}()
fileprivate static let darkTheme: [Int: UIColor] = {
var theme = [Int: UIColor]()
return theme
}()
fileprivate static var currentTheme = YSColor.lightTheme
public var dark: UIColor {
get {
return YSColor.getColor(self, theme: YSColor.darkTheme)
}
}
public var light: UIColor {
get {
return YSColor.getColor(self, theme: YSColor.lightTheme)
}
}
public var color: UIColor {
get {
return YSColor.getColor(self, theme: YSColor.currentTheme)
}
}
public static func getColor(_ color: YSColor, theme: [Int: UIColor]) -> UIColor {
switch color {
default:
return theme[color.rawValue]!
}
}
}
| mit | 59e6a60d35e08ad1b0010ab895750936 | 21.617021 | 85 | 0.531044 | 3.937037 | false | false | false | false |
kiroskirin/RunSpeedRun | Run Speed Run/AppDelegate.swift | 1 | 6368 | //
// AppDelegate.swift
// Run Speed Run
//
// Created by Kraisorn Soisakhu on 2/5/2560 BE.
// Copyright © 2560 UKS Labs. All rights reserved.
//
import UIKit
import CoreLocation
import WatchConnectivity
import UserNotifications
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
let locationManager = CLLocationManager()
// override init() {
// // Initial Firebase
// FIRApp.configure()
// }
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
let current = UNUserNotificationCenter.current()
current.delegate = self
current.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if !granted {
DispatchQueue.main.async(execute: {
self.window?.rootViewController?.showError(title: "Notification Error", with: "You will unable to receive notification when enter range of speed camera")
})
}
}
current.removeAllDeliveredNotifications()
} else {
// Fallback on earlier versions
application.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .badge, .alert], categories: nil))
application.cancelAllLocalNotifications()
application.applicationIconBadgeNumber = 0
}
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.allowsBackgroundLocationUpdates = true
if CLLocationManager.authorizationStatus() == .authorizedAlways {
self.locationManager.startUpdatingLocation()
}
// WatchKit
if WCSession.isSupported() {
WCSession.default().delegate = self
WCSession.default().activate()
}
FIRApp.configure()
return true
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
application.applicationIconBadgeNumber = 0
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let notification = response.notification
if notification.request.trigger is UNPushNotificationTrigger {
print("-- get remote push --")
} else {
print("-- get local push --")
}
completionHandler()
}
}
extension AppDelegate : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
let application = UIApplication.shared
if application.applicationState == .active {
self.postNotification(name: .enterRegion, at: region)
} else {
if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
content.title = "Speed Camera Area"
content.subtitle = "Entering area of \(region.identifier)"
content.body = "Becareful when drive and slow it down a little bit."
content.sound = UNNotificationSound(named: "warning_detector.aiff")
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: region.identifier, content: content, trigger: trigger)
let current = UNUserNotificationCenter.current()
current.add(request, withCompletionHandler: { error in
if let theError = error {
print(theError.localizedDescription)
}
})
} else {
let localNotification = UILocalNotification()
localNotification.alertTitle = "Speed Camera Area"
localNotification.alertBody = "Entering area \(region.identifier)"
localNotification.soundName = "warning_detector.aiff"
localNotification.applicationIconBadgeNumber = 1
application.presentLocalNotificationNow(localNotification)
}
}
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
self.postNotification(name: .exitRegion, at: region)
}
func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
self.postNotification(name: .errorOnRegion, at: region)
}
func postNotification(name: NSNotification.Name, at region:CLRegion?) {
let info = ["camera_title": region?.identifier ?? "untitled region"]
NotificationCenter.default.post(name: name, object: nil, userInfo: info)
}
}
extension NSNotification.Name {
static let enterRegion = NSNotification.Name(rawValue: "enterRegion")
static let exitRegion = NSNotification.Name(rawValue: "exitRegion")
static let errorOnRegion = NSNotification.Name(rawValue: "errorOnRegion")
}
extension AppDelegate : WCSessionDelegate {
@available(iOS 9.3, *)
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
switch activationState {
case .activated:
do {
try session.updateApplicationContext(["foo": "bar"])
} catch let theError as NSError {
print(theError.localizedDescription)
}
default: break
}
}
func sessionDidBecomeInactive(_ session: WCSession) {
print("In active")
}
func sessionDidDeactivate(_ session: WCSession) {
print("Deactivate")
}
}
| mit | 2172d349c4ab126b925d3bf3547cb56b | 37.355422 | 177 | 0.625569 | 5.889917 | false | false | false | false |
lnakamura/heroku-toolbelt-ios | Toolbelt/RepoDetailViewController.swift | 1 | 4649 | //
// RepoDetailViewController.swift
// Toolbelt
//
// Created by Liane Nakamura on 12/24/15.
// Copyright © 2015 lianenakamura. All rights reserved.
//
import UIKit
import SVProgressHUD
class RepoDetailViewController: UIViewController {
var repo: Repo?
lazy var scrollView: UIScrollView = {
var scrollView = UIScrollView()
scrollView.backgroundColor = UIColor(red:0.26, green:0.0, blue:0.6, alpha:1.0)
return scrollView
}()
lazy var titleLabel: UILabel = {
var titleLabel = UILabel()
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.text = "Restart all dynos"
titleLabel.textColor = UIColor.whiteColor()
return titleLabel
}()
lazy var restartButton: UIButton = {
var restartButton = UIButton()
restartButton.backgroundColor = UIColor.whiteColor()
restartButton.layer.cornerRadius = CGFloat(30)
restartButton.setImage(UIImage(named: "restart.png"), forState: .Normal)
restartButton.imageEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
restartButton.addTarget(self, action: "didTapRestartButton:", forControlEvents: .TouchUpInside)
return restartButton
}()
override func loadView() {
super.loadView()
view.backgroundColor = UIColor(red:0.26, green:0.0, blue:0.6, alpha:1.0)
view.addSubview(scrollView)
scrollView.addSubview(titleLabel)
scrollView.addSubview(restartButton)
setupConstraints()
}
override func viewDidLoad() {
super.viewDidLoad()
title = repo?.name
}
func setupConstraints() {
scrollView.translatesAutoresizingMaskIntoConstraints = false
titleLabel.translatesAutoresizingMaskIntoConstraints = false
restartButton.translatesAutoresizingMaskIntoConstraints = false
let views: [String : UIView] = [
"scrollView": scrollView,
"titleLabel": titleLabel,
"restartButton": restartButton,
]
let metrics: [String : String] = ["": ""]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
scrollView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: scrollView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0))
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[titleLabel]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|->=1-[restartButton(60)]->=1-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-44.0-[restartButton(60)]-15.0-[titleLabel]", options: [.AlignAllCenterX], metrics: metrics, views: views))
}
func didTapRestartButton(sender: UIButton) {
if let appId = repo?.name {
SVProgressHUD.show()
HerokuClient.sharedInstance.restartAllDynos(appId,
success: { [weak self] (response) -> Void in
SVProgressHUD.dismiss()
let alertController = UIAlertController(title: "Dyno Restart All", message: "Dynos successfully restarted.", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(okAction)
self?.presentViewController(alertController, animated: true, completion: nil)
}, failure: { [weak self] (response) -> Void in
SVProgressHUD.dismiss()
print(response)
let alertController = UIAlertController(title: "Dyno Restart All", message: "Dynos were not restarted.", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(okAction)
self?.presentViewController(alertController, animated: true, completion: nil)
}
)
}
}
}
| mit | f464f3a01ca7a93a12622a6a919c2a1b | 44.126214 | 233 | 0.644793 | 5.29385 | false | false | false | false |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/Hakuba/Hakuba/Section.swift | 2 | 5753 | //
// Section.swift
// Example
//
// Created by Le VanNghia on 3/4/16.
//
//
import Foundation
protocol SectionDelegate: class {
func bumpMe(type: SectionBumpType, animation: Animation)
}
public class Section {
weak var delegate: SectionDelegate?
public private(set) var cellmodels: [CellModel] = []
private let bumpTracker = BumpTracker()
internal(set) var index: Int = 0
var changed: Bool {
return bumpTracker.changed
}
public var header: HeaderFooterViewModel? {
didSet {
header?.section = index
header?.type = .Header
}
}
public var footer: HeaderFooterViewModel? {
didSet {
footer?.section = index
footer?.type = .Footer
}
}
public subscript(index: Int) -> CellModel? {
get {
return cellmodels.get(index)
}
}
public init() {
}
public func bump(animation: Animation = .None) -> Self {
let type = bumpTracker.getSectionBumpType(index)
delegate?.bumpMe(type, animation: animation)
bumpTracker.didBump()
return self
}
}
// MARK - Public methods
public extension Section {
// MARK - Reset
func reset() -> Self {
return reset([])
}
func reset(cellmodel: CellModel) -> Self {
return reset([cellmodel])
}
func reset(cellmodels: [CellModel]) -> Self {
setupCellmodels(cellmodels, indexFrom: 0)
self.cellmodels = cellmodels
bumpTracker.didReset()
return self
}
// MARK - Append
func append(cellmodel: CellModel) -> Self {
return append([cellmodel])
}
func append(cellmodels: [CellModel]) -> Self {
return insert(cellmodels, atIndex: count)
}
// MARK - Insert
func insert(cellmodel: CellModel, atIndex index: Int) -> Self {
return insert([cellmodel], atIndex: index)
}
func insert(cellmodels: [CellModel], atIndex index: Int) -> Self {
guard cellmodels.isNotEmpty else {
return self
}
let start = min(count, index)
self.cellmodels.insert(cellmodels, atIndex: start)
let affectedCellmodels = Array(self.cellmodels[start..<count])
setupCellmodels(affectedCellmodels, indexFrom: start)
let indexes = (index..<(index + cellmodels.count)).map { $0 }
bumpTracker.didInsert(indexes)
return self
}
func insertBeforeLast(viewmodel: CellModel) -> Self {
return insertBeforeLast([viewmodel])
}
func insertBeforeLast(viewmodels: [CellModel]) -> Self {
let index = max(cellmodels.count - 1, 0)
return insert(viewmodels, atIndex: index)
}
// MARK - Remove
func remove(index: Int) -> Self {
return remove([index])
}
func remove(range: Range<Int>) -> Self {
let indexes = range.map { $0 }
return remove(indexes)
}
func remove(indexes: [Int]) -> Self {
guard indexes.isNotEmpty else {
return self
}
let sortedIndexes = indexes
.sort(<)
.filter { $0 >= 0 && $0 < self.count }
var remainCellmodels: [CellModel] = []
var i = 0
for j in 0..<count {
if let k = sortedIndexes.get(i) where k == j {
i += 1
} else {
remainCellmodels.append(cellmodels[j])
}
}
cellmodels = remainCellmodels
setupCellmodels(cellmodels, indexFrom: 0)
bumpTracker.didRemove(sortedIndexes)
return self
}
func removeLast() -> Self {
let index = cellmodels.count - 1
guard index >= 0 else {
return self
}
return remove(index)
}
func remove(cellmodel: CellModel) -> Self {
let index = cellmodels.indexOf { return $0 === cellmodel }
guard let i = index else {
return self
}
return remove(i)
}
// MAKR - Move
func move(from: Int, to: Int) -> Self {
cellmodels.move(fromIndex: from, toIndex: to)
setupCellmodels([cellmodels[from]], indexFrom: from)
setupCellmodels([cellmodels[to]], indexFrom: to)
bumpTracker.didMove(from, to: to)
return self
}
}
// MARK - Utilities
public extension Section {
var count: Int {
return cellmodels.count
}
var isEmpty: Bool {
return count == 0
}
var isNotEmpty: Bool {
return !isEmpty
}
var first: CellModel? {
return cellmodels.first
}
var last: CellModel? {
return cellmodels.last
}
}
// MARK - Internal methods
extension Section {
func setup(index: Int, delegate: SectionDelegate) {
self.delegate = delegate
self.index = index
header?.section = index
footer?.section = index
setupCellmodels(cellmodels, indexFrom: 0)
}
func didReloadTableView() {
bumpTracker.didBump()
}
}
// MARK - Private methods
private extension Section {
func setupCellmodels(cellmodels: [CellModel], indexFrom start: Int) {
guard let delegate = delegate as? CellModelDelegate else {
return
}
var start = start
cellmodels.forEach { cellmodel in
let indexPath = NSIndexPath(forRow: start, inSection: index)
cellmodel.setup(indexPath, delegate: delegate)
start += 1
}
}
} | apache-2.0 | b3b3af942aa2cb40213faf44de373849 | 22.295547 | 73 | 0.5498 | 4.491023 | false | false | false | false |
Antidote-for-Tox/Antidote | Antidote/TextViewController.swift | 1 | 2755 | // 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
private struct Constants {
static let Offset = 10.0
static let TitleColorKey = "TITLE_COLOR"
static let TextColorKey = "TEXT_COLOR"
}
class TextViewController: UIViewController {
fileprivate let resourceName: String
fileprivate let backgroundColor: UIColor
fileprivate let titleColor: UIColor
fileprivate let textColor: UIColor
fileprivate var textView: UITextView!
init(resourceName: String, backgroundColor: UIColor, titleColor: UIColor, textColor: UIColor) {
self.resourceName = resourceName
self.backgroundColor = backgroundColor
self.titleColor = titleColor
self.textColor = textColor
super.init(nibName: nil, bundle: nil)
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
loadViewWithBackgroundColor(backgroundColor)
createTextView()
installConstraints()
loadHtml()
}
}
private extension TextViewController {
func createTextView() {
textView = UITextView()
textView.isEditable = false
textView.backgroundColor = .clear
view.addSubview(textView)
}
func installConstraints() {
textView.snp.makeConstraints {
$0.leading.top.equalTo(view).offset(Constants.Offset)
$0.trailing.bottom.equalTo(view).offset(-Constants.Offset)
}
}
func loadHtml() {
do {
struct FakeError: Error {}
guard let htmlFilePath = Bundle.main.path(forResource: resourceName, ofType: "html") else {
throw FakeError()
}
var htmlString = try NSString(contentsOfFile: htmlFilePath, encoding: String.Encoding.utf8.rawValue)
htmlString = htmlString.replacingOccurrences(of: Constants.TitleColorKey, with: titleColor.hexString()) as NSString
htmlString = htmlString.replacingOccurrences(of: Constants.TextColorKey, with: textColor.hexString()) as NSString
guard let data = htmlString.data(using: String.Encoding.unicode.rawValue) else {
throw FakeError()
}
let options = [ NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html ]
try textView.attributedText = NSAttributedString(data: data, options: options, documentAttributes: nil)
}
catch {
handleErrorWithType(.cannotLoadHTML)
}
}
}
| mpl-2.0 | 4cd5e3a8eb33a879ff70daedfa85d389 | 32.597561 | 127 | 0.669691 | 5.101852 | false | false | false | false |
DrewKiino/Atlantis | Atlantis/ViewController.swift | 1 | 5015 | //
// ViewController.swift
// Atlantis
//
// Created by Andrew Aquino on 6/29/16.
// Copyright © 2016 Andrew Aquino. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let string: String = "Proper Text Alignment!"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Atlantis.Configuration.coloredLogLevels = [.Verbose, .Error]
// Atlantis.Configuration.hasColoredLogs = true
// log.verbose("Hello, World")
// log.info("Hello, World")
// log.warning("Hello, World")
// log.debug("Hello, World")
// log.error("Hello, World")
let object = Object()
object.number = 1
object.numberArray = [1, 2]
object.float = 1.0
object.floatArray = [1.0, 2.0]
object.double = 2.0
object.doubleArray = [2.0, 3.0]
object.string = "Hello"
object.stringArray = ["Hello", "World"]
object.bool = true
object.boolArray = [true, false]
object.dictionary = [
"Hello": "World" as AnyObject,
"World": 1000 as AnyObject
]
let object2 = Object()
object2.number = 2
object2.numberArray = [1, 2]
object2.float = 1.0
object2.floatArray = [1.0, 2.0]
object2.double = 2.0
object2.doubleArray = [2.0, 3.0]
object2.string = "Hello"
object2.stringArray = ["Hello", "World"]
let object3 = Object()
object3.number = 3
object3.numberArray = [1, 2]
object3.float = 1.0
object3.floatArray = [1.0, 2.0]
object3.double = 2.0
object3.doubleArray = [2.0, 3.0]
object3.string = "Hello"
object3.stringArray = ["Hello", "World"]
object.object = object2
object.objectArray = [object2, object3]
// log.debug(UIColor())
// log.debug(object2)
// log.debug([object, object2, object3])
// let user2 = User2()
// user2.age = 42
// user2.name = "Bob"
// user2.id = "54321"
// log.debug(User2()) // any
// struct Struct {
// var name: String = "Bob the Builder"
// var skills: [String] = ["structures, buildings"]
// }
//
// let this = Struct()
//
// log.debug(this)
enum This {
case isCool
case isNotCool
}
// let this: This = .IsCool
// let thiz: This = .IsCool
//
// log.debug(This.IsCool)
// log.debug(This.IsNotCool)
// log.debug(this)
// log.debug(thiz)
// log.debug([object, object2, 1, "Hello"])
// log.debug(1)
// log.debug([1])
// log.debug(1.1 as Float)
// log.debug([1.2 as Float])
// log.debug(1.3 as Double)
// log.debug([1.4 as Double])
// log.debug("")
// log.debug([""])
// log.debug(true)
// log.debug([true])
// let dictionary: [String: AnyObject] = [
// "": 1,
// "1": "World"
// ]
// log.debug(dictionary)
// let nothing: String? = nil
// log.debug(nothing)
// let error = NSError(domain: "Hello, World!", code: 404, userInfo: nil)
// let error2 = NSError(domain: "Hello, World!", code: 404, userInfo: ["Hello": "World", "Number": 0])
// let error3 = NSError(domain: "Hello, World!", code: -999, userInfo: nil)
// log.error(error)
// log.error(error2)
// log.error(error3)
// log.verbose(string)
// log.info(string)
// log.warning(string)
// log.debug(string)
// log.error(string)
//
aaaaaaafseaelieshfashif()
faeoifhieahflsfjseifseilfjiasefjlasej()
faeoifhie()
aaaaaaafseaelieshfashif()
faeoifhie()
awfawfawfawfaeoifhieahflsfjseifseilfjiasefjlasej()
aaaaaaafseaelieshfashif()
faeoifhie()
faeoifhie()
faeoifhie()
faeoifhie()
faeoifhie()
faeoifhie()
faeoifhie()
aaaaaaafseaelieshfashif()
faeoifhie()
awfawfawfawfaeoifhieahflsfjseifseilfjiasefjlasej()
aaaaaaafseaelieshfashif()
faeoifhie()
faeoifhie()
faeoifhie()
//
// log.verbose(string)
// log.info(string)
// log.warning(string)
// log.debug(string)
// log.error(string)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func aaaaaaafseaelieshfashif() {
log.info(string)
}
func faeoifhieahflsfjseifseilfjiasefjlasej() {
log.info(string)
}
func awfawfawfawfaeoifhieahflsfjseifseilfjiasefjlasej() {
log.verbose(string)
}
func faeoifhie() {
log.info(string)
}
}
open class Object {
open var number: Int?
open var numberArray: [Int]?
open var string: String?
open var stringArray: [String]?
open var float: Float?
open var floatArray: [Float]?
open var double: Double?
open var doubleArray: [Double]?
open var bool: Bool?
open var boolArray: [Bool]?
open var dictionary: [String: AnyObject]?
open var object: Object?
open var objectArray: [Object]?
}
open class User2 {
open var name: String?
open var id: String?
open var age: Int?
open var user: User2?
}
| mit | 402f02b7c28d3ee934e38e2d7d2a30f9 | 21.790909 | 105 | 0.607898 | 2.961607 | false | false | false | false |
wscqs/FMDemo- | FMDemo/Classes/Module/Record/CutBarWaveView.swift | 1 | 6764 | //
// BarWaveView.swift
// FMDemo
//
// Created by mba on 17/1/19.
// Copyright © 2017年 mbalib. All rights reserved.
//
import UIKit
protocol CutBarWaveViewDelegate: NSObjectProtocol{
func changceTimeLabel(cutBarWaveView: CutBarWaveView, centerX: CGFloat, thumbPointXIndex: Int)
}
class CutBarWaveView: UIView {
weak var delegate: CutBarWaveViewDelegate?
var pointXArray: Array<CGFloat>? {
didSet{
guard pointXArray != nil else {
return
}
setNeedsDisplay()
}
}
var minSecond: CGFloat = 3.0
fileprivate var scrollView = UIScrollView()
fileprivate var thumbBarImage: UIImageView = UIImageView()
fileprivate var playHightView: UIView = UIView()
fileprivate var playBackView: UIView = UIView()
fileprivate var thumbPointXIndex: Int = 0
let kLineWidth: CGFloat = 2.0
let spaceW: CGFloat = 2.0 * 2
var boundsH: CGFloat = 0
var boundsW: CGFloat = 0
var scrollViewContenW: CGFloat = 0
/// 边框及底部颜色
var waveBackgroundColor = UIColor.colorWithHexString("2b95ff") {
didSet {
layer.borderWidth = 3.0
layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).cgColor
backgroundColor = waveBackgroundColor
}
}
/// 声波的颜色.colorWithHexString("2e80d1")
var waveStrokeColor = UIColor.colorWithHexString("2e80d1") {
didSet {
}
}
var waveHightStrokeColor = UIColor.white {
didSet {
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
setupView()
}
override func awakeFromNib() {
super.awakeFromNib()
setupView()
}
func setupView() {
frame = bounds
backgroundColor = waveBackgroundColor
layer.cornerRadius = 3.0
layer.borderWidth = 0.5
layer.borderColor = UIColor.lightGray.cgColor
layer.masksToBounds = true
addSubview(scrollView)
scrollView.addSubview(playBackView)
scrollView.addSubview(playHightView)
scrollView.bounces = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.delegate = self
addSubview(thumbBarImage)
thumbBarImage.image = #imageLiteral(resourceName: "record_volume_control_ico")
thumbBarImage.contentMode = .scaleAspectFit
thumbBarImage.isUserInteractionEnabled = true
let panGes = UIPanGestureRecognizer(target: self, action: #selector(actionPan(sender:)))
thumbBarImage.addGestureRecognizer(panGes)
}
func actionPan(sender: UIPanGestureRecognizer) {
let transPoint = sender.translation(in: self)
let transX = transPoint.x
var newCenter = CGPoint(x: (sender.view?.center.x)! + transX, y: (sender.view?.center.y)!)
// 设置边界
let space = 5 * spaceW
newCenter.x = max(space, newCenter.x)
newCenter.x = min(min(scrollViewContenW - space, boundsW - space), newCenter.x)
sender.view?.center = newCenter
sender.setTranslation(CGPoint.zero, in: self)
updateCutView()
}
override func draw(_ rect: CGRect) {
guard let pointXArray = pointXArray else {
return
}
if pointXArray.count == 0 {return}
let spaceTop: CGFloat = 2
boundsH = self.bounds.size.height - spaceTop
boundsW = self.bounds.size.width
let maxiBarTrackImageW = CGFloat(pointXArray.count) * spaceW
scrollViewContenW = maxiBarTrackImageW
let path = UIBezierPath()
for i in 0 ..< pointXArray.count {
let x = CGFloat(i) * spaceW
path.move(to: CGPoint(x: x, y: boundsH))
path.addLine(to: CGPoint(x: x, y: boundsH * (1 - pointXArray[i])))
}
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = self.waveStrokeColor.cgColor
shapeLayer.path = path.cgPath
shapeLayer.lineWidth = kLineWidth
playBackView.layer.addSublayer(shapeLayer)
let shapeLayer1 = CAShapeLayer()
shapeLayer1.strokeColor = self.waveHightStrokeColor.cgColor
shapeLayer1.path = path.cgPath
shapeLayer1.lineWidth = kLineWidth
playHightView.layer.addSublayer(shapeLayer1)
playHightView.layer.masksToBounds = true
playBackView.frame = CGRect(x: 0, y: 0, width: scrollViewContenW, height: boundsH)
scrollView.contentSize = CGSize(width: maxiBarTrackImageW, height: boundsH)
var cgRect = bounds
cgRect.origin.y = 4
scrollView.frame = cgRect
if scrollViewContenW - boundsW > 0 {
scrollView.contentOffset = CGPoint(x: scrollViewContenW - boundsW, y: 0)
}
initThumbRect()
updateCutView()
}
fileprivate func initThumbRect() {
// // 初始位置 在结束前3秒
// minSecond = 3
var thumbBarX: CGFloat = 0
if scrollViewContenW > boundsW {
thumbBarX = boundsW - spaceW * 5 * minSecond
} else {
thumbBarX = scrollView.contentSize.width - spaceW * 5 * minSecond
}
thumbBarImage.frame = CGRect(x: thumbBarX, y: 2, width: 40, height: bounds.height)
}
fileprivate func updateCutView() {
let point = thumbBarImage.convert(CGPoint(x: -thumbBarImage.bounds.width/2, y: 0), from: scrollView)
thumbPointXIndex = Int(-point.x / spaceW)
playHightView.frame = CGRect(x: 0, y: 0, width: -point.x, height: boundsH)
let transPoint = thumbBarImage.convert(CGPoint(x: 0, y: 0), from: self)
delegate?.changceTimeLabel(cutBarWaveView: self, centerX: -transPoint.x + thumbBarImage.bounds.size.width/2, thumbPointXIndex: thumbPointXIndex)
}
}
// MARK: - open API
extension CutBarWaveView {
/// 传入播放的进度
func setPlayProgress(thumbPointXIndex :Int) {
self.thumbPointXIndex = thumbPointXIndex
playHightView.frame = CGRect(x: 0, y: 0, width: CGFloat(thumbPointXIndex * 4), height: boundsH)
}
}
extension CutBarWaveView: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
updateCutView()
}
}
| apache-2.0 | fbaae3ebc7a0cf9885d6cf864b2833fe | 30.739336 | 152 | 0.612812 | 4.374265 | false | false | false | false |
GenerallyHelpfulSoftware/SVGgh | SVGgh Debugging App/ButtonsDemoViewController.swift | 1 | 2057 | //
// ButtonsDemoViewController.swift
// SVGgh
//
// Created by Glenn Howes on 4/23/16.
// Copyright © 2016 Generally Helpful. All rights reserved.
//
import UIKit
import SVGgh
class ButtonCell: UICollectionViewCell
{
@IBOutlet var button : GHButton!
var colorScheme: ColorScheme?
{
didSet
{
guard let scheme = self.colorScheme else
{
return
}
self.button.schemeNumber = Int(scheme)
}
}
}
class ButtonsDemoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet var collectionView: UICollectionView!
{
didSet
{
collectionView.dataSource = self
collectionView.delegate = self
collectionView.reloadData()
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return kLastColorScheme
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let result = collectionView.dequeueReusableCell(withReuseIdentifier: "ButtonCell", for: indexPath as IndexPath) as! ButtonCell
result.colorScheme = ColorScheme(indexPath.item)
return result
}
@objc func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
let baseSize = CGFloat(floor(fmin(self.view.bounds.width, self.view.bounds.height)/5.0))
return CGSize(width: baseSize, height: baseSize)
}
}
| mit | db69a6746752ed434342f47c53060742 | 26.052632 | 134 | 0.636673 | 5.711111 | false | false | false | false |
practicalswift/swift | test/IRGen/protocol_metadata.swift | 6 | 5608 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s -DINT=i%target-ptrsize
// REQUIRES: CPU=x86_64
protocol A { func a() }
protocol B { func b() }
protocol C : class { func c() }
@objc protocol O { func o() }
@objc protocol OPT {
@objc optional func opt()
@objc optional static func static_opt()
@objc optional var prop: O { get }
@objc optional subscript (x: O) -> O { get }
}
protocol AB : A, B { func ab() }
protocol ABO : A, B, O { func abo() }
// -- @objc protocol O uses ObjC symbol mangling and layout
// CHECK-LABEL: @_PROTOCOL__TtP17protocol_metadata1O_ = private constant
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS__TtP17protocol_metadata1O_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata1O_
// CHECK-SAME: }
// CHECK: [[A_NAME:@.*]] = private constant [2 x i8] c"A\00"
// CHECK-LABEL: @"$s17protocol_metadata1AMp" = hidden constant
// CHECK-SAME: i32 65603,
// CHECK-SAME: @"$s17protocol_metadataMXM"
// CHECK-SAME: [[A_NAME]]
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 0,
// CHECK-SAME: }
// CHECK: [[B_NAME:@.*]] = private constant [2 x i8] c"B\00"
// CHECK-LABEL: @"$s17protocol_metadata1BMp" = hidden constant
// CHECK-SAME: i32 65603,
// CHECK-SAME: @"$s17protocol_metadataMXM"
// CHECK-SAME: i32 0,
// CHECK-SAME: [[B_NAME]]
// CHECK-SAME: i32 1,
// CHECK: }
// CHECK: [[C_NAME:@.*]] = private constant [2 x i8] c"C\00"
// CHECK-LABEL: @"$s17protocol_metadata1CMp" = hidden constant
// CHECK-SAME: i32 67,
// CHECK-SAME: @"$s17protocol_metadataMXM"
// CHECK-SAME: [[C_NAME]]
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 0,
// AnyObject layout constraint
// CHECK-SAME: i32 31,
// CHECK-SAME: @"symbolic x"
// CHECK-SAME: i32 0
// CHECK-SAME: }
// -- @objc protocol OPT uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata3OPT_ = private constant { {{.*}} i32, [4 x i8*]*, i8*, i8* } {
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS_OPT__TtP17protocol_metadata3OPT_,
// CHECK-SAME: @_PROTOCOL_CLASS_METHODS_OPT__TtP17protocol_metadata3OPT_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata3OPT_
// CHECK-SAME: }
// -- inheritance lists for refined protocols
// CHECK: [[AB_NAME:@.*]] = private constant [3 x i8] c"AB\00"
// CHECK: @"$s17protocol_metadata2ABMp" = hidden constant
// CHECK-SAME: i32 65603,
// CHECK-SAME: @"$s17protocol_metadataMXM"
// CHECK-SAME: [[AB_NAME]]
// CHECK-SAME: i32 2, i32 3, i32 0
// Inheritance from A
// CHECK-SAME: i32 128,
// CHECK-SAME: @"symbolic x"
// CHECK-SAME: @"$s17protocol_metadata1AMp"
// Inheritance from B
// CHECK-SAME: i32 128,
// CHECK-SAME: @"symbolic x"
// CHECK-SAME: @"$s17protocol_metadata1BMp"
// CHECK: }
protocol Comprehensive {
associatedtype Assoc : A
init()
func instanceMethod()
static func staticMethod()
var instance: Assoc { get set }
static var global: Assoc { get set }
}
// CHECK: [[COMPREHENSIVE_ASSOC_NAME:@.*]] = private constant [6 x i8] c"Assoc\00"
// CHECK: @"$s17protocol_metadata13ComprehensiveMp" = hidden constant
// CHECK-SAME: i32 65603
// CHECK-SAME: i32 1
// CHECK-SAME: i32 11,
// CHECK-SAME: i32 trunc
// CHECK-SAME: [6 x i8]* [[COMPREHENSIVE_ASSOC_NAME]]
// CHECK-SAME: %swift.protocol_requirement { i32 8, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 7, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 2, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 17, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 1, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 19, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 20, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 22, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 3, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 4, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 6, i32 0 }
func reify_metadata<T>(_ x: T) {}
// CHECK: define hidden swiftcc void @"$s17protocol_metadata0A6_types{{[_0-9a-zA-Z]*}}F"
func protocol_types(_ a: A,
abc: A & B & C,
abco: A & B & C & O) {
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$s17protocol_metadata1AMp" to [[INT]])
// CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 true, %swift.type* null, i64 1, [[INT]]* {{%.*}})
reify_metadata(a)
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$s17protocol_metadata1AMp"
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$s17protocol_metadata1BMp"
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$s17protocol_metadata1CMp"
// CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 3, [[INT]]* {{%.*}})
reify_metadata(abc)
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$s17protocol_metadata1AMp"
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$s17protocol_metadata1BMp"
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$s17protocol_metadata1CMp"
// CHECK: [[O_REF:%.*]] = load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP17protocol_metadata1O_"
// CHECK: [[O_REF_INT:%.*]] = ptrtoint i8* [[O_REF]] to [[INT]]
// CHECK: [[O_REF_DESCRIPTOR:%.*]] = or [[INT]] [[O_REF_INT]], 1
// CHECK: store [[INT]] [[O_REF_DESCRIPTOR]]
// CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 4, [[INT]]* {{%.*}})
reify_metadata(abco)
}
| apache-2.0 | 13919ce50caeb9a9460adf5542eeea6c | 37.675862 | 162 | 0.635164 | 3.010199 | false | false | false | false |
legendecas/Rocket.Chat.iOS | Rocket.Chat.Shared/Views/Chat/ChatTitleView.swift | 1 | 1680 | //
// ChatTitleView.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 10/10/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
final class ChatTitleView: UIView {
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var labelTitle: UILabel! {
didSet {
labelTitle.textColor = .RCDarkGray()
}
}
@IBOutlet weak var imageArrowDown: UIImageView! {
didSet {
imageArrowDown.image = imageArrowDown.image?.imageWithTint(.RCGray())
}
}
var subscription: Subscription! {
didSet {
labelTitle.text = subscription.displayName()
switch subscription.type {
case .channel:
icon.image = UIImage(named: "Hashtag", in: Bundle.rocketChat, compatibleWith: nil)?.imageWithTint(.RCGray())
case .directMessage:
var color = UIColor.RCGray()
if let user = subscription.directMessageUser {
color = { _ -> UIColor in
switch user.status {
case .online: return .RCOnline()
case .offline: return .RCGray()
case .away: return .RCAway()
case .busy: return .RCBusy()
}
}()
}
icon.image = UIImage(named: "Mention", in: Bundle.rocketChat, compatibleWith: nil)?.imageWithTint(color)
case .group, .livechat:
icon.image = UIImage(named: "Lock", in: Bundle.rocketChat, compatibleWith: nil)?.imageWithTint(.RCGray())
}
}
}
}
| mit | a030e0e69b6c959c711f1f289e21908c | 30.092593 | 124 | 0.531864 | 4.67688 | false | false | false | false |
google/eddystone | tools/gatt-config/ios/Beaconfig/Beaconfig/UserLoginViewController.swift | 2 | 9219 | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
///
/// Manages the view where the user signs in with Google and chooses a project.
///
class UserLoginViewController: UIViewController, GIDSignInUIDelegate,
UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var userInfoView: UIView!
@IBOutlet weak var signInButton: GIDSignInButton!
@IBOutlet weak var signOutButton: UIButton!
@IBOutlet weak var statusText: UILabel!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var emailTextView: UILabel!
@IBOutlet weak var projectIDPickerView: UIPickerView!
@IBOutlet weak var projectSelectionDescriptionView: UILabel!
var viewToDisable: UIView?
var selectHolder: UIView?
var projectsArray: NSMutableArray = ["Not Selected"]
var userInfo: UserInformation!
var additionalScopes = ["https://www.googleapis.com/auth/userlocation.beacon.registry",
"https://www.googleapis.com/auth/cloud-platform"]
override func viewDidLoad() {
super.viewDidLoad()
GIDSignIn.sharedInstance().uiDelegate = self
projectIDPickerView.delegate = self
projectIDPickerView.dataSource = self
projectIDPickerView.showsSelectionIndicator = true
projectSelectionDescriptionView.text = "Configuration of Eddystone EID beacons requires you\n" +
"to select a Google Cloud project."
CustomViews.addShadow(userInfoView)
projectSelectionDescriptionView.backgroundColor = kLightGrayColor
CustomViews.addShadow(projectSelectionDescriptionView)
///
/// We need to manually add scopes in order to do the beacon registrations and to use the
/// clout platform. We only do this if the user is not signed in.
///
if !userInfo.userCurrentlySignedIn {
for scope in additionalScopes {
GIDSignIn.sharedInstance().scopes.append(scope)
}
}
reloadDataInUIElements()
NSNotificationCenter.defaultCenter()
.addObserver(self,
selector: #selector(UserLoginViewController.receiveToggleAuthUINotification(_:)),
name: "ToggleAuthUINotification",
object: nil)
signOutButton.setTitle("Sign Out", forState: UIControlState.Normal)
signOutButton.setTitleColor(kGreenColor, forState: UIControlState.Normal)
signOutButton.addTarget(self,
action: #selector(UserLoginViewController.didTapSignOut),
forControlEvents: .TouchUpInside)
}
func prepareForUse(userInfo: UserInformation) {
self.userInfo = userInfo
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return projectsArray.count
}
///
/// When the user selects a project, immediately save it to be used in EID configuration
/// and remove all the notifications that tell the user to select a project.
///
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
EIDConfiguration.projectID = (userInfo.projectsArray.objectAtIndex(row) as! String)
userInfo.selectedProjectIndex = row
if let selectView = self.selectHolder {
selectView.removeFromSuperview()
}
}
func pickerView(pickerView: UIPickerView,
viewForRow row: Int,
forComponent component: Int,
reusingView view: UIView?) -> UIView {
let pickerLabel = UILabel()
pickerLabel.textColor = UIColor.blackColor()
pickerLabel.text = projectsArray[row] as? String
pickerLabel.font = UIFont(name: "Arial-BoldMT", size: 15)
pickerLabel.textAlignment = NSTextAlignment.Center
return pickerLabel
}
func signIn(signIn: GIDSignIn!,
presentViewController viewController: UIViewController!) {
print("sign in button pressed")
self.presentViewController(viewController, animated: true, completion: nil)
}
/// Dismiss the "Sign in with Google" view.
func signIn(signIn: GIDSignIn!,
dismissViewController viewController: UIViewController!) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func didTapSignOut() {
GIDSignIn.sharedInstance().signOut()
NSNotificationCenter.defaultCenter().postNotificationName(
"ToggleAuthUINotification", object: nil, userInfo: nil)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: "ToggleAuthUINotification",
object: nil)
}
func reloadDataInUIElements() {
profileImage.frame.size = CGSizeMake(100, 100)
profileImage.image = userInfo.userImage
profileImage.layer.cornerRadius = profileImage.frame.width/2
profileImage.clipsToBounds = true
if userInfo.userCurrentlySignedIn {
statusText.text = userInfo.userName!
emailTextView.hidden = false
emailTextView.text = userInfo.userEmail!
signInButton.hidden = true
signOutButton.hidden = false
projectIDPickerView.hidden = false
projectSelectionDescriptionView.hidden = false
projectsArray = userInfo.projectsArray
projectIDPickerView.reloadAllComponents()
if let row = userInfo.selectedProjectIndex {
projectIDPickerView.selectRow(row, inComponent: 0, animated: true)
}
} else {
statusText.text = userInfo.statusInfo
emailTextView.hidden = true
signInButton.hidden = false
signOutButton.hidden = true
projectsArray.removeAllObjects()
projectIDPickerView.reloadAllComponents()
projectIDPickerView.hidden = true
projectSelectionDescriptionView.hidden = true
EIDConfiguration.projectID = nil
}
}
@objc func receiveToggleAuthUINotification(notification: NSNotification) {
if (notification.name == "ToggleAuthUINotification") {
if let data = notification.userInfo {
userInfo.userName = data["statusText"] as? String
let imageData = NSData(contentsOfURL: data["imageURL"] as! NSURL)
userInfo.userImage = UIImage(data: imageData!)!
userInfo.userEmail = data["email"] as? String
userInfo.userCurrentlySignedIn = true
/// When the user signs in, we need to get a list of the projects using the Cloud platform.
userInfo.getProjectList() {state in
dispatch_async(dispatch_get_main_queue()) {
if state == GettingProjectsListState.GotUserProjects {
self.reloadDataInUIElements()
if let view = self.viewToDisable {
view.removeFromSuperview()
}
if let selectView = self.selectHolder {
if EIDConfiguration.projectID != nil {
selectView.removeFromSuperview()
} else {
selectView.hidden = false
}
}
} else if state == GettingProjectsListState.UnableToGetProjects {
self.didTapSignOut()
self.showAlert("Projects List",
description: "Unable to get projects list.",
buttonText: "Dismiss")
} else if state == GettingProjectsListState.UserHasNoProjects {
self.didTapSignOut()
self.showAlert("Projects List",
description: "The account you selected has no projects." +
"You will not be able to register an EID Beacon." +
"Create a Google project or change the account.",
buttonText: "Dismiss")
}
}
}
} else {
userInfo.clearData()
reloadDataInUIElements()
}
}
}
func showAlert(title: String, description: String, buttonText:String) {
let alertController = UIAlertController(title: title,
message: description,
preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: buttonText,
style: UIAlertActionStyle.Default,
handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| apache-2.0 | 21fb03bed863af7c3770ab9e647442a8 | 39.434211 | 100 | 0.661677 | 5.480975 | false | false | false | false |
Jnosh/swift | test/SILGen/keypaths.swift | 2 | 7875 | // RUN: %target-swift-frontend -enable-experimental-keypath-components -emit-silgen %s | %FileCheck %s
struct S<T> {
var x: T
let y: String
var z: C<T>
var computed: C<T> { fatalError() }
var observed: C<T> { didSet { fatalError() } }
var reabstracted: () -> ()
}
class C<T> {
final var x: T
final let y: String
final var z: S<T>
var nonfinal: S<T>
var computed: S<T> { fatalError() }
var observed: S<T> { didSet { fatalError() } }
final var reabstracted: () -> ()
init() { fatalError() }
}
protocol P {
var x: Int { get }
var y: String { get set }
}
extension P {
var z: String {
return y
}
}
// CHECK-LABEL: sil hidden @{{.*}}storedProperties
func storedProperties<T>(_: T) {
// CHECK: keypath $WritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T>
_ = \S<T>.x
// CHECK: keypath $KeyPath<S<T>, String>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.y : $String) <T>
_ = \S<T>.y
// CHECK: keypath $ReferenceWritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T>
_ = \S<T>.z.x
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T>
_ = \C<T>.x
// CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.y : $String) <T>
_ = \C<T>.y
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T>
_ = \C<T>.z.x
// CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.y : $String) <T>
_ = \C<T>.z.z.y
}
// CHECK-LABEL: sil hidden @{{.*}}computedProperties
func computedProperties<T: P>(_: T) {
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $S<τ_0_0>,
// CHECK-SAME: id #C.nonfinal!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @_T08keypaths1CC8nonfinalAA1SVyxGvAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in C<τ_0_0>) -> @out S<τ_0_0>,
// CHECK-SAME: setter @_T08keypaths1CC8nonfinalAA1SVyxGvAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in S<τ_0_0>, @in C<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \C<T>.nonfinal
// CHECK: keypath $KeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: gettable_property $S<τ_0_0>,
// CHECK-SAME: id #C.computed!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @_T08keypaths1CC8computedAA1SVyxGvAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in C<τ_0_0>) -> @out S<τ_0_0>
// CHECK-SAME: ) <T>
_ = \C<T>.computed
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $S<τ_0_0>,
// CHECK-SAME: id #C.observed!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @_T08keypaths1CC8observedAA1SVyxGvAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in C<τ_0_0>) -> @out S<τ_0_0>,
// CHECK-SAME: setter @_T08keypaths1CC8observedAA1SVyxGvAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in S<τ_0_0>, @in C<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \C<T>.observed
_ = \C<T>.nonfinal.x
_ = \C<T>.computed.x
_ = \C<T>.observed.x
_ = \C<T>.z.computed
_ = \C<T>.z.observed
_ = \C<T>.observed.x
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $() -> (),
// CHECK-SAME: id ##C.reabstracted,
// CHECK-SAME: getter @_T08keypaths1CC12reabstractedyycvAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in C<τ_0_0>) -> @out @callee_owned (@in ()) -> @out (),
// CHECK-SAME: setter @_T08keypaths1CC12reabstractedyycvAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in @callee_owned (@in ()) -> @out (), @in C<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \C<T>.reabstracted
// CHECK: keypath $KeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>; gettable_property $C<τ_0_0>,
// CHECK-SAME: id @_T08keypaths1SV8computedAA1CCyxGfg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>,
// CHECK-SAME: getter @_T08keypaths1SV8computedAA1CCyxGvAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in S<τ_0_0>) -> @out C<τ_0_0>
// CHECK-SAME: ) <T>
_ = \S<T>.computed
// CHECK: keypath $WritableKeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>;
// CHECK-SAME: settable_property $C<τ_0_0>,
// CHECK-SAME: id @_T08keypaths1SV8observedAA1CCyxGfg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>,
// CHECK-SAME: getter @_T08keypaths1SV8observedAA1CCyxGvAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in S<τ_0_0>) -> @out C<τ_0_0>,
// CHECK-SAME: setter @_T08keypaths1SV8observedAA1CCyxGvAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in C<τ_0_0>, @inout S<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \S<T>.observed
_ = \S<T>.z.nonfinal
_ = \S<T>.z.computed
_ = \S<T>.z.observed
_ = \S<T>.computed.x
_ = \S<T>.computed.y
// CHECK: keypath $WritableKeyPath<S<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>;
// CHECK-SAME: settable_property $() -> (),
// CHECK-SAME: id ##S.reabstracted,
// CHECK-SAME: getter @_T08keypaths1SV12reabstractedyycvAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in S<τ_0_0>) -> @out @callee_owned (@in ()) -> @out (),
// CHECK-SAME: setter @_T08keypaths1SV12reabstractedyycvAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in @callee_owned (@in ()) -> @out (), @inout S<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \S<T>.reabstracted
// CHECK: keypath $KeyPath<T, Int>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: gettable_property $Int,
// CHECK-SAME: id #P.x!getter.1 : <Self where Self : P> (Self) -> () -> Int,
// CHECK-SAME: getter @_T08keypaths1PP1xSivAaBRzlxTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in τ_0_0) -> @out Int
// CHECK-SAME: ) <T>
_ = \T.x
// CHECK: keypath $WritableKeyPath<T, String>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: settable_property $String,
// CHECK-SAME: id #P.y!getter.1 : <Self where Self : P> (Self) -> () -> String,
// CHECK-SAME: getter @_T08keypaths1PP1ySSvAaBRzlxTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in τ_0_0) -> @out String,
// CHECK-SAME: setter @_T08keypaths1PP1ySSvAaBRzlxTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in String, @inout τ_0_0) -> ()
// CHECK-SAME: ) <T>
_ = \T.y
// CHECK: keypath $KeyPath<T, String>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: gettable_property $String,
// CHECK-SAME: id @_T08keypaths1PPAAE1zSSfg
_ = \T.z
}
struct Concrete: P {
var x: Int
var y: String
}
// CHECK-LABEL: sil hidden @_T08keypaths35keyPathsWithSpecificGenericInstanceyyF
func keyPathsWithSpecificGenericInstance() {
// CHECK: keypath $KeyPath<Concrete, String>, (
// CHECK-SAME: gettable_property $String,
// CHECK-SAME: id @_T08keypaths1PPAAE1zSSfg
// CHECK-SAME: getter @_T08keypaths1PPAAE1zSSvAA8ConcreteVTK : $@convention(thin) (@in Concrete) -> @out String
_ = \Concrete.z
_ = \S<Concrete>.computed
}
class AA<T> {
var a: Int { get { return 0 } set { } }
}
class BB<U, V>: AA<V> {
}
func keyPathForInheritedMember() {
_ = \BB<Int, String>.a
}
| apache-2.0 | cd3cccaafda91f58868f9cdfed33cea5 | 43.849711 | 183 | 0.591184 | 2.493252 | false | false | false | false |
IvanVorobei/ParallaxTableView | ParallaxTableView - project/ParallaxTableView/Sparrow/Random/SPRandom.swift | 1 | 2897 | // The MIT License (MIT)
//
// Copyright (c) 2015 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public extension Int {
public static func random(_ n: Int) -> Int {
return Int(arc4random_uniform(UInt32(n)))
}
public static func random(min: Int, max: Int) -> Int {
return Int(arc4random_uniform(UInt32(max - min - 1))) + min
}
}
public extension Double {
public static func random() -> Double {
return Double(arc4random()) / 0xFFFFFFFF
}
public static func random(min: Double, max: Double) -> Double {
return Double.random() * (max - min) + min
}
}
public extension Float {
public static func random() -> Float {
return Float(arc4random()) / 0xFFFFFFFF
}
public static func random(min: Float, max: Float) -> Float {
return Float.random() * (max - min) + min
}
}
public extension CGFloat {
public static func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
public static func random(min: CGFloat, max: CGFloat) -> CGFloat {
return CGFloat.random() * (max - min) + min
}
}
extension Collection {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
extension MutableCollection where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in startIndex ..< endIndex - 1 {
let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
| mit | d860e29e3310e1519b2ba8b7a812f9af | 32.686047 | 81 | 0.657577 | 4.229197 | false | false | false | false |
SukhKalsi/MemeApp | MemeMe/MemeMeTextfieldDelegate.swift | 1 | 1782 | //
// MemeMeTextfieldDelegate.swift
// MemeMe
//
// Created by Sukh Kalsi on 16/08/2015.
// Copyright (c) 2015 Sukh Kalsi. All rights reserved.
//
import Foundation
import UIKit
class MemeMeTextfieldDelegate: NSObject, UITextFieldDelegate {
var activeTextFieldTag: Int?
// Just as user begins typing into any textfield, identifiy if this is first time entering specific textfield - if so clear the default text.
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
var text = textField.text
var tag = textField.tag
// assign our property so we know when editing if we need to move the view up i.e. for Bottom TextField.
self.activeTextFieldTag = tag
// The tag is defined within storyboard attributes inspector for each textfield
if (text == "TOP" && tag == 1) || (text == "BOTTOM" && tag == 2) {
textField.text = ""
}
return true
}
// Once finished, bring focus back to the main app.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// Whilst typing, convert everything to uppercase - for some reason setting capitalisation doesn't do this automatically...
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// If we have upper case, then we directly edit the text field...
if string.capitalizedString != string {
textField.text = textField.text! + string.capitalizedString
return false
}
// Otherwise we allow the proposed edit.
return true
}
} | mit | 356211511673386bee2311b4955faa79 | 33.288462 | 145 | 0.641975 | 5.091429 | false | false | false | false |
PixelRunStudios/SwiftTest | SwiftTest/SwiftTest/AppDelegate.swift | 1 | 2738 | //
// AppDelegate.swift
// SwiftTest
//
// Created by Markus Feng on 9/21/14.
// Copyright (c) 2014 Markus Feng. 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.
println("Hello, world!");
var variable = 10;
//println(variable);
variable = 20;
//println(variable);
var notDoubleThing = 70;
//println(notDoubleThing);
var doubleThing : Double = 70;
//println(doubleThing);
let apples = 3;
let appleSummary = "I have \(apples) apples.";
println(appleSummary);
var listOfAwesome = ["", "", "", ""];
listOfAwesome[0] = "hi";
listOfAwesome[1] = "lol";
println(listOfAwesome[0]);
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 558ca7a818c13aa194adf06e564ffca4 | 39.264706 | 285 | 0.692841 | 5.337232 | false | false | false | false |
nekrich/GlobalMessageService-iOS | Source/Core/Message/GMSMessage.swift | 1 | 5086 | //
// GMSMessage.swift
// Pods
//
// Created by Vitalii Budnik on 1/25/16.
//
//
import Foundation
/**
Compares two `GlobalMessageServiceMessage`s
- Parameter lhs: frirst `GlobalMessageServiceMessage`
- Parameter rhs: second `GlobalMessageServiceMessage`
- Returns: `true` if both messages are equal, otherwise returns `false`
*/
@warn_unused_result public func == (
lhs: GlobalMessageServiceMessage,
rhs: GlobalMessageServiceMessage)
-> Bool //swiftlint:disable:this opening_brace
{
return lhs.alphaName == rhs.alphaName
&& lhs.type == rhs.type
&& lhs.id == rhs.id
&& lhs.deliveredDate.timeIntervalSinceReferenceDate == rhs.deliveredDate.timeIntervalSinceReferenceDate
}
/**
`Struct` representing delivered message to subscriber
*/
public struct GlobalMessageServiceMessage: Hashable {
/**
`String` representing senders alpha name. Can be `nil`
*/
public let alphaName: String
/**
`String` representing message body. Can be `nil`
*/
public let message: String
/**
Message delivered `NSDate`
*/
public let deliveredDate: NSDate
/**
Message type
- SeeAlso: `GlobalMessageServiceMessageType` for details
*/
public let type: GlobalMessageServiceMessageType
/**
`UInt64` Global Message Services message id
*/
public let id: UInt64 // swiftlint:disable:this variable_name
// swiftlint:disable valid_docs
/**
Initializes a new instance of `GlobalMessageServiceMessage` from `GMSInboxMessage`
- Parameter message: `GMSInboxMessage` object
- Returns: Converted object from `GMSInboxMessage` if successfully converted, `nil` otherwise
*/
internal init?(message: GMSInboxMessage) {
// swiftlint:enable valid_docs
guard let type = GlobalMessageServiceMessageType(rawValue: message.type) else {
return nil
}
if message.fetchedDate?.to != GlobalMessageService.registeredUserPhone {
return nil
}
self.alphaName = message.getAlphaNameString()
self.message = message.message ?? ""
self.id = message.messageID?.unsignedLongLongValue ?? 0
self.deliveredDate = NSDate(timeIntervalSinceReferenceDate: message.deliveredDate)
self.type = type
}
// swiftlint:disable valid_docs
/**
Initializes a new instance of `GlobalMessageServiceMessage` from `GlobalMessageServicePushNotification`
- Parameter pushNotification: `GlobalMessageServicePushNotification` object
- Returns: Converted object from `GlobalMessageServicePushNotification` if successfully converted,
`nil` otherwise
*/
public init(pushNotification: GlobalMessageServicePushNotification) {
// swiftlint:enable valid_docs
self.alphaName = pushNotification.alphaName
self.message = pushNotification.body ?? ""
self.id = pushNotification.gmsMessageID
self.deliveredDate = pushNotification.deliveredDate
self.type = .PushNotification
}
// swiftlint:disable valid_docs
/**
Initializes a new instance of `GlobalMessageServiceMessage` from `[String: AnyObject]`
- Parameter dictionary: Dictionary<String, AnyObject> describing message
- Returns: Converted object from ` Dictionary<String, AnyObject>` if successfully converted,
`nil` otherwise
*/
internal init?(
// swiftlint:enable valid_docs
dictionary: Dictionary<String, AnyObject>,
andType type: GlobalMessageServiceMessageType) // swiftlint:disable:this opening_brace
{
guard let
from = dictionary["from"] as? String,
to = dictionary["to"] as? Double,
message = dictionary["message"] as? String,
id = dictionary["msg_uniq_id"] as? Double,
deliveredTimeStamp = dictionary["deliveredDate"] as? Double
else // swiftlint:disable:this opening_brace
{
return nil
}
if Int64(to) != GlobalMessageService.registeredUserPhone {
return nil
}
self.alphaName = from
//self.to = UInt64(to)
self.message = message
self.id = UInt64(id)
self.deliveredDate = NSDate(timeIntervalSince1970: deliveredTimeStamp / 1000.0)
self.type = type
}
public var hashValue: Int {
return "\(alphaName)\(deliveredDate.timeIntervalSinceReferenceDate)\(id)\(type.rawValue)".hash
}
public func delete() -> Bool {
let predicate = NSPredicate(
format: "messageID == %@ && deliveredDate == %@ && type == \(type.rawValue)",
NSDecimalNumber(unsignedLongLong: id),
deliveredDate)//,
//NSNumber(short: ))
let moc = GlobalMessageServiceCoreDataHelper.newManagedObjectContext()
if let message = GMSInboxMessage.findObject(
withPredicate: predicate,
inManagedObjectContext: moc,
createNewIfNotFound: false) as? GMSInboxMessage {
message.deletionMark = true
let result = moc.saveSafeRecursively()
switch result {
case .Failure(_):
return false
default:
return true
}
}
return false
}
}
| apache-2.0 | c36b1c160d900c402758234ad3cdc3c4 | 28.74269 | 106 | 0.680299 | 4.802644 | false | false | false | false |
jwfriese/Fleet | TestAppCommon/PuppyListViewController.swift | 2 | 1517 | import UIKit
class PuppyListViewController: UIViewController {
@IBOutlet weak var showPuppiesListButton: UIButton?
@IBOutlet weak var corgiButton: UIButton?
@IBOutlet weak var malteseButton: UIButton?
@IBOutlet weak var frenchBulldogButton: UIButton?
@IBOutlet weak var basenjiButton: UIButton?
private var ShowCorgiSegueIdentifier: String { get { return "ShowCorgi" } }
var segueDestinationViewDidLoadCallCount: Int = 0
var segueDestinationViewController: UIViewController?
var corgiViewControllerImageViewIBOutletValue: UIImageView?
@IBAction func showPuppiesList() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.revealPuppies()
}
}
fileprivate func revealPuppies() {
corgiButton?.isHidden = false
malteseButton?.isHidden = false
frenchBulldogButton?.isHidden = false
basenjiButton?.isHidden = false
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == ShowCorgiSegueIdentifier {
if let corgiViewController = segue.destination as? CorgiViewController {
segueDestinationViewDidLoadCallCount = corgiViewController.viewDidLoadCallCount
segueDestinationViewController = segue.destination
corgiViewControllerImageViewIBOutletValue = corgiViewController.corgiImageView
}
}
}
}
| apache-2.0 | b884def294b0fb5356333b005829ae17 | 37.897436 | 136 | 0.709954 | 5.125 | false | false | false | false |
vtourraine/trackup | trackup-ios/DocumentsListViewController.swift | 1 | 2780 | //
// DocumentsListViewController.swift
// trackup-ios
//
// Created by Vincent Tourraine on 30/11/16.
// Copyright © 2016-2018 Studio AMANgA. All rights reserved.
//
import UIKit
import TrackupCore
class DocumentsListViewController: UITableViewController {
var detailViewController: DocumentViewController? = nil
var documents = [TrackupDocument]()
override func viewDidLoad() {
super.viewDidLoad()
let parser = TrackupParser()
let paths = [Bundle.main.path(forResource: "onelist", ofType: "tu.md"),
Bundle.main.path(forResource: "contacts", ofType: "tu.md"),
Bundle.main.path(forResource: "gameskeeper", ofType: "tu.md")]
documents = paths.map({ (path) -> TrackupDocument in
let content = try! NSString(contentsOfFile: path!, usedEncoding: nil)
let document = parser.documentFromString(content as String)
return document
})
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DocumentViewController
}
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let document = documents[indexPath.row]
let controller = (segue.destination as! UINavigationController).topViewController as! DocumentViewController
controller.representedDocument = document
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return documents.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let document = documents[indexPath.row]
cell.textLabel?.text = document.title
cell.detailTextLabel?.text = "\(document.versions.count) versions"
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return false
}
}
| mit | f67fce2bcd8083979ef7cea397eef092 | 35.565789 | 146 | 0.671105 | 5.333973 | false | false | false | false |
luinily/hOme | hOme/UI/SequenceTimeCell.swift | 1 | 1627 | //
// SequenceTimeCell.swift
// hOme
//
// Created by Coldefy Yoann on 2016/04/06.
// Copyright © 2016年 YoannColdefy. All rights reserved.
//
import Foundation
import UIKit
class SequenceTimeCell: UITableViewCell {
private var _timeEditor: UITextField!
@IBOutlet weak var timeEditor: UITextField! {
get {return _timeEditor}
set {
_timeEditor = newValue
_timeEditor.delegate = self
}
}
@IBAction func editingDidEnd(_ sender: AnyObject) {
if let newTime = _timeEditor.text {
_time?.time = newTime
if let time = _time {
_onChange?(time)
}
}
}
private var _time: CommandTime?
var time: CommandTime? {
get {return _time}
set {
_time = newValue
_timeEditor.text = newValue?.time
}
}
private var _onChange: ((_ newValue: CommandTime) -> Void)?
var onChange: ((_ newValue: CommandTime) -> Void)? {
get {return _onChange}
set {
_onChange = newValue
}
}
}
extension SequenceTimeCell: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let stringCharacterRange = string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) else {
return false
}
if stringCharacterRange.isEmpty {
return false //this field accepts only alphanumeric chars
}
if let text = textField.text {
let length = text.characters.count //check if this is still the way to do this
switch length {
case 2:
textField.text = text + ":"
default:
break
}
if length > 4 {
return false
}
return true
}
return false
}
}
| mit | 75c02e118a9b705bed75220c37fb9f16 | 20.368421 | 126 | 0.676724 | 3.569231 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/PromiseKit/Sources/Guarantee.swift | 1 | 9965 | import class Foundation.Thread
import Dispatch
/**
A `Guarantee` is a functional abstraction around an asynchronous operation that cannot error.
- See: `Thenable`
*/
public final class Guarantee<T>: Thenable {
let box: PromiseKit.Box<T>
fileprivate init(box: SealedBox<T>) {
self.box = box
}
/// Returns a `Guarantee` sealed with the provided value.
public static func value(_ value: T) -> Guarantee<T> {
return .init(box: SealedBox(value: value))
}
/// Returns a pending `Guarantee` that can be resolved with the provided closure’s parameter.
public init(resolver body: (@escaping(T) -> Void) -> Void) {
box = Box()
body(box.seal)
}
/// - See: `Thenable.pipe`
public func pipe(to: @escaping(Result<T>) -> Void) {
pipe{ to(.fulfilled($0)) }
}
func pipe(to: @escaping(T) -> Void) {
switch box.inspect() {
case .pending:
box.inspect {
switch $0 {
case .pending(let handlers):
handlers.append(to)
case .resolved(let value):
to(value)
}
}
case .resolved(let value):
to(value)
}
}
/// - See: `Thenable.result`
public var result: Result<T>? {
switch box.inspect() {
case .pending:
return nil
case .resolved(let value):
return .fulfilled(value)
}
}
final private class Box<T>: EmptyBox<T> {
deinit {
switch inspect() {
case .pending:
PromiseKit.conf.logHandler(.pendingGuaranteeDeallocated)
case .resolved:
break
}
}
}
init(_: PMKUnambiguousInitializer) {
box = Box()
}
/// Returns a tuple of a pending `Guarantee` and a function that resolves it.
public class func pending() -> (guarantee: Guarantee<T>, resolve: (T) -> Void) {
return { ($0, $0.box.seal) }(Guarantee<T>(.pending))
}
}
public extension Guarantee {
@discardableResult
func done(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> Void) -> Guarantee<Void> {
let rg = Guarantee<Void>(.pending)
pipe { (value: T) in
on.async(flags: flags) {
body(value)
rg.box.seal(())
}
}
return rg
}
func get(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping (T) -> Void) -> Guarantee<T> {
return map(on: on, flags: flags) {
body($0)
return $0
}
}
func map<U>(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> U) -> Guarantee<U> {
let rg = Guarantee<U>(.pending)
pipe { value in
on.async(flags: flags) {
rg.box.seal(body(value))
}
}
return rg
}
@discardableResult
func then<U>(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> Guarantee<U>) -> Guarantee<U> {
let rg = Guarantee<U>(.pending)
pipe { value in
on.async(flags: flags) {
body(value).pipe(to: rg.box.seal)
}
}
return rg
}
func asVoid() -> Guarantee<Void> {
return map(on: nil) { _ in }
}
/**
Blocks this thread, so you know, don’t call this on a serial thread that
any part of your chain may use. Like the main thread for example.
*/
func wait() -> T {
if Thread.isMainThread {
conf.logHandler(.waitOnMainThread)
}
var result = value
if result == nil {
let group = DispatchGroup()
group.enter()
pipe { (foo: T) in result = foo; group.leave() }
group.wait()
}
return result!
}
}
public extension Guarantee where T: Sequence {
/**
`Guarantee<[T]>` => `T` -> `U` => `Guarantee<[U]>`
Guarantee.value([1,2,3])
.mapValues { integer in integer * 2 }
.done {
// $0 => [2,4,6]
}
*/
func mapValues<U>(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U) -> Guarantee<[U]> {
return map(on: on, flags: flags) { $0.map(transform) }
}
/**
`Guarantee<[T]>` => `T` -> `[U]` => `Guarantee<[U]>`
Guarantee.value([1,2,3])
.flatMapValues { integer in [integer, integer] }
.done {
// $0 => [1,1,2,2,3,3]
}
*/
func flatMapValues<U: Sequence>(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U) -> Guarantee<[U.Iterator.Element]> {
return map(on: on, flags: flags) { (foo: T) in
foo.flatMap { transform($0) }
}
}
/**
`Guarantee<[T]>` => `T` -> `U?` => `Guarantee<[U]>`
Guarantee.value(["1","2","a","3"])
.compactMapValues { Int($0) }
.done {
// $0 => [1,2,3]
}
*/
func compactMapValues<U>(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U?) -> Guarantee<[U]> {
return map(on: on, flags: flags) { foo -> [U] in
#if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1))
return foo.flatMap(transform)
#else
return foo.compactMap(transform)
#endif
}
}
/**
`Guarantee<[T]>` => `T` -> `Guarantee<U>` => `Guaranetee<[U]>`
Guarantee.value([1,2,3])
.thenMap { .value($0 * 2) }
.done {
// $0 => [2,4,6]
}
*/
func thenMap<U>(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> Guarantee<U>) -> Guarantee<[U]> {
return then(on: on, flags: flags) {
when(fulfilled: $0.map(transform))
}.recover {
// if happens then is bug inside PromiseKit
fatalError(String(describing: $0))
}
}
/**
`Guarantee<[T]>` => `T` -> `Guarantee<[U]>` => `Guarantee<[U]>`
Guarantee.value([1,2,3])
.thenFlatMap { integer in .value([integer, integer]) }
.done {
// $0 => [1,1,2,2,3,3]
}
*/
func thenFlatMap<U: Thenable>(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U) -> Guarantee<[U.T.Iterator.Element]> where U.T: Sequence {
return then(on: on, flags: flags) {
when(fulfilled: $0.map(transform))
}.map(on: nil) {
$0.flatMap { $0 }
}.recover {
// if happens then is bug inside PromiseKit
fatalError(String(describing: $0))
}
}
/**
`Guarantee<[T]>` => `T` -> Bool => `Guarantee<[T]>`
Guarantee.value([1,2,3])
.filterValues { $0 > 1 }
.done {
// $0 => [2,3]
}
*/
func filterValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ isIncluded: @escaping(T.Iterator.Element) -> Bool) -> Guarantee<[T.Iterator.Element]> {
return map(on: on, flags: flags) {
$0.filter(isIncluded)
}
}
/**
`Guarantee<[T]>` => (`T`, `T`) -> Bool => `Guarantee<[T]>`
Guarantee.value([5,2,3,4,1])
.sortedValues { $0 > $1 }
.done {
// $0 => [5,4,3,2,1]
}
*/
func sortedValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ areInIncreasingOrder: @escaping(T.Iterator.Element, T.Iterator.Element) -> Bool) -> Guarantee<[T.Iterator.Element]> {
return map(on: on, flags: flags) {
$0.sorted(by: areInIncreasingOrder)
}
}
}
public extension Guarantee where T: Sequence, T.Iterator.Element: Comparable {
/**
`Guarantee<[T]>` => `Guarantee<[T]>`
Guarantee.value([5,2,3,4,1])
.sortedValues()
.done {
// $0 => [1,2,3,4,5]
}
*/
func sortedValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil) -> Guarantee<[T.Iterator.Element]> {
return map(on: on, flags: flags) { $0.sorted() }
}
}
#if swift(>=3.1)
public extension Guarantee where T == Void {
convenience init() {
self.init(box: SealedBox(value: Void()))
}
static var value: Guarantee<Void> {
return .value(Void())
}
}
#endif
public extension DispatchQueue {
/**
Asynchronously executes the provided closure on a dispatch queue.
DispatchQueue.global().async(.promise) {
md5(input)
}.done { md5 in
//…
}
- Parameter body: The closure that resolves this promise.
- Returns: A new `Guarantee` resolved by the result of the provided closure.
- Note: There is no Promise/Thenable version of this due to Swift compiler ambiguity issues.
*/
@available(macOS 10.10, iOS 2.0, tvOS 10.0, watchOS 2.0, *)
final func async<T>(_: PMKNamespacer, group: DispatchGroup? = nil, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = [], execute body: @escaping () -> T) -> Guarantee<T> {
let rg = Guarantee<T>(.pending)
async(group: group, qos: qos, flags: flags) {
rg.box.seal(body())
}
return rg
}
}
#if os(Linux)
import func CoreFoundation._CFIsMainThread
extension Thread {
// `isMainThread` is not implemented yet in swift-corelibs-foundation.
static var isMainThread: Bool {
return _CFIsMainThread()
}
}
#endif
| apache-2.0 | 6de89e125f5eb299cd05b5082c676f29 | 29.643077 | 211 | 0.526157 | 3.782378 | false | false | false | false |
ted005/Qiu_Suo | Qiu Suo/Pods/Kingfisher/Kingfisher/ImageCache.swift | 6 | 28061 | //
// ImageCache.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification.
The `object` of this notification is the `ImageCache` object which sends the notification.
A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed.
The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it.
*/
public let KingfisherDidCleanDiskCacheNotification = "com.onevcat.Kingfisher.KingfisherDidCleanDiskCacheNotification"
/**
Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`.
*/
public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
private let defaultCacheName = "default"
private let cacheReverseDNS = "com.onevcat.Kingfisher.ImageCache."
private let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue."
private let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue."
private let defaultCacheInstance = ImageCache(name: defaultCacheName)
private let defaultMaxCachePeriodInSecond: NSTimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week
/// It represents a task of retrieving image. You can call `cancel` on it to stop the process.
public typealias RetrieveImageDiskTask = dispatch_block_t
/**
Cache type of a cached image.
- None: The image is not cached yet when retrieving it.
- Memory: The image is cached in memory.
- Disk: The image is cached in disk.
*/
public enum CacheType {
case None, Memory, Disk
}
/// `ImageCache` represents both the memory and disk cache system of Kingfisher. While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create your own cache object and configure it as your need. You should use an `ImageCache` object to manipulate memory and disk cache for Kingfisher.
public class ImageCache {
//Memory
private let memoryCache = NSCache()
/// The largest cache cost of memory cache. The total cost is pixel count of all cached images in memory.
public var maxMemoryCost: UInt = 0 {
didSet {
self.memoryCache.totalCostLimit = Int(maxMemoryCost)
}
}
//Disk
private let ioQueue: dispatch_queue_t
private let diskCachePath: String
private var fileManager: NSFileManager!
/// The longest time duration of the cache being stored in disk. Default is 1 week.
public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond
/// The largest disk size can be taken for the cache. It is the total allocated size of cached files in bytes. Default is 0, which means no limit.
public var maxDiskCacheSize: UInt = 0
private let processQueue: dispatch_queue_t
/// The default cache.
public class var defaultCache: ImageCache {
return defaultCacheInstance
}
/**
Init method. Passing a name for the cache. It represents a cache folder in the memory and disk.
- parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name. This value should not be an empty string.
- returns: The cache object.
*/
public init(name: String) {
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
}
let cacheName = cacheReverseDNS + name
memoryCache.name = cacheName
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
diskCachePath = (paths.first! as NSString).stringByAppendingPathComponent(cacheName)
ioQueue = dispatch_queue_create(ioQueueName + name, DISPATCH_QUEUE_SERIAL)
processQueue = dispatch_queue_create(processQueueName + name, DISPATCH_QUEUE_CONCURRENT)
dispatch_sync(ioQueue, { () -> Void in
self.fileManager = NSFileManager()
})
NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "cleanExpiredDiskCache", name: UIApplicationWillTerminateNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgroundCleanExpiredDiskCache", name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
// MARK: - Store & Remove
public extension ImageCache {
/**
Store an image to cache. It will be saved to both memory and disk.
It is an async operation, if you need to do something about the stored image, use `-storeImage:forKey:toDisk:completionHandler:`
instead.
- parameter image: The image will be stored.
- parameter originalData: The original data of the image.
Kingfisher will use it to check the format of the image and optimize cache size on disk.
If `nil` is supplied, the image data will be saved as a normalized PNG file.
- parameter key: Key for the image.
*/
public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String) {
storeImage(image, originalData: originalData,forKey: key, toDisk: true, completionHandler: nil)
}
/**
Store an image to cache. It is an async operation.
- parameter image: The image will be stored.
- parameter originalData: The original data of the image.
Kingfisher will use it to check the format of the image and optimize cache size on disk.
If `nil` is supplied, the image data will be saved as a normalized PNG file.
- parameter key: Key for the image.
- parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
- parameter completionHandler: Called when stroe operation completes.
*/
public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) {
memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost)
func callHandlerInMainQueue() {
if let handler = completionHandler {
dispatch_async(dispatch_get_main_queue()) {
handler()
}
}
}
if toDisk {
dispatch_async(ioQueue, { () -> Void in
let imageFormat: ImageFormat
if let originalData = originalData {
imageFormat = originalData.kf_imageFormat
} else {
imageFormat = .Unknown
}
let data: NSData?
switch imageFormat {
case .PNG: data = UIImagePNGRepresentation(image)
case .JPEG: data = UIImageJPEGRepresentation(image, 1.0)
case .Unknown: data = UIImagePNGRepresentation(image.kf_normalizedImage())
}
if let data = data {
if !self.fileManager.fileExistsAtPath(self.diskCachePath) {
do {
try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
} catch _ {}
}
self.fileManager.createFileAtPath(self.cachePathForKey(key), contents: data, attributes: nil)
callHandlerInMainQueue()
} else {
callHandlerInMainQueue()
}
})
} else {
callHandlerInMainQueue()
}
}
/**
Remove the image for key for the cache. It will be opted out from both memory and disk.
It is an async operation, if you need to do something about the stored image, use `-removeImageForKey:fromDisk:completionHandler:`
instead.
- parameter key: Key for the image.
*/
public func removeImageForKey(key: String) {
removeImageForKey(key, fromDisk: true, completionHandler: nil)
}
/**
Remove the image for key for the cache. It is an async operation.
- parameter key: Key for the image.
- parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory.
- parameter completionHandler: Called when removal operation completes.
*/
public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) {
memoryCache.removeObjectForKey(key)
func callHandlerInMainQueue() {
if let handler = completionHandler {
dispatch_async(dispatch_get_main_queue()) {
handler()
}
}
}
if fromDisk {
dispatch_async(ioQueue, { () -> Void in
do {
try self.fileManager.removeItemAtPath(self.cachePathForKey(key))
} catch _ {}
callHandlerInMainQueue()
})
} else {
callHandlerInMainQueue()
}
}
}
// MARK: - Get data from cache
extension ImageCache {
/**
Get an image for a key from memory or disk.
- parameter key: Key for the image.
- parameter options: Options of retrieving image.
- parameter completionHandler: Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`.
- returns: The retrieving task.
*/
public func retrieveImageForKey(key: String, options:KingfisherManager.Options, completionHandler: ((UIImage?, CacheType!) -> ())?) -> RetrieveImageDiskTask? {
// No completion handler. Not start working and early return.
guard let completionHandler = completionHandler else {
return dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {}
}
let block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {
if let image = self.retrieveImageInMemoryCacheForKey(key) {
//Found image in memory cache.
if options.shouldDecode {
dispatch_async(self.processQueue, { () -> Void in
let result = image.kf_decodedImage(scale: options.scale)
dispatch_async(options.queue, { () -> Void in
completionHandler(result, .Memory)
})
})
} else {
completionHandler(image, .Memory)
}
} else {
//Begin to load image from disk
dispatch_async(self.ioQueue, { () -> Void in
if let image = self.retrieveImageInDiskCacheForKey(key, scale: options.scale) {
if options.shouldDecode {
dispatch_async(self.processQueue, { () -> Void in
let result = image.kf_decodedImage(scale: options.scale)
self.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil)
dispatch_async(options.queue, { () -> Void in
completionHandler(result, .Memory)
return
})
})
} else {
self.storeImage(image, forKey: key, toDisk: false, completionHandler: nil)
dispatch_async(options.queue, { () -> Void in
completionHandler(image, .Disk)
})
}
} else {
// No image found from either memory or disk
dispatch_async(options.queue, { () -> Void in
completionHandler(nil, nil)
})
}
})
}
}
dispatch_async(dispatch_get_main_queue(), block)
return block
}
/**
Get an image for a key from memory.
- parameter key: Key for the image.
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
public func retrieveImageInMemoryCacheForKey(key: String) -> UIImage? {
return memoryCache.objectForKey(key) as? UIImage
}
/**
Get an image for a key from disk.
- parameter key: Key for the image.
- param scale: The scale factor to assume when interpreting the image data.
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = KingfisherManager.DefaultOptions.scale) -> UIImage? {
return diskImageForKey(key, scale: scale)
}
}
// MARK: - Clear & Clean
extension ImageCache {
/**
Clear memory cache.
*/
@objc public func clearMemoryCache() {
memoryCache.removeAllObjects()
}
/**
Clear disk cache. This is an async operation.
*/
public func clearDiskCache() {
clearDiskCacheWithCompletionHandler(nil)
}
/**
Clear disk cache. This is an async operation.
- parameter completionHander: Called after the operation completes.
*/
public func clearDiskCacheWithCompletionHandler(completionHander: (()->())?) {
dispatch_async(ioQueue, { () -> Void in
do {
try self.fileManager.removeItemAtPath(self.diskCachePath)
} catch _ {
}
do {
try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
if let completionHander = completionHander {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHander()
})
}
})
}
/**
Clean expired disk cache. This is an async operation.
*/
@objc public func cleanExpiredDiskCache() {
cleanExpiredDiskCacheWithCompletionHander(nil)
}
/**
Clean expired disk cache. This is an async operation.
- parameter completionHandler: Called after the operation completes.
*/
public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) {
// Do things in cocurrent io queue
dispatch_async(ioQueue, { () -> Void in
let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath)
let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]
let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond)
var cachedFiles = [NSURL: [NSObject: AnyObject]]()
var URLsToDelete = [NSURL]()
var diskCacheSize: UInt = 0
if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL,
includingPropertiesForKeys: resourceKeys,
options: NSDirectoryEnumerationOptions.SkipsHiddenFiles,
errorHandler: nil) {
for fileURL in fileEnumerator.allObjects as! [NSURL] {
do {
let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys)
// If it is a Directory. Continue to next file URL.
if let isDirectory = resourceValues[NSURLIsDirectoryKey] as? NSNumber {
if isDirectory.boolValue {
continue
}
}
// If this file is expired, add it to URLsToDelete
if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate {
if modificationDate.laterDate(expiredDate) == expiredDate {
URLsToDelete.append(fileURL)
continue
}
}
if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize += fileSize.unsignedLongValue
cachedFiles[fileURL] = resourceValues
}
} catch _ {
}
}
}
for fileURL in URLsToDelete {
do {
try self.fileManager.removeItemAtURL(fileURL)
} catch _ {
}
}
if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
let targetSize = self.maxDiskCacheSize / 2
// Sort files by last modify date. We want to clean from the oldest files.
let sortedFiles = cachedFiles.keysSortedByValue({ (resourceValue1, resourceValue2) -> Bool in
if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate {
if let date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate {
return date1.compare(date2) == .OrderedAscending
}
}
// Not valid date information. This should not happen. Just in case.
return true
})
for fileURL in sortedFiles {
do {
try self.fileManager.removeItemAtURL(fileURL)
} catch {
}
URLsToDelete.append(fileURL)
if let fileSize = cachedFiles[fileURL]?[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize -= fileSize.unsignedLongValue
}
if diskCacheSize < targetSize {
break
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if URLsToDelete.count != 0 {
let cleanedHashes = URLsToDelete.map({ (url) -> String in
return url.lastPathComponent!
})
NSNotificationCenter.defaultCenter().postNotificationName(KingfisherDidCleanDiskCacheNotification, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
}
if let completionHandler = completionHandler {
completionHandler()
}
})
})
}
/**
Clean expired disk cache when app in background. This is an async operation.
In most cases, you should not call this method explicitly.
It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
*/
@objc public func backgroundCleanExpiredDiskCache() {
func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) {
UIApplication.sharedApplication().endBackgroundTask(task)
task = UIBackgroundTaskInvalid
}
var backgroundTask: UIBackgroundTaskIdentifier!
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in
endBackgroundTask(&backgroundTask!)
}
cleanExpiredDiskCacheWithCompletionHander { () -> () in
endBackgroundTask(&backgroundTask!)
}
}
}
// MARK: - Check cache status
public extension ImageCache {
/**
* Cache result for checking whether an image is cached for a key.
*/
public struct CacheCheckResult {
public let cached: Bool
public let cacheType: CacheType?
}
/**
Check whether an image is cached for a key.
- parameter key: Key for the image.
- returns: The check result.
*/
public func isImageCachedForKey(key: String) -> CacheCheckResult {
if memoryCache.objectForKey(key) != nil {
return CacheCheckResult(cached: true, cacheType: .Memory)
}
let filePath = cachePathForKey(key)
if fileManager.fileExistsAtPath(filePath) {
return CacheCheckResult(cached: true, cacheType: .Disk)
}
return CacheCheckResult(cached: false, cacheType: nil)
}
/**
Get the hash for the key. This could be used for matching files.
- parameter key: The key which is used for caching.
- returns: Corresponding hash.
*/
public func hashForKey(key: String) -> String {
return cacheFileNameForKey(key)
}
/**
Calculate the disk size taken by cache.
It is the total allocated size of the cached files in bytes.
- parameter completionHandler: Called with the calculated size when finishes.
*/
public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())?) {
dispatch_async(ioQueue, { () -> Void in
let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath)
let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey]
var diskCacheSize: UInt = 0
if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL,
includingPropertiesForKeys: resourceKeys,
options: NSDirectoryEnumerationOptions.SkipsHiddenFiles,
errorHandler: nil) {
for fileURL in fileEnumerator.allObjects as! [NSURL] {
do {
let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys)
// If it is a Directory. Continue to next file URL.
if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue {
if isDirectory {
continue
}
}
if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize += fileSize.unsignedLongValue
}
} catch _ {
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let completionHandler = completionHandler {
completionHandler(size: diskCacheSize)
}
})
})
}
}
// MARK: - Internal Helper
extension ImageCache {
func diskImageForKey(key: String, scale: CGFloat) -> UIImage? {
if let data = diskImageDataForKey(key) {
if let image = UIImage(data: data, scale: scale) {
return image
} else {
return nil
}
} else {
return nil
}
}
func diskImageDataForKey(key: String) -> NSData? {
let filePath = cachePathForKey(key)
return NSData(contentsOfFile: filePath)
}
func cachePathForKey(key: String) -> String {
let fileName = cacheFileNameForKey(key)
return (diskCachePath as NSString).stringByAppendingPathComponent(fileName)
}
func cacheFileNameForKey(key: String) -> String {
return key.kf_MD5()
}
}
extension UIImage {
var kf_imageCost: Int {
return Int(size.height * size.width * scale * scale)
}
}
private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8]
private let jpgHeaderIF: [UInt8] = [0xFF, 0xE0]
extension NSData {
var kf_imageFormat: ImageFormat {
var buffer = [UInt8](count: 8, repeatedValue: 0)
self.getBytes(&buffer, length: 8)
if buffer == pngHeader {
return .PNG
} else if buffer[0] == jpgHeaderSOI[0] &&
buffer[1] == jpgHeaderSOI[1] &&
buffer[2] == jpgHeaderIF[0] &&
buffer[3] == buffer[3] & jpgHeaderIF[1]
{
return .JPEG
}
return .Unknown
}
}
enum ImageFormat {
case Unknown, PNG, JPEG
}
extension Dictionary {
func keysSortedByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {
var array = Array(self)
array.sortInPlace {
let (_, lv) = $0
let (_, rv) = $1
return isOrderedBefore(lv, rv)
}
return array.map {
let (k, _) = $0
return k
}
}
}
| gpl-2.0 | 283b86f1f4bf95b554615b696e76beb4 | 39.668116 | 337 | 0.570365 | 5.680364 | false | false | false | false |
huhk345/LAFramework | LAMediator/Classes/LAMediator.swift | 1 | 4528 | //
// LAMediator.swift
// Pods
//
// Created by LakeR on 16/6/27.
//
//
import Foundation
import ObjectiveC
@objc public protocol LAModual {
}
@objc open class LAMediator : NSObject {
struct Singleton{
static var onceToken : Int = 0
static var instance : LAMediator?
}
static var __once: () = {
Singleton.instance = LAMediator()
}()
let MediatorDomain = "com.laker.mediator"
public enum MediatorErrorCode : Int {
case errorNoScheme = 100,errorNoTarget,errorNoAction,errorNotModualTarget,errorNilUrl,errorParameter
}
open class func shareInstance()->LAMediator{
_ = LAMediator.__once
return Singleton.instance!
}
// MARK: - swift API
open func performActionWithURL(_ url : URL?) throws -> AnyObject?{
guard let _ = url else{
throw errorWithCode(MediatorErrorCode.errorNilUrl)
}
let urlTypes : [[String : AnyObject]]? = (Bundle.main.infoDictionary?["CFBundleURLTypes"] as? [ [String : AnyObject] ])
var schemes : [String] = []
urlTypes?.forEach({ (urlType : [String : AnyObject]) in
(urlType["CFBundleURLSchemes"] as? [String])?.forEach({ (scheme : String) in
schemes.append(scheme)
})
})
if !schemes.contains(url!.scheme!) {
throw errorWithCode(MediatorErrorCode.errorNoScheme)
}
let components : URLComponents? = URLComponents(url: url!, resolvingAgainstBaseURL: false)
var parameter : [String:String] = [:]
components?.queryItems?.forEach({ (queryItem : URLQueryItem) in
parameter[queryItem.name] = queryItem.value
})
return try self.performTarget(url!.host, action: url!.path.replacingOccurrences(of: "/", with: ""), parameter: parameter as [String : AnyObject],fromURL: true)
}
open func performTarget(_ target : String?, action : String?, parameter : [String:AnyObject] ) throws -> AnyObject? {
return try self.performTarget(target, action: action, parameter: parameter, fromURL: false)
}
open func performTarget(_ target : String?, action : String?, parameter : [String:AnyObject] ,fromURL: Bool) throws -> AnyObject? {
guard let _ = target , let _ = action else{
throw errorWithCode(MediatorErrorCode.errorParameter)
}
let targetClass : AnyClass? = NSClassFromString(target!)
let target : AnyObject? = targetClass?.alloc()
guard let _ = target as? LAModual else{
throw errorWithCode(MediatorErrorCode.errorNotModualTarget)
}
let action : Selector? = NSSelectorFromString(action!+":param:")
guard let _ = target, let _ = action else {
throw errorWithCode(MediatorErrorCode.errorNoTarget)
}
if target?.responds(to: action!) == true {
var navController = UIApplication.shared.keyWindow?.rootViewController
if !(navController is UINavigationController) {
navController = navController?.navigationController
}
return target?.perform(action!,with: navController, with: parameter)?.takeUnretainedValue()
}
else{
let notFoundAction : Selector = NSSelectorFromString("notFound:")
if target?.responds(to: notFoundAction) == true {
return target?.perform(notFoundAction, with: parameter)?.takeUnretainedValue()
}
else{
throw errorWithCode(MediatorErrorCode.errorNoAction)
}
}
}
// MARK: - Objc wrapper API
open func objcPerformActionWithURL(_ url : URL?) -> AnyObject?{
do{
return try performActionWithURL(url)
}
catch let error as NSError {
return error
}
}
open func objcPerformTarget(_ target : String!, action : String!, parameter : [String:AnyObject]) -> AnyObject? {
do {
return try performTarget(target, action: action, parameter: parameter)
}
catch let error as NSError {
return error
}
}
// MARK: - help functions
func errorWithCode(_ code : MediatorErrorCode) -> NSError {
return NSError(domain: MediatorDomain, code:code.rawValue, userInfo: ["description":"\(code)"])
}
}
| mit | 90db89c4a44127365f39f1dd48ee07a1 | 31.811594 | 167 | 0.592314 | 4.981298 | false | false | false | false |
noprom/Cocktail-Pro | smartmixer/smartmixer/Ingridients/IngredientCollection.swift | 1 | 6121 | //
// MaterialCollection.swift
// smartmixer
//
// Created by 姚俊光 on 14-9-2.
// Copyright (c) 2014年 Smart Group. All rights reserved.
//
import UIKit
import CoreData
class IngredientCollection: UICollectionViewController {
//该导航需要设置的
var NavigationController:UINavigationController!
var icollectionView:UICollectionView!
@IBOutlet var navtitle:UINavigationItem!
//分类的id
var CatagoryId:Int = 0
//分类的显示名称
var catagoryName:String = ""
class func IngredientCollectionInit()->IngredientCollection{
let ingredientCollection = UIStoryboard(name: "Ingredients"+deviceDefine, bundle: nil).instantiateViewControllerWithIdentifier("ingredientCollection") as! IngredientCollection
return ingredientCollection
}
override func viewDidLoad() {
super.viewDidLoad()
if(navtitle != nil){
navtitle.title = catagoryName
}
if(deviceDefine==""){//添加向右滑动返回
let slideback = UISwipeGestureRecognizer()
slideback.addTarget(self, action: "SwipeToBack:")
slideback.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(slideback)
self.view.userInteractionEnabled = true
}
}
func SwipeToBack(sender:UISwipeGestureRecognizer){
self.NavigationController?.popViewControllerAnimated(true)
}
@IBAction func back(sender: UIBarButtonItem) {
self.NavigationController?.popViewControllerAnimated(true)
}
//处理向下向上滚动影藏控制栏
var lastPos:CGFloat = 0
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
lastPos = scrollView.contentOffset.y
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
if(deviceDefine != "" ){
let off = scrollView.contentOffset.y
if((off-lastPos)>50 && off>50){//向下了
lastPos = off
rootController.showOrhideToolbar(false)
}else if((lastPos-off)>50){
lastPos = off
rootController.showOrhideToolbar(true)
}
}
}
//@MARK:数据显示处理部分
func reloadData(){
_fetchedResultsController = nil
icollectionView.reloadData()
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
icollectionView = collectionView
let sectionInfo = self.fetchedResultsController.sections!
let item = sectionInfo[section]
return item.numberOfObjects
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ingredientThumb", forIndexPath: indexPath) as! IngredientThumb
if(CatagoryId==0){
let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Container
cell.SetContainer(item)
}else{
let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Ingridient
cell.SetContentData(item)
}
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if(CatagoryId==0){
let container = ContainerDetail.ContainerDetailInit()
let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Container
container.CurrentContainer = item
self.NavigationController.pushViewController(container, animated: true)
}else{
let materials = IngredientDetail.IngredientDetailInit()
let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Ingridient
materials.ingridient=item
self.NavigationController.pushViewController(materials, animated: true)
}
if(deviceDefine != ""){
rootController.showOrhideToolbar(false)
}
}
//@MARK:数据的读取
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
if(CatagoryId == 0){
fetchRequest.entity = NSEntityDescription.entityForName("Container", inManagedObjectContext: managedObjectContext)
fetchRequest.fetchBatchSize = 20
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]
}else{
fetchRequest.entity = NSEntityDescription.entityForName("Ingridient", inManagedObjectContext: managedObjectContext)
fetchRequest.fetchBatchSize = 30
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]
if(CatagoryId>0){
fetchRequest.predicate = NSPredicate(format: "categoryId == \(CatagoryId) ")
}else{
fetchRequest.predicate = NSPredicate(format: "(name CONTAINS[cd] '\(catagoryName)' OR nameEng CONTAINS[cd] '\(catagoryName)')")
}
}
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
_fetchedResultsController = aFetchedResultsController
do {
try _fetchedResultsController!.performFetch()
}catch{
abort()
}
// var error: NSError? = nil
// if !_fetchedResultsController!.performFetch(&error) {
// abort()
// }
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
}
| apache-2.0 | ff3a98a3eb0cb4516c7eda20822614b1 | 36.993671 | 183 | 0.642845 | 5.833819 | false | false | false | false |
cztatsumi-keisuke/TKKeyboardControl | TKKeyboardControl/Classes/TKKeyboardControl.swift | 1 | 34984 | //
// TKKeyboardControl.swift
//
// Created by 辰己 佳祐 on 2016/04/21.
// Copyright © 2016年 Keisuke Tatsumi. All rights reserved.
//
import UIKit
import Foundation
public typealias TKKeyboardDidMoveBlock = ((_ keyboardFrameInView: CGRect, _ firstResponder: UIResponder?, _ opening: Bool, _ closing: Bool) -> Void)?
private let frameKeyPath = "frame"
class TKKeyboardDidMoveBlockWrapper {
var closure: TKKeyboardDidMoveBlock
init(_ closure: TKKeyboardDidMoveBlock) {
self.closure = closure
}
}
class PreviousKeyboardRectWrapper {
var closure: CGRect
init(_ closure: CGRect) {
self.closure = closure
}
}
@inline(__always) func AnimationOptionsForCurve(_ curve: UIViewAnimationCurve) -> UIViewAnimationOptions {
return UIViewAnimationOptions(rawValue: UInt(curve.rawValue))
}
public extension UIView {
// MARK: - Public Properties
@objc dynamic var keyboardTriggerOffset: CGFloat {
get {
guard let triggerOffset: CGFloat = objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveTriggerOffset) as? CGFloat else {
return 0
}
return triggerOffset
}
set {
willChangeValue(forKey: "keyboardTriggerOffset")
objc_setAssociatedObject(self,
&AssociatedKeys.DescriptiveTriggerOffset,
newValue as CGFloat,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
didChangeValue(forKey: "keyboardTriggerOffset")
}
}
var keyboardWillRecede: Bool {
get {
guard let activityView = keyboardActiveView else { return false }
guard let activityViewSuperView = activityView.superview else { return false }
guard let panGesture = keyboardPanRecognizer else { return false }
let keyboardViewHeight = activityView.bounds.size.height
let keyboardWindowHeight = activityViewSuperView.bounds.size.height
let touchLocationInKeyboardWindow = panGesture.location(in: activityViewSuperView)
let thresholdHeight = keyboardWindowHeight - keyboardViewHeight - keyboardTriggerOffset + 44.0
let velocity = panGesture.velocity(in: activityView)
return touchLocationInKeyboardWindow.y >= thresholdHeight && velocity.y >= 0
}
}
// MARK: - Public Methods
func isKeyboardOpened() -> Bool {
return keyboardOpened
}
func addKeyboardPanning(frameBasedActionHandler: TKKeyboardDidMoveBlock? = nil, constraintBasedActionHandler: TKKeyboardDidMoveBlock? = nil) {
addKeyboardControl(panning: true, frameBasedActionHandler: frameBasedActionHandler, constraintBasedActionHandler: constraintBasedActionHandler)
}
func addKeyboardNonpanning(frameBasedActionHandler: TKKeyboardDidMoveBlock? = nil, constraintBasedActionHandler: TKKeyboardDidMoveBlock? = nil) {
addKeyboardControl(panning: false, frameBasedActionHandler: frameBasedActionHandler, constraintBasedActionHandler: constraintBasedActionHandler)
}
func keyboardFrameInView() -> CGRect {
if let activityView = keyboardActiveView {
let keyboardFrameInView = convert(activityView.frame, from: activityView.superview)
return keyboardFrameInView
}
else {
let keyboardFrameInView = CGRect(x: 0, y: UIScreen.main.bounds.size.height, width: 0, height: 0)
return keyboardFrameInView
}
}
func removeKeyboardControl() {
// Unregister for text input notifications
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextFieldTextDidBeginEditing, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextViewTextDidBeginEditing, object: nil)
// Unregister for keyboard notifications
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
// For the sake of 4.X compatibility
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "UIKeyboardWillChangeFrameNotification"), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "UIKeyboardDidChangeFrameNotification"), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil)
// Unregister any gesture recognizer
if let panRecognizer = keyboardPanRecognizer {
removeGestureRecognizer(panRecognizer)
}
// Release a few properties
frameBasedKeyboardDidMoveBlock = nil
constraintBasedKeyboardDidMoveBlock = nil
keyboardActiveInput = nil
keyboardActiveView = nil
keyboardPanRecognizer = nil
}
func hideKeyboard() {
hideKeyboard(isKeyboardViewHidden: false)
}
}
fileprivate let swizzling: (UIView.Type) -> () = { view in
let originalSelector = #selector(UIView.addSubview(_:))
let swizzledSelector = #selector(UIView.swizzled_addSubview(_:))
let originalMethod = class_getInstanceMethod(view, originalSelector)
let swizzledMethod = class_getInstanceMethod(view, swizzledSelector)
let didAddMethod = class_addMethod(view, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
if didAddMethod {
class_replaceMethod(view, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
}
extension UIView: UIGestureRecognizerDelegate {
fileprivate struct AssociatedKeys {
static var DescriptiveTriggerOffset = "DescriptiveTriggerOffset"
static var UIViewKeyboardTriggerOffset = "UIViewKeyboardTriggerOffset"
static var UIViewKeyboardDidMoveFrameBasedBlock = "UIViewKeyboardDidMoveFrameBasedBlock"
static var UIViewKeyboardDidMoveConstraintBasedBlock = "UIViewKeyboardDidMoveConstraintBasedBlock"
static var UIViewKeyboardActiveInput = "UIViewKeyboardActiveInput"
static var UIViewKeyboardActiveView = "UIViewKeyboardActiveView"
static var UIViewKeyboardPanRecognizer = "UIViewKeyboardPanRecognizer"
static var UIViewPreviousKeyboardRect = "UIViewPreviousKeyboardRect"
static var UIViewIsPanning = "UIViewIsPanning"
static var UIViewKeyboardOpened = "UIViewKeyboardOpened"
static var UIViewKeyboardFrameObserved = "UIViewKeyboardFrameObserved"
}
fileprivate var frameBasedKeyboardDidMoveBlock: TKKeyboardDidMoveBlock {
get {
guard let cl = objc_getAssociatedObject(self, &AssociatedKeys.UIViewKeyboardDidMoveFrameBasedBlock) as? TKKeyboardDidMoveBlockWrapper else {
return nil
}
return cl.closure
}
set {
willChangeValue(forKey: "frameBasedKeyboardDidMoveBlock")
objc_setAssociatedObject(self,
&AssociatedKeys.UIViewKeyboardDidMoveFrameBasedBlock,
TKKeyboardDidMoveBlockWrapper(newValue),
.OBJC_ASSOCIATION_RETAIN)
didChangeValue(forKey: "frameBasedKeyboardDidMoveBlock")
}
}
fileprivate var constraintBasedKeyboardDidMoveBlock: TKKeyboardDidMoveBlock {
get {
guard let cl = objc_getAssociatedObject(self, &AssociatedKeys.UIViewKeyboardDidMoveConstraintBasedBlock) as? TKKeyboardDidMoveBlockWrapper else {
return nil
}
return cl.closure
}
set {
willChangeValue(forKey: "constraintBasedKeyboardDidMoveBlock")
objc_setAssociatedObject(self,
&AssociatedKeys.UIViewKeyboardDidMoveConstraintBasedBlock,
TKKeyboardDidMoveBlockWrapper(newValue),
.OBJC_ASSOCIATION_RETAIN)
didChangeValue(forKey: "constraintBasedKeyboardDidMoveBlock")
}
}
fileprivate var keyboardActiveInput: UIResponder? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.UIViewKeyboardActiveInput) as? UIResponder
}
set {
if let newValue: UIResponder = newValue {
willChangeValue(forKey: "keyboardActiveInput")
objc_setAssociatedObject(self,
&AssociatedKeys.UIViewKeyboardActiveInput,
newValue as UIResponder,
.OBJC_ASSOCIATION_RETAIN)
didChangeValue(forKey: "keyboardActiveInput")
}
}
}
fileprivate var keyboardActiveView: UIView? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.UIViewKeyboardActiveView) as? UIView
}
set {
if let newValue: UIView = newValue {
willChangeValue(forKey: "keyboardActiveView")
objc_setAssociatedObject(self,
&AssociatedKeys.UIViewKeyboardActiveView,
newValue as UIView,
.OBJC_ASSOCIATION_RETAIN)
didChangeValue(forKey: "keyboardActiveView")
}
}
}
fileprivate var keyboardPanRecognizer: UIPanGestureRecognizer? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.UIViewKeyboardPanRecognizer) as? UIPanGestureRecognizer
}
set {
if let newValue: UIPanGestureRecognizer = newValue {
willChangeValue(forKey: "keyboardPanRecognizer")
objc_setAssociatedObject(self,
&AssociatedKeys.UIViewKeyboardPanRecognizer,
newValue as UIPanGestureRecognizer,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
didChangeValue(forKey: "keyboardPanRecognizer")
}
}
}
fileprivate var previousKeyboardRect: CGRect {
get {
guard let cl = objc_getAssociatedObject(self, &AssociatedKeys.UIViewPreviousKeyboardRect) as? PreviousKeyboardRectWrapper else {
return CGRect.zero
}
return cl.closure
}
set {
willChangeValue(forKey: "previousKeyboardRect")
objc_setAssociatedObject(self,
&AssociatedKeys.UIViewPreviousKeyboardRect,
PreviousKeyboardRectWrapper(newValue),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
didChangeValue(forKey: "previousKeyboardRect")
}
}
fileprivate var panning: Bool {
get {
guard let isPanningNumber: NSNumber = objc_getAssociatedObject(self, &AssociatedKeys.UIViewIsPanning) as? NSNumber else {
return false
}
return isPanningNumber.boolValue
}
set {
willChangeValue(forKey: "panning")
objc_setAssociatedObject(self,
&AssociatedKeys.UIViewIsPanning,
NSNumber(value: newValue as Bool),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
didChangeValue(forKey: "panning")
}
}
fileprivate var keyboardOpened: Bool {
get {
guard let isKeyboardOpenedNumber: NSNumber = objc_getAssociatedObject(self, &AssociatedKeys.UIViewKeyboardOpened) as? NSNumber else {
return false
}
return isKeyboardOpenedNumber.boolValue
}
set {
willChangeValue(forKey: "keyboardOpened")
objc_setAssociatedObject(self,
&AssociatedKeys.UIViewKeyboardOpened,
NSNumber(value: newValue as Bool),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
didChangeValue(forKey: "keyboardOpened")
}
}
fileprivate var keyboardFrameObserved: Bool {
get {
guard let isKeyboardFrameObservedNumber: NSNumber = objc_getAssociatedObject(self, &AssociatedKeys.UIViewKeyboardFrameObserved) as? NSNumber else {
return false
}
return isKeyboardFrameObservedNumber.boolValue
}
set {
willChangeValue(forKey: "keyboardFrameObserved")
objc_setAssociatedObject(self,
&AssociatedKeys.UIViewKeyboardFrameObserved,
NSNumber(value: newValue as Bool),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
didChangeValue(forKey: "keyboardFrameObserved")
}
}
fileprivate var safeAreaBottomInset: CGFloat {
if #available(iOS 11, *) {
return safeAreaInsets.bottom
}
return 0
}
fileprivate class func initializeControl() {
struct Static {
static var token: Int = 0
}
if self !== UIView.self {
return
}
swizzling(self)
}
// MARK: Add Keyboard Control
fileprivate func addKeyboardControl(panning: Bool, frameBasedActionHandler: TKKeyboardDidMoveBlock?, constraintBasedActionHandler: TKKeyboardDidMoveBlock?) {
// Avoid twice registration
removeKeyboardControl()
if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0 {
if panning && responds(to: #selector(getter: UIScrollView.keyboardDismissMode)) {
if let scrollView = self as? UIScrollView {
scrollView.keyboardDismissMode = .interactive
}
}
}
self.panning = panning
if let frameBasedActionHandler = frameBasedActionHandler {
frameBasedKeyboardDidMoveBlock = frameBasedActionHandler
}
if let constraintBasedActionHandler = constraintBasedActionHandler {
constraintBasedKeyboardDidMoveBlock = constraintBasedActionHandler
}
// Register for text input notifications
NotificationCenter.default.addObserver(self, selector: #selector(UIView.responderDidBecomeActive(_:)), name: NSNotification.Name.UITextFieldTextDidBeginEditing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(UIView.responderDidBecomeActive(_:)), name: NSNotification.Name.UITextViewTextDidBeginEditing, object: nil)
// Register for keyboard notifications
NotificationCenter.default.addObserver(self, selector: #selector(UIView.inputKeyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(UIView.inputKeyboardDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
// For the sake of 4.X compatibility
NotificationCenter.default.addObserver(self, selector: #selector(UIView.inputKeyboardWillChangeFrame(_:)), name: NSNotification.Name(rawValue: "UIKeyboardWillChangeFrameNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(UIView.inputKeyboardDidChangeFrame), name: NSNotification.Name(rawValue: "UIKeyboardDidChangeFrameNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(UIView.inputKeyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(UIView.inputKeyboardDidHide), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}
// MARK: - Input Notifications
@objc fileprivate func responderDidBecomeActive(_ notification: Notification) {
keyboardActiveInput = notification.object as? UIResponder
if keyboardActiveInput?.inputAccessoryView == nil {
let textField = keyboardActiveInput as! UITextField
if textField.responds(to: #selector(getter: UIResponder.inputAccessoryView)) {
let nullView: UIView = UIView(frame: CGRect.zero)
nullView.backgroundColor = .clear
textField.inputAccessoryView = nullView
}
keyboardActiveInput = textField as UIResponder
inputKeyboardDidShow()
}
}
// MARK: - Keyboard Notifications
@objc fileprivate func inputKeyboardWillShow(_ notification: Notification) {
guard let userInfo = (notification as NSNotification).userInfo else { return }
guard let keyboardEndFrameWindow: CGRect = ((userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue) else { return }
guard let keyboardTransitionDuration: Double = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double else { return }
var keyboardTransitionAnimationCurve: UIViewAnimationCurve = .easeInOut
if let curveIntValue = (userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.intValue,
let curve = UIViewAnimationCurve(rawValue: curveIntValue << 16) {
keyboardTransitionAnimationCurve = curve
}
keyboardActiveView?.isHidden = false
keyboardOpened = true
let keyboardEndFrameView = convert(keyboardEndFrameWindow, from: nil)
let constraintBasedKeyboardDidMoveBlockCalled = (constraintBasedKeyboardDidMoveBlock != nil && !keyboardEndFrameView.isNull)
if constraintBasedKeyboardDidMoveBlockCalled {
constraintBasedKeyboardDidMoveBlock?(keyboardEndFrameWindow, keyboardActiveInput, true, false)
}
UIView.animate(withDuration: keyboardTransitionDuration,
delay: 0,
options: [AnimationOptionsForCurve(keyboardTransitionAnimationCurve), .beginFromCurrentState],
animations: {
if constraintBasedKeyboardDidMoveBlockCalled {
self.layoutIfNeeded()
}
if self.frameBasedKeyboardDidMoveBlock != nil && !keyboardEndFrameView.isNull {
self.frameBasedKeyboardDidMoveBlock?(keyboardEndFrameView, self.keyboardActiveInput, true, false)
}
}) { _ in
if self.panning {
// remove before recognizer
if let panRecognizer = self.keyboardPanRecognizer {
self.removeGestureRecognizer(panRecognizer)
}
self.keyboardPanRecognizer = UIPanGestureRecognizer(target: self, action: #selector(UIView.panGestureDidChange(_:)))
self.keyboardPanRecognizer?.delegate = self
self.keyboardPanRecognizer?.cancelsTouchesInView = false
guard let panGesture = self.keyboardPanRecognizer else { return }
self.addGestureRecognizer(panGesture)
}
}
}
@objc fileprivate func inputKeyboardDidShow() {
keyboardActiveView = findInputSetHostView()
keyboardActiveView?.isHidden = false
if keyboardActiveView == nil {
keyboardActiveInput = recursiveFindFirstResponder(self)
keyboardActiveView = findInputSetHostView()
keyboardActiveView?.isHidden = false
}
if !keyboardFrameObserved {
keyboardActiveView?.addObserver(self, forKeyPath: frameKeyPath, options: .new, context: nil)
keyboardFrameObserved = true
}
}
@objc fileprivate func inputKeyboardWillChangeFrame(_ notification: Notification) {
guard let userInfo = (notification as NSNotification).userInfo else { return }
guard let keyboardEndFrameWindow: CGRect = ((userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue) else { return }
guard let keyboardTransitionDuration: Double = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double else { return }
var keyboardTransitionAnimationCurve: UIViewAnimationCurve = .easeInOut
if let curveIntValue = (userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.intValue,
let curve = UIViewAnimationCurve(rawValue: curveIntValue << 16) {
keyboardTransitionAnimationCurve = curve
}
let keyboardEndFrameView = convert(keyboardEndFrameWindow, from: nil)
let constraintBasedKeyboardDidMoveBlockCalled = (constraintBasedKeyboardDidMoveBlock != nil && !keyboardEndFrameView.isNull)
if constraintBasedKeyboardDidMoveBlockCalled {
constraintBasedKeyboardDidMoveBlock?(keyboardEndFrameWindow, keyboardActiveInput, false, false)
}
UIView.animate(withDuration: keyboardTransitionDuration,
delay: 0,
options: [AnimationOptionsForCurve(keyboardTransitionAnimationCurve), .beginFromCurrentState],
animations: {
if constraintBasedKeyboardDidMoveBlockCalled {
self.layoutIfNeeded()
}
if self.frameBasedKeyboardDidMoveBlock != nil && !keyboardEndFrameView.isNull {
self.frameBasedKeyboardDidMoveBlock?(keyboardEndFrameView, self.keyboardActiveInput, false, false)
}
}, completion:nil)
}
@objc fileprivate func inputKeyboardDidChangeFrame() {
// Nothing to see here
}
@objc fileprivate func inputKeyboardWillHide(_ notification: Notification) {
guard let userInfo = (notification as NSNotification).userInfo else { return }
guard let keyboardEndFrameWindow: CGRect = ((userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue) else { return }
guard let keyboardTransitionDuration: Double = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double else { return }
var keyboardTransitionAnimationCurve: UIViewAnimationCurve = .easeInOut
if let curveIntValue = (userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.intValue,
let curve = UIViewAnimationCurve(rawValue: curveIntValue << 16) {
keyboardTransitionAnimationCurve = curve
}
var keyboardEndFrameView = convert(keyboardEndFrameWindow, from: nil)
keyboardEndFrameView.origin.y -= safeAreaBottomInset
let constraintBasedKeyboardDidMoveBlockCalled = (constraintBasedKeyboardDidMoveBlock != nil && !keyboardEndFrameView.isNull)
if constraintBasedKeyboardDidMoveBlockCalled {
constraintBasedKeyboardDidMoveBlock?(keyboardEndFrameWindow, keyboardActiveInput, false, true)
}
UIView.animate(withDuration: keyboardTransitionDuration,
delay: 0,
options: [AnimationOptionsForCurve(keyboardTransitionAnimationCurve), .beginFromCurrentState],
animations: {
if constraintBasedKeyboardDidMoveBlockCalled {
self.layoutIfNeeded()
}
if self.frameBasedKeyboardDidMoveBlock != nil && !keyboardEndFrameView.isNull {
self.frameBasedKeyboardDidMoveBlock?(keyboardEndFrameView, self.keyboardActiveInput, false, true)
}
}) { _ in
if let panRecognizer = self.keyboardPanRecognizer {
self.removeGestureRecognizer(panRecognizer)
}
self.keyboardPanRecognizer = nil
if self.keyboardFrameObserved {
self.keyboardActiveView?.removeObserver(self, forKeyPath: frameKeyPath)
self.keyboardFrameObserved = false
}
}
}
@objc fileprivate func inputKeyboardDidHide() {
keyboardActiveView?.isHidden = false
keyboardActiveView?.isUserInteractionEnabled = true
keyboardActiveView = nil
keyboardActiveInput = nil
keyboardOpened = false
}
fileprivate func hideKeyboard(isKeyboardViewHidden: Bool) {
if keyboardActiveView != nil {
keyboardActiveView?.isHidden = isKeyboardViewHidden
keyboardActiveView?.isUserInteractionEnabled = false
keyboardActiveInput?.resignFirstResponder()
}
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath else { return }
if keyPath == frameKeyPath && object as? UIView == keyboardActiveView {
guard let keyboardEndFrameWindow = (object as? UIView)?.frame else { return }
guard var keyboardEndFrameView = keyboardActiveView?.frame else { return }
keyboardEndFrameView.origin.y = keyboardEndFrameWindow.origin.y
if keyboardEndFrameView.origin.y > UIScreen.main.bounds.height - safeAreaBottomInset {
keyboardEndFrameView.origin.y = UIScreen.main.bounds.height - safeAreaBottomInset
}
if keyboardEndFrameView.equalTo(previousKeyboardRect) {
return
}
guard let activityView = keyboardActiveView else { return }
if !activityView.isHidden && !keyboardEndFrameView.isNull {
if frameBasedKeyboardDidMoveBlock != nil {
frameBasedKeyboardDidMoveBlock?(keyboardEndFrameView, keyboardActiveView, false, false)
}
if constraintBasedKeyboardDidMoveBlock != nil {
constraintBasedKeyboardDidMoveBlock?(keyboardEndFrameWindow, keyboardActiveInput, false, false)
layoutIfNeeded()
}
}
previousKeyboardRect = keyboardEndFrameView
}
}
// MARK: - Touches Management
@objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == keyboardPanRecognizer || otherGestureRecognizer == keyboardPanRecognizer {
return true
}
else {
return false
}
}
@objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer == keyboardPanRecognizer {
guard let touchView = touch.view else { return true }
return (!touchView.isFirstResponder || (isKind(of: UITextView.self) && isEqual(touchView)))
}
else {
return true
}
}
@objc fileprivate func panGestureDidChange(_ gesture: UIPanGestureRecognizer) {
if keyboardActiveView == nil || keyboardActiveInput == nil || keyboardActiveView?.isHidden ?? false {
keyboardActiveInput = recursiveFindFirstResponder(self)
keyboardActiveView = findInputSetHostView()
keyboardActiveView?.isHidden = false
}
else {
keyboardActiveView?.isHidden = false
}
guard let activityView = keyboardActiveView else { return }
guard let activityViewSuperView = activityView.superview else { return }
let keyboardViewHeight: CGFloat = activityView.bounds.size.height
let keyboardWindowHeight: CGFloat = activityViewSuperView.bounds.size.height
let touchLocationInKeyboardWindow = gesture.location(in: activityView.superview)
if touchLocationInKeyboardWindow.y > keyboardWindowHeight - keyboardViewHeight - keyboardTriggerOffset {
activityView.isUserInteractionEnabled = false
}
else {
activityView.isUserInteractionEnabled = true
}
switch gesture.state {
case .began:
gesture.maximumNumberOfTouches = gesture.numberOfTouches
break
case .changed:
var newKeyboardViewFrame = activityView.frame
newKeyboardViewFrame.origin.y = touchLocationInKeyboardWindow.y + keyboardTriggerOffset
newKeyboardViewFrame.origin.y = min(newKeyboardViewFrame.origin.y, keyboardWindowHeight)
newKeyboardViewFrame.origin.y = max(newKeyboardViewFrame.origin.y, keyboardWindowHeight - keyboardViewHeight)
if (keyboardActiveInput?.isFirstResponder ?? false) && newKeyboardViewFrame.origin.y > UIScreen.main.bounds.height - safeAreaBottomInset {
newKeyboardViewFrame.origin.y = UIScreen.main.bounds.height - safeAreaBottomInset
}
if newKeyboardViewFrame.origin.y != keyboardActiveView?.frame.origin.y {
UIView.animate(withDuration: 0,
delay: 0,
options: .beginFromCurrentState,
animations: {
activityView.frame = newKeyboardViewFrame
}, completion: nil)
}
break
case .ended, .cancelled:
let thresholdHeight = keyboardWindowHeight - keyboardViewHeight - keyboardTriggerOffset + 44
let velocity = gesture.velocity(in: keyboardActiveView)
var shouldRecede = Bool()
if touchLocationInKeyboardWindow.y < thresholdHeight || velocity.y < 0 {
shouldRecede = false
}
else {
shouldRecede = true
}
var newKeyboardViewFrame = activityView.frame
newKeyboardViewFrame.origin.y = !shouldRecede ? keyboardWindowHeight - keyboardViewHeight: keyboardWindowHeight
UIView.animate(withDuration: 0.25,
delay: 0,
options: [.curveEaseOut, .beginFromCurrentState],
animations: {
activityView.frame = newKeyboardViewFrame
}, completion: { _ in
activityView.isUserInteractionEnabled = !shouldRecede
if shouldRecede {
self.hideKeyboard(isKeyboardViewHidden: true)
}
})
gesture.maximumNumberOfTouches = LONG_MAX
break
default:
break
}
}
// MARK: - Internal Methods
fileprivate func recursiveFindFirstResponder(_ view: UIView) -> UIView? {
if view.isFirstResponder {
return view
}
var found: UIView? = nil
for v in view.subviews {
found = recursiveFindFirstResponder(v)
if found != nil {
break
}
}
return found
}
fileprivate func findInputSetHostView() -> UIView? {
if #available(iOS 9, *) {
guard let remoteKeyboardWindowClass = NSClassFromString("UIRemoteKeyboardWindow") else { return nil }
guard let inputSetHostViewClass = NSClassFromString("UIInputSetHostView") else { return nil }
for window in UIApplication.shared.windows {
if window.isKind(of: remoteKeyboardWindowClass) {
for subView in window.subviews {
if subView.isKind(of: inputSetHostViewClass) {
for subSubView in subView.subviews {
if subSubView.isKind(of: inputSetHostViewClass) {
return subSubView
}
}
}
}
}
}
}
else {
return keyboardActiveInput?.inputAccessoryView?.superview
}
return nil
}
@objc fileprivate func swizzled_addSubview(_ subView: UIView) {
if subView.inputAccessoryView == nil {
if subView.isKind(of: UITextField.self) {
let textField = subView as! UITextField
if textField.responds(to: #selector(getter: UIResponder.inputAccessoryView)) {
let nullView: UIView = UIView(frame: .zero)
nullView.backgroundColor = .clear
textField.inputAccessoryView = nullView
}
}
else if subView.isKind(of: UITextView.self) {
let textView = subView as! UITextView
if textView.responds(to: #selector(getter: UIResponder.inputAccessoryView)) {
let nullView: UIView = UIView(frame: .zero)
nullView.backgroundColor = .clear
textView.inputAccessoryView = nullView
}
}
}
swizzled_addSubview(subView)
}
}
extension UIApplication {
private static let runOnce: Void = {
UIView.initializeControl()
}()
override open var next: UIResponder? {
// Called before applicationDidFinishLaunching
UIApplication.runOnce
return super.next
}
}
| mit | af8aee90e5a409a6151c70c3d5adf1de | 41.288996 | 205 | 0.613874 | 6.28107 | false | false | false | false |
hakan4/LineGraphKit | LineGraphKit/LineGraphKit/Classes/ViewElements/LineLayer.swift | 1 | 2415 | //
// LineLayer.swift
// GraphKit
//
// Created by Håkan Andersson on 27/06/15.
// Copyright (c) 2015 Fineline. All rights reserved.
//
import UIKit
class LineLayer: CAShapeLayer {
final var animationDuration: Double! = 1
fileprivate final var points: [Point]!
init(points: [Point]) {
super.init()
fillColor = UIColor.clear.cgColor
self.points = points
self.path = createPath()
contentsScale = UIScreen.main.scale
setNeedsDisplay()
}
override init(layer: Any) {
super.init(layer: layer)
if let sliceLayer = layer as? LineLayer {
self.animationDuration = sliceLayer.animationDuration
self.points = sliceLayer.points
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func action(forKey event: String) -> CAAction? {
if event == "strokeEnd" {
return makeAnimationForKey(event)
}
return super.action(forKey: event)
}
override class func needsDisplay(forKey key: String) -> Bool {
if key == "strokeEnd" {
return true
}
return super.needsDisplay(forKey: key)
}
fileprivate func createPath() -> CGPath {
let path = CGMutablePath()
var mutablePoints = points
mutablePoints?.remove(at: 0)
if var mutablePoints = mutablePoints {
let initialPoint = mutablePoints.remove(at: 0)
path.move(to: CGPoint(x: initialPoint.x, y: initialPoint.y))
for point in mutablePoints {
path.addLine(to: CGPoint(x: point.x, y: point.y))
}
}
return path
}
fileprivate func makeAnimationForKey(_ key: String) -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: key)
animation.fromValue = self.presentation()?.value(forKeyPath: key)
animation.toValue = self.value(forKeyPath: key)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.duration = animationDuration
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
return animation
}
func drawLine() {
strokeEnd = 0.0
}
func removeLine() {
strokeEnd = 1.0
}
}
| mit | 72fc50223dd4851406568a6938b5c11c | 27.738095 | 99 | 0.60232 | 4.696498 | false | false | false | false |
Rodeo314/navdtools | src/misc/voices.swift | 1 | 1420 | import AppKit
// filter text-to-speech voices (only show voices w/high-quality available)
for i in NSSpeechSynthesizer.availableVoices()
{
var attributes = NSSpeechSynthesizer.attributesForVoice(i)
var identifier = String(attributes[NSVoiceIdentifier]!)
var name = String(attributes[NSVoiceName]!)
var gender = String(attributes[NSVoiceGender]!)
var age = String(attributes[NSVoiceAge]!)
var locale = String(attributes[NSVoiceLocaleIdentifier]!)
var hasRelative = attributes["VoiceRelativeDesirability"]
var intRelative = Int("0")
var valRelative = 0
if (hasRelative != nil)
{
intRelative = Int(String(hasRelative!))
if (intRelative != nil)
{
valRelative = intRelative!
}
}
while (name.utf8.count < 10)
{
name += " "
}
for _ in (1...11) // VoiceGender
{
gender.removeAtIndex(gender.startIndex)
}
while (age.utf8.count < 3)
{
age = " " + age
}
while (locale.utf8.count < 8)
{
locale += " "
}
if (hasRelative != nil && intRelative != nil && valRelative >= 13400)
{
print(identifier)
print(" -> " + name, gender, age, locale, separator: "\t")
print(" -> " + String(valRelative))
print("")
}
else
{
print(name + ":", String(valRelative))
print("")
}
}
| gpl-2.0 | 0b11f94d9e735d507972434bdcc1bf67 | 26.843137 | 75 | 0.572535 | 3.977591 | false | false | false | false |
APUtils/APExtensions | APExtensions/Classes/Core/_Extensions/_UIKit/UINavigationController+Utils.swift | 1 | 3812 | //
// UINavigationController+Utils.swift
// APExtensions
//
// Created by Anton Plebanovich on 6/6/17.
// Copyright © 2019 Anton Plebanovich. All rights reserved.
//
import UIKit
public extension UINavigationController {
/// Root view controller
var rootViewController: UIViewController {
return viewControllers.first!
}
/// Pushes view controller animated
func pushViewController(_ viewController: UIViewController) {
pushViewController(viewController, animated: true)
}
/// Pops view controller animated
func popViewController() {
popViewController(animated: true)
}
}
// ******************************* MARK: - Completion
public extension UINavigationController {
/// Pushes view controller with completion
func pushViewController(_ viewController: UIViewController, animated: Bool = true, completion: (() -> Void)?) {
pushViewController(viewController, animated: animated)
handleCompletion(animated: animated, completion: completion)
}
/// Pops view controller with completion
func popViewController(animated: Bool = true, completion: (() -> Void)?) {
popViewController(animated: animated)
handleCompletion(animated: animated, completion: completion)
}
/// Pops to view controller with completion
func popToViewController(viewController: UIViewController, animated: Bool = true, completion: (() -> Void)?) {
popToViewController(viewController, animated: animated)
handleCompletion(animated: animated, completion: completion)
}
/// Pops view controller if it present in navigation stack and all overlaying view controllers.
/// Do nothing if view controller is not in navigation stack.
func pop(viewController: UIViewController, animated: Bool = true, completion: (() -> Void)?) {
if viewControllers.last == viewController {
// Last controller in stack. Just dismiss it.
popViewController(animated: animated, completion: completion)
} else {
// Not last controller in stack. Pop view controller together with overlaying controllers.
guard let index = viewControllers.firstIndex(of: viewController) else {
completion?()
return
}
let newViewControllers = Array(viewControllers.prefix(upTo: index))
setViewControllers(newViewControllers, animated: animated, completion: completion)
}
}
/// Pops to root with completion
func popToRootViewController(animated: Bool = true, completion: (() -> Void)?) {
popToRootViewController(animated: animated)
handleCompletion(animated: animated, completion: completion)
}
/// Replaces view controllers with completion
func setViewControllers(_ vcs: [UIViewController], animated: Bool = true, completion: (() -> Void)?) {
setViewControllers(vcs, animated: animated)
handleCompletion(animated: animated, completion: completion)
}
/// Replaces last view controller with completion
func replaceLast(_ vc: UIViewController, animated: Bool = true, completion: (() -> Void)?) {
var vcs = viewControllers
vcs.removeLast()
vcs.append(vc)
setViewControllers(vcs, animated: animated, completion: completion)
}
private func handleCompletion(animated: Bool = true, completion: (() -> Void)?) {
if animated, let coordinator = transitionCoordinator {
let success = coordinator.animate(alongsideTransition: nil, completion: { _ in completion?() })
if !success {
completion?()
}
} else {
completion?()
}
}
}
| mit | e7cd93265ac2c3366d22de756ab685ba | 37.11 | 115 | 0.649961 | 5.637574 | false | false | false | false |
hejunbinlan/Carlos | Carlos/Transformers.swift | 2 | 1505 | import Foundation
import MapKit
/**
NSDateFormatter extension to conform to the TwoWayTransformer protocol
This class transforms from NSDate to String (transform) and viceversa (inverseTransform)
*/
extension NSDateFormatter: TwoWayTransformer {
public typealias TypeIn = NSDate
public typealias TypeOut = String
public func transform(val: TypeIn) -> TypeOut? {
return stringFromDate(val)
}
public func inverseTransform(val: TypeOut) -> TypeIn? {
return dateFromString(val)
}
}
/**
NSNumberFormatter extension to conform to the TwoWayTransformer protocol
This class transforms from NSNumber to String (transform) and viceversa (inverseTransform)
*/
extension NSNumberFormatter: TwoWayTransformer {
public typealias TypeIn = NSNumber
public typealias TypeOut = String
public func transform(val: TypeIn) -> TypeOut? {
return stringFromNumber(val)
}
public func inverseTransform(val: TypeOut) -> TypeIn? {
return numberFromString(val)
}
}
/**
MKDistanceFormatter extension to conform to the TwoWayTransformer protocol
This class transforms from CLLocationDistance to String (transform) and viceversa (inverseTransform)
*/
extension MKDistanceFormatter: TwoWayTransformer {
public typealias TypeIn = CLLocationDistance
public typealias TypeOut = String
public func transform(val: TypeIn) -> TypeOut? {
return stringFromDistance(val)
}
public func inverseTransform(val: TypeOut) -> TypeIn? {
return distanceFromString(val)
}
} | mit | 11980d37191b47c407783a4147b971f3 | 25.892857 | 100 | 0.762791 | 4.777778 | false | false | false | false |
iossocket/BabyMoment | BabyMoment/PhotoManger/XLAlbumCell.swift | 1 | 1711 | //
// XLAlbumCell.swift
// BabyMoment
//
// Created by Xueliang Zhu on 8/24/16.
// Copyright © 2016 kotlinchina. All rights reserved.
//
import UIKit
import Photos
class XLAlbumCell: UITableViewCell {
@IBOutlet weak var albumNameLabel: UILabel!
@IBOutlet weak var albumPhotoCountLabel: UILabel!
@IBOutlet weak var albumCoverImageView: UIImageView!
}
extension XLAlbumCell {
func configCell(albumTitle: String, assetCollection: PHAssetCollection) {
albumNameLabel.text = albumTitle
let options = PHFetchOptions()
options.sortDescriptors = [
NSSortDescriptor(key: "creationDate", ascending: true)
]
let fetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: options)
albumPhotoCountLabel.text = "\(fetchResult.count) photos"
let request = PHImageRequestOptions()
request.deliveryMode = .Opportunistic
request.resizeMode = .Exact
let scale = UIScreen.mainScreen().scale
let targetSize = CGSize(width: 70 * scale, height: 70 * scale)
let manager = PHImageManager.defaultManager()
if tag != 0 {
manager.cancelImageRequest(PHImageRequestID(tag))
}
if fetchResult.count > 0 {
tag = Int(manager.requestImageForAsset(fetchResult.firstObject as! PHAsset, targetSize: targetSize, contentMode: PHImageContentMode.AspectFill, options: request) { (image, _) -> Void in
self.albumCoverImageView.image = image
})
} else {
self.albumCoverImageView.image = UIImage(named: "DefaultCoverImage")
}
}
}
| mit | a5e11633e7260ea3963bc965e0bb3731 | 31.884615 | 197 | 0.645614 | 5 | false | false | false | false |
mrdepth/EVEUniverse | Neocom/Neocom/Utility/Views/SearchControllerWrapper.swift | 2 | 2069 | //
// SearchControllerWrapper.swift
// Neocom
//
// Created by Artem Shimanski on 5/2/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Combine
class SearchResultsControllerWrapper<Content: View>: UIHostingController<Content> {
override var navigationController: UINavigationController? {
presentingViewController?.navigationController
}
}
class SearchControllerWrapper<Results, Content: View, P: Publisher>: UIViewController, UISearchResultsUpdating where P.Failure == Never, P.Output == Results {
var search: (String) -> P
var content: (Results?) -> Content
var searchResults: UIHostingController<Content>
var searchController: UISearchController
private var subscription: AnyCancellable?
init(search: @escaping (String) -> P, content: @escaping (Results?) -> Content) {
self.search = search
self.content = content
searchResults = SearchResultsControllerWrapper(rootView: content(nil))
searchController = UISearchController(searchResultsController: searchResults)
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError()
}
@Published private var searchString: String = ""
override func didMove(toParent parent: UIViewController?) {
guard let parent = parent else {return}
parent.definesPresentationContext = true
parent.navigationItem.searchController = searchController
subscription = $searchString.debounce(for: .seconds(0.5), scheduler: RunLoop.main)
.flatMap {[search] in search($0)}
.receive(on: RunLoop.main)
.map{[content] in content($0)}
.sink { [searchResults] results in
searchResults.rootView = results
}
searchController.searchResultsUpdater = self
}
func updateSearchResults(for searchController: UISearchController) {
searchString = searchController.searchBar.searchTextField.text ?? ""
}
}
| lgpl-2.1 | 74480d752a81afb59c308499824f4736 | 34.050847 | 158 | 0.6794 | 5.289003 | false | false | false | false |
alblue/swift | stdlib/public/SDK/Foundation/JSONEncoder.swift | 3 | 114078 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary`
/// containing `Encodable` values (in which case it should be exempt from key conversion strategies).
///
/// NOTE: The architecture and environment check is due to a bug in the current (2018-08-08) Swift 4.2
/// runtime when running on i386 simulator. The issue is tracked in https://bugs.swift.org/browse/SR-8276
/// Making the protocol `internal` instead of `fileprivate` works around this issue.
/// Once SR-8276 is fixed, this check can be removed and the protocol always be made fileprivate.
#if arch(i386) || arch(arm)
internal protocol _JSONStringDictionaryEncodableMarker { }
#else
fileprivate protocol _JSONStringDictionaryEncodableMarker { }
#endif
extension Dictionary : _JSONStringDictionaryEncodableMarker where Key == String, Value: Encodable { }
/// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary`
/// containing `Decodable` values (in which case it should be exempt from key conversion strategies).
///
/// The marker protocol also provides access to the type of the `Decodable` values,
/// which is needed for the implementation of the key conversion strategy exemption.
///
/// NOTE: Please see comment above regarding SR-8276
#if arch(i386) || arch(arm)
internal protocol _JSONStringDictionaryDecodableMarker {
static var elementType: Decodable.Type { get }
}
#else
fileprivate protocol _JSONStringDictionaryDecodableMarker {
static var elementType: Decodable.Type { get }
}
#endif
extension Dictionary : _JSONStringDictionaryDecodableMarker where Key == String, Value: Decodable {
static var elementType: Decodable.Type { return Value.self }
}
//===----------------------------------------------------------------------===//
// JSON Encoder
//===----------------------------------------------------------------------===//
/// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON.
open class JSONEncoder {
// MARK: Options
/// The formatting of the output JSON data.
public struct OutputFormatting : OptionSet {
/// The format's default value.
public let rawValue: UInt
/// Creates an OutputFormatting value with the given raw value.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
/// Produce human-readable JSON with indented output.
public static let prettyPrinted = OutputFormatting(rawValue: 1 << 0)
/// Produce JSON with dictionary keys sorted in lexicographic order.
@available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
public static let sortedKeys = OutputFormatting(rawValue: 1 << 1)
}
/// The strategy to use for encoding `Date` values.
public enum DateEncodingStrategy {
/// Defer to `Date` for choosing an encoding. This is the default strategy.
case deferredToDate
/// Encode the `Date` as a UNIX timestamp (as a JSON number).
case secondsSince1970
/// Encode the `Date` as UNIX millisecond timestamp (as a JSON number).
case millisecondsSince1970
/// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Encode the `Date` as a string formatted by the given formatter.
case formatted(DateFormatter)
/// Encode the `Date` as a custom value encoded by the given closure.
///
/// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place.
case custom((Date, Encoder) throws -> Void)
}
/// The strategy to use for encoding `Data` values.
public enum DataEncodingStrategy {
/// Defer to `Data` for choosing an encoding.
case deferredToData
/// Encoded the `Data` as a Base64-encoded string. This is the default strategy.
case base64
/// Encode the `Data` as a custom value encoded by the given closure.
///
/// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place.
case custom((Data, Encoder) throws -> Void)
}
/// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN).
public enum NonConformingFloatEncodingStrategy {
/// Throw upon encountering non-conforming values. This is the default strategy.
case `throw`
/// Encode the values using the given representation strings.
case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String)
}
/// The strategy to use for automatically changing the value of keys before encoding.
public enum KeyEncodingStrategy {
/// Use the keys specified by each type. This is the default strategy.
case useDefaultKeys
/// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to JSON payload.
///
/// Capital characters are determined by testing membership in `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` (Unicode General Categories Lu and Lt).
/// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences.
///
/// Converting from camel case to snake case:
/// 1. Splits words at the boundary of lower-case to upper-case
/// 2. Inserts `_` between words
/// 3. Lowercases the entire string
/// 4. Preserves starting and ending `_`.
///
/// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`.
///
/// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted.
case convertToSnakeCase
/// Provide a custom conversion to the key in the encoded JSON from the keys specified by the encoded types.
/// The full path to the current encoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before encoding.
/// If the result of the conversion is a duplicate key, then only one value will be present in the result.
case custom((_ codingPath: [CodingKey]) -> CodingKey)
fileprivate static func _convertToSnakeCase(_ stringKey: String) -> String {
guard !stringKey.isEmpty else { return stringKey }
var words : [Range<String.Index>] = []
// The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase
//
// myProperty -> my_property
// myURLProperty -> my_url_property
//
// We assume, per Swift naming conventions, that the first character of the key is lowercase.
var wordStart = stringKey.startIndex
var searchRange = stringKey.index(after: wordStart)..<stringKey.endIndex
// Find next uppercase character
while let upperCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) {
let untilUpperCase = wordStart..<upperCaseRange.lowerBound
words.append(untilUpperCase)
// Find next lowercase character
searchRange = upperCaseRange.lowerBound..<searchRange.upperBound
guard let lowerCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else {
// There are no more lower case letters. Just end here.
wordStart = searchRange.lowerBound
break
}
// Is the next lowercase letter more than 1 after the uppercase? If so, we encountered a group of uppercase letters that we should treat as its own word
let nextCharacterAfterCapital = stringKey.index(after: upperCaseRange.lowerBound)
if lowerCaseRange.lowerBound == nextCharacterAfterCapital {
// The next character after capital is a lower case character and therefore not a word boundary.
// Continue searching for the next upper case for the boundary.
wordStart = upperCaseRange.lowerBound
} else {
// There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character.
let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound)
words.append(upperCaseRange.lowerBound..<beforeLowerIndex)
// Next word starts at the capital before the lowercase we just found
wordStart = beforeLowerIndex
}
searchRange = lowerCaseRange.upperBound..<searchRange.upperBound
}
words.append(wordStart..<searchRange.upperBound)
let result = words.map({ (range) in
return stringKey[range].lowercased()
}).joined(separator: "_")
return result
}
}
/// The output format to produce. Defaults to `[]`.
open var outputFormatting: OutputFormatting = []
/// The strategy to use in encoding dates. Defaults to `.deferredToDate`.
open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate
/// The strategy to use in encoding binary data. Defaults to `.base64`.
open var dataEncodingStrategy: DataEncodingStrategy = .base64
/// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`.
open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw
/// The strategy to use for encoding keys. Defaults to `.useDefaultKeys`.
open var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys
/// Contextual user-provided information for use during encoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the encoding hierarchy.
fileprivate struct _Options {
let dateEncodingStrategy: DateEncodingStrategy
let dataEncodingStrategy: DataEncodingStrategy
let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy
let keyEncodingStrategy: KeyEncodingStrategy
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level encoder.
fileprivate var options: _Options {
return _Options(dateEncodingStrategy: dateEncodingStrategy,
dataEncodingStrategy: dataEncodingStrategy,
nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy,
keyEncodingStrategy: keyEncodingStrategy,
userInfo: userInfo)
}
// MARK: - Constructing a JSON Encoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Encoding Values
/// Encodes the given top-level value and returns its JSON representation.
///
/// - parameter value: The value to encode.
/// - returns: A new `Data` value containing the encoded JSON data.
/// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
/// - throws: An error if any value throws an error during encoding.
open func encode<T : Encodable>(_ value: T) throws -> Data {
let encoder = _JSONEncoder(options: self.options)
guard let topLevel = try encoder.box_(value) else {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values."))
}
if topLevel is NSNull {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as null JSON fragment."))
} else if topLevel is NSNumber {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as number JSON fragment."))
} else if topLevel is NSString {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as string JSON fragment."))
}
let writingOptions = JSONSerialization.WritingOptions(rawValue: self.outputFormatting.rawValue)
do {
return try JSONSerialization.data(withJSONObject: topLevel, options: writingOptions)
} catch {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Unable to encode the given top-level value to JSON.", underlyingError: error))
}
}
}
// MARK: - _JSONEncoder
fileprivate class _JSONEncoder : Encoder {
// MARK: Properties
/// The encoder's storage.
fileprivate var storage: _JSONEncodingStorage
/// Options set on the top-level encoder.
fileprivate let options: JSONEncoder._Options
/// The path to the current point in encoding.
public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level encoder options.
fileprivate init(options: JSONEncoder._Options, codingPath: [CodingKey] = []) {
self.options = options
self.storage = _JSONEncodingStorage()
self.codingPath = codingPath
}
/// Returns whether a new element can be encoded at this coding path.
///
/// `true` if an element has not yet been encoded at this coding path; `false` otherwise.
fileprivate var canEncodeNewValue: Bool {
// Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container).
// At the same time, every time a container is requested, a new value gets pushed onto the storage stack.
// If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition.
//
// This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path.
// Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here).
return self.storage.count == self.codingPath.count
}
// MARK: - Encoder Methods
public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> {
// If an existing keyed container was already requested, return that one.
let topContainer: NSMutableDictionary
if self.canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = self.storage.pushKeyedContainer()
} else {
guard let container = self.storage.containers.last as? NSMutableDictionary else {
preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.")
}
topContainer = container
}
let container = _JSONKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
return KeyedEncodingContainer(container)
}
public func unkeyedContainer() -> UnkeyedEncodingContainer {
// If an existing unkeyed container was already requested, return that one.
let topContainer: NSMutableArray
if self.canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = self.storage.pushUnkeyedContainer()
} else {
guard let container = self.storage.containers.last as? NSMutableArray else {
preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.")
}
topContainer = container
}
return _JSONUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
}
public func singleValueContainer() -> SingleValueEncodingContainer {
return self
}
}
// MARK: - Encoding Storage and Containers
fileprivate struct _JSONEncodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the JSON types (NSNull, NSNumber, NSString, NSArray, NSDictionary).
private(set) fileprivate var containers: [NSObject] = []
// MARK: - Initialization
/// Initializes `self` with no containers.
fileprivate init() {}
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary {
let dictionary = NSMutableDictionary()
self.containers.append(dictionary)
return dictionary
}
fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray {
let array = NSMutableArray()
self.containers.append(array)
return array
}
fileprivate mutating func push(container: __owned NSObject) {
self.containers.append(container)
}
fileprivate mutating func popContainer() -> NSObject {
precondition(!self.containers.isEmpty, "Empty container stack.")
return self.containers.popLast()!
}
}
// MARK: - Encoding Containers
fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the encoder we're writing to.
private let encoder: _JSONEncoder
/// A reference to the container we're writing to.
private let container: NSMutableDictionary
/// The path of coding keys taken to get to this point in encoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` with the given references.
fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
// MARK: - Coding Path Operations
private func _converted(_ key: CodingKey) -> CodingKey {
switch encoder.options.keyEncodingStrategy {
case .useDefaultKeys:
return key
case .convertToSnakeCase:
let newKeyString = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(key.stringValue)
return _JSONKey(stringValue: newKeyString, intValue: key.intValue)
case .custom(let converter):
return converter(codingPath + [key])
}
}
// MARK: - KeyedEncodingContainerProtocol Methods
public mutating func encodeNil(forKey key: Key) throws {
self.container[_converted(key).stringValue] = NSNull()
}
public mutating func encode(_ value: Bool, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Int, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Int8, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Int16, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Int32, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Int64, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: UInt, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: UInt8, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: UInt16, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: UInt32, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: UInt64, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: String, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Float, forKey key: Key) throws {
// Since the float may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[_converted(key).stringValue] = try self.encoder.box(value)
}
public mutating func encode(_ value: Double, forKey key: Key) throws {
// Since the double may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[_converted(key).stringValue] = try self.encoder.box(value)
}
public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[_converted(key).stringValue] = try self.encoder.box(value)
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
let dictionary = NSMutableDictionary()
self.container[_converted(key).stringValue] = dictionary
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
let array = NSMutableArray()
self.container[_converted(key).stringValue] = array
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
}
public mutating func superEncoder() -> Encoder {
return _JSONReferencingEncoder(referencing: self.encoder, key: _JSONKey.super, convertedKey: _converted(_JSONKey.super), wrapping: self.container)
}
public mutating func superEncoder(forKey key: Key) -> Encoder {
return _JSONReferencingEncoder(referencing: self.encoder, key: key, convertedKey: _converted(key), wrapping: self.container)
}
}
fileprivate struct _JSONUnkeyedEncodingContainer : UnkeyedEncodingContainer {
// MARK: Properties
/// A reference to the encoder we're writing to.
private let encoder: _JSONEncoder
/// A reference to the container we're writing to.
private let container: NSMutableArray
/// The path of coding keys taken to get to this point in encoding.
private(set) public var codingPath: [CodingKey]
/// The number of elements encoded into the container.
public var count: Int {
return self.container.count
}
// MARK: - Initialization
/// Initializes `self` with the given references.
fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
// MARK: - UnkeyedEncodingContainer Methods
public mutating func encodeNil() throws { self.container.add(NSNull()) }
public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Float) throws {
// Since the float may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(_JSONKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func encode(_ value: Double) throws {
// Since the double may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(_JSONKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func encode<T : Encodable>(_ value: T) throws {
self.encoder.codingPath.append(_JSONKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> {
self.codingPath.append(_JSONKey(index: self.count))
defer { self.codingPath.removeLast() }
let dictionary = NSMutableDictionary()
self.container.add(dictionary)
let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
self.codingPath.append(_JSONKey(index: self.count))
defer { self.codingPath.removeLast() }
let array = NSMutableArray()
self.container.add(array)
return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
}
public mutating func superEncoder() -> Encoder {
return _JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container)
}
}
extension _JSONEncoder : SingleValueEncodingContainer {
// MARK: - SingleValueEncodingContainer Methods
fileprivate func assertCanEncodeNewValue() {
precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.")
}
public func encodeNil() throws {
assertCanEncodeNewValue()
self.storage.push(container: NSNull())
}
public func encode(_ value: Bool) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int8) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int16) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int32) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int64) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt8) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt16) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt32) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt64) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: String) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Float) throws {
assertCanEncodeNewValue()
try self.storage.push(container: self.box(value))
}
public func encode(_ value: Double) throws {
assertCanEncodeNewValue()
try self.storage.push(container: self.box(value))
}
public func encode<T : Encodable>(_ value: T) throws {
assertCanEncodeNewValue()
try self.storage.push(container: self.box(value))
}
}
// MARK: - Concrete Value Representations
extension _JSONEncoder {
/// Returns the given value boxed in a container appropriate for pushing onto the container stack.
fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) }
fileprivate func box(_ float: Float) throws -> NSObject {
guard !float.isInfinite && !float.isNaN else {
guard case let .convertToString(positiveInfinity: posInfString,
negativeInfinity: negInfString,
nan: nanString) = self.options.nonConformingFloatEncodingStrategy else {
throw EncodingError._invalidFloatingPointValue(float, at: codingPath)
}
if float == Float.infinity {
return NSString(string: posInfString)
} else if float == -Float.infinity {
return NSString(string: negInfString)
} else {
return NSString(string: nanString)
}
}
return NSNumber(value: float)
}
fileprivate func box(_ double: Double) throws -> NSObject {
guard !double.isInfinite && !double.isNaN else {
guard case let .convertToString(positiveInfinity: posInfString,
negativeInfinity: negInfString,
nan: nanString) = self.options.nonConformingFloatEncodingStrategy else {
throw EncodingError._invalidFloatingPointValue(double, at: codingPath)
}
if double == Double.infinity {
return NSString(string: posInfString)
} else if double == -Double.infinity {
return NSString(string: negInfString)
} else {
return NSString(string: nanString)
}
}
return NSNumber(value: double)
}
fileprivate func box(_ date: Date) throws -> NSObject {
switch self.options.dateEncodingStrategy {
case .deferredToDate:
// Must be called with a surrounding with(pushedKey:) call.
// Dates encode as single-value objects; this can't both throw and push a container, so no need to catch the error.
try date.encode(to: self)
return self.storage.popContainer()
case .secondsSince1970:
return NSNumber(value: date.timeIntervalSince1970)
case .millisecondsSince1970:
return NSNumber(value: 1000.0 * date.timeIntervalSince1970)
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return NSString(string: _iso8601Formatter.string(from: date))
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case .formatted(let formatter):
return NSString(string: formatter.string(from: date))
case .custom(let closure):
let depth = self.storage.count
do {
try closure(date, self)
} catch {
// If the value pushed a container before throwing, pop it back off to restore state.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
guard self.storage.count > depth else {
// The closure didn't encode anything. Return the default keyed container.
return NSDictionary()
}
// We can pop because the closure encoded something.
return self.storage.popContainer()
}
}
fileprivate func box(_ data: Data) throws -> NSObject {
switch self.options.dataEncodingStrategy {
case .deferredToData:
// Must be called with a surrounding with(pushedKey:) call.
let depth = self.storage.count
do {
try data.encode(to: self)
} catch {
// If the value pushed a container before throwing, pop it back off to restore state.
// This shouldn't be possible for Data (which encodes as an array of bytes), but it can't hurt to catch a failure.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
return self.storage.popContainer()
case .base64:
return NSString(string: data.base64EncodedString())
case .custom(let closure):
let depth = self.storage.count
do {
try closure(data, self)
} catch {
// If the value pushed a container before throwing, pop it back off to restore state.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
guard self.storage.count > depth else {
// The closure didn't encode anything. Return the default keyed container.
return NSDictionary()
}
// We can pop because the closure encoded something.
return self.storage.popContainer()
}
}
fileprivate func box(_ dict: [String : Encodable]) throws -> NSObject? {
let depth = self.storage.count
let result = self.storage.pushKeyedContainer()
do {
for (key, value) in dict {
self.codingPath.append(_JSONKey(stringValue: key, intValue: nil))
defer { self.codingPath.removeLast() }
result[key] = try box(value)
}
} catch {
// If the value pushed a container before throwing, pop it back off to restore state.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
// The top container should be a new container.
guard self.storage.count > depth else {
return nil
}
return self.storage.popContainer()
}
fileprivate func box(_ value: Encodable) throws -> NSObject {
return try self.box_(value) ?? NSDictionary()
}
// This method is called "box_" instead of "box" to disambiguate it from the overloads. Because the return type here is different from all of the "box" overloads (and is more general), any "box" calls in here would call back into "box" recursively instead of calling the appropriate overload, which is not what we want.
fileprivate func box_(_ value: Encodable) throws -> NSObject? {
// Disambiguation between variable and function is required due to
// issue tracked at: https://bugs.swift.org/browse/SR-1846
let type = Swift.type(of: value)
if type == Date.self || type == NSDate.self {
// Respect Date encoding strategy
return try self.box((value as! Date))
} else if type == Data.self || type == NSData.self {
// Respect Data encoding strategy
return try self.box((value as! Data))
} else if type == URL.self || type == NSURL.self {
// Encode URLs as single strings.
return self.box((value as! URL).absoluteString)
} else if type == Decimal.self || type == NSDecimalNumber.self {
// JSONSerialization can natively handle NSDecimalNumber.
return (value as! NSDecimalNumber)
} else if value is _JSONStringDictionaryEncodableMarker {
return try self.box(value as! [String : Encodable])
}
// The value should request a container from the _JSONEncoder.
let depth = self.storage.count
do {
try value.encode(to: self)
} catch {
// If the value pushed a container before throwing, pop it back off to restore state.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
// The top container should be a new container.
guard self.storage.count > depth else {
return nil
}
return self.storage.popContainer()
}
}
// MARK: - _JSONReferencingEncoder
/// _JSONReferencingEncoder is a special subclass of _JSONEncoder which has its own storage, but references the contents of a different encoder.
/// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container).
fileprivate class _JSONReferencingEncoder : _JSONEncoder {
// MARK: Reference types.
/// The type of container we're referencing.
private enum Reference {
/// Referencing a specific index in an array container.
case array(NSMutableArray, Int)
/// Referencing a specific key in a dictionary container.
case dictionary(NSMutableDictionary, String)
}
// MARK: - Properties
/// The encoder we're referencing.
fileprivate let encoder: _JSONEncoder
/// The container reference itself.
private let reference: Reference
// MARK: - Initialization
/// Initializes `self` by referencing the given array container in the given encoder.
fileprivate init(referencing encoder: _JSONEncoder, at index: Int, wrapping array: NSMutableArray) {
self.encoder = encoder
self.reference = .array(array, index)
super.init(options: encoder.options, codingPath: encoder.codingPath)
self.codingPath.append(_JSONKey(index: index))
}
/// Initializes `self` by referencing the given dictionary container in the given encoder.
fileprivate init(referencing encoder: _JSONEncoder,
key: CodingKey, convertedKey: __shared CodingKey, wrapping dictionary: NSMutableDictionary) {
self.encoder = encoder
self.reference = .dictionary(dictionary, convertedKey.stringValue)
super.init(options: encoder.options, codingPath: encoder.codingPath)
self.codingPath.append(key)
}
// MARK: - Coding Path Operations
fileprivate override var canEncodeNewValue: Bool {
// With a regular encoder, the storage and coding path grow together.
// A referencing encoder, however, inherits its parents coding path, as well as the key it was created for.
// We have to take this into account.
return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1
}
// MARK: - Deinitialization
// Finalizes `self` by writing the contents of our storage to the referenced encoder's storage.
deinit {
let value: Any
switch self.storage.count {
case 0: value = NSDictionary()
case 1: value = self.storage.popContainer()
default: fatalError("Referencing encoder deallocated with multiple containers on stack.")
}
switch self.reference {
case .array(let array, let index):
array.insert(value, at: index)
case .dictionary(let dictionary, let key):
dictionary[NSString(string: key)] = value
}
}
}
//===----------------------------------------------------------------------===//
// JSON Decoder
//===----------------------------------------------------------------------===//
/// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types.
open class JSONDecoder {
// MARK: Options
/// The strategy to use for decoding `Date` values.
public enum DateDecodingStrategy {
/// Defer to `Date` for decoding. This is the default strategy.
case deferredToDate
/// Decode the `Date` as a UNIX timestamp from a JSON number.
case secondsSince1970
/// Decode the `Date` as UNIX millisecond timestamp from a JSON number.
case millisecondsSince1970
/// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Decode the `Date` as a string parsed by the given formatter.
case formatted(DateFormatter)
/// Decode the `Date` as a custom value decoded by the given closure.
case custom((_ decoder: Decoder) throws -> Date)
}
/// The strategy to use for decoding `Data` values.
public enum DataDecodingStrategy {
/// Defer to `Data` for decoding.
case deferredToData
/// Decode the `Data` from a Base64-encoded string. This is the default strategy.
case base64
/// Decode the `Data` as a custom value decoded by the given closure.
case custom((_ decoder: Decoder) throws -> Data)
}
/// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN).
public enum NonConformingFloatDecodingStrategy {
/// Throw upon encountering non-conforming values. This is the default strategy.
case `throw`
/// Decode the values from the given representation strings.
case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String)
}
/// The strategy to use for automatically changing the value of keys before decoding.
public enum KeyDecodingStrategy {
/// Use the keys specified by each type. This is the default strategy.
case useDefaultKeys
/// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by each type.
///
/// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences.
///
/// Converting from snake case to camel case:
/// 1. Capitalizes the word starting after each `_`
/// 2. Removes all `_`
/// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata).
/// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`.
///
/// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character.
case convertFromSnakeCase
/// Provide a custom conversion from the key in the encoded JSON to the keys specified by the decoded types.
/// The full path to the current decoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before decoding.
/// If the result of the conversion is a duplicate key, then only one value will be present in the container for the type to decode from.
case custom((_ codingPath: [CodingKey]) -> CodingKey)
fileprivate static func _convertFromSnakeCase(_ stringKey: String) -> String {
guard !stringKey.isEmpty else { return stringKey }
// Find the first non-underscore character
guard let firstNonUnderscore = stringKey.firstIndex(where: { $0 != "_" }) else {
// Reached the end without finding an _
return stringKey
}
// Find the last non-underscore character
var lastNonUnderscore = stringKey.index(before: stringKey.endIndex)
while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" {
stringKey.formIndex(before: &lastNonUnderscore)
}
let keyRange = firstNonUnderscore...lastNonUnderscore
let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore
let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex
var components = stringKey[keyRange].split(separator: "_")
let joinedString : String
if components.count == 1 {
// No underscores in key, leave the word as is - maybe already camel cased
joinedString = String(stringKey[keyRange])
} else {
joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined()
}
// Do a cheap isEmpty check before creating and appending potentially empty strings
let result : String
if (leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty) {
result = joinedString
} else if (!leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty) {
// Both leading and trailing underscores
result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange])
} else if (!leadingUnderscoreRange.isEmpty) {
// Just leading
result = String(stringKey[leadingUnderscoreRange]) + joinedString
} else {
// Just trailing
result = joinedString + String(stringKey[trailingUnderscoreRange])
}
return result
}
}
/// The strategy to use in decoding dates. Defaults to `.deferredToDate`.
open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate
/// The strategy to use in decoding binary data. Defaults to `.base64`.
open var dataDecodingStrategy: DataDecodingStrategy = .base64
/// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`.
open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw
/// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`.
open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys
/// Contextual user-provided information for use during decoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the decoding hierarchy.
fileprivate struct _Options {
let dateDecodingStrategy: DateDecodingStrategy
let dataDecodingStrategy: DataDecodingStrategy
let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy
let keyDecodingStrategy: KeyDecodingStrategy
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level decoder.
fileprivate var options: _Options {
return _Options(dateDecodingStrategy: dateDecodingStrategy,
dataDecodingStrategy: dataDecodingStrategy,
nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy,
keyDecodingStrategy: keyDecodingStrategy,
userInfo: userInfo)
}
// MARK: - Constructing a JSON Decoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Decoding Values
/// Decodes a top-level value of the given type from the given JSON representation.
///
/// - parameter type: The type of the value to decode.
/// - parameter data: The data to decode from.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid JSON.
/// - throws: An error if any value throws an error during decoding.
open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T {
let topLevel: Any
do {
topLevel = try JSONSerialization.jsonObject(with: data)
} catch {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error))
}
let decoder = _JSONDecoder(referencing: topLevel, options: self.options)
guard let value = try decoder.unbox(topLevel, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
}
return value
}
}
// MARK: - _JSONDecoder
fileprivate class _JSONDecoder : Decoder {
// MARK: Properties
/// The decoder's storage.
fileprivate var storage: _JSONDecodingStorage
/// Options set on the top-level decoder.
fileprivate let options: JSONDecoder._Options
/// The path to the current point in encoding.
fileprivate(set) public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level container and options.
fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: JSONDecoder._Options) {
self.storage = _JSONDecodingStorage()
self.storage.push(container: container)
self.codingPath = codingPath
self.options = options
}
// MARK: - Decoder Methods
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let topContainer = self.storage.topContainer as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer)
}
let container = _JSONKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer)
return KeyedDecodingContainer(container)
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get unkeyed decoding container -- found null value instead."))
}
guard let topContainer = self.storage.topContainer as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer)
}
return _JSONUnkeyedDecodingContainer(referencing: self, wrapping: topContainer)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
}
// MARK: - Decoding Storage
fileprivate struct _JSONDecodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the JSON types (NSNull, NSNumber, String, Array, [String : Any]).
private(set) fileprivate var containers: [Any] = []
// MARK: - Initialization
/// Initializes `self` with no containers.
fileprivate init() {}
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate var topContainer: Any {
precondition(!self.containers.isEmpty, "Empty container stack.")
return self.containers.last!
}
fileprivate mutating func push(container: __owned Any) {
self.containers.append(container)
}
fileprivate mutating func popContainer() {
precondition(!self.containers.isEmpty, "Empty container stack.")
self.containers.removeLast()
}
}
// MARK: Decoding Containers
fileprivate struct _JSONKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _JSONDecoder
/// A reference to the container we're reading from.
private let container: [String : Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [String : Any]) {
self.decoder = decoder
switch decoder.options.keyDecodingStrategy {
case .useDefaultKeys:
self.container = container
case .convertFromSnakeCase:
// Convert the snake case keys in the container to camel case.
// If we hit a duplicate key after conversion, then we'll use the first one we saw. Effectively an undefined behavior with JSON dictionaries.
self.container = Dictionary(container.map {
key, value in (JSONDecoder.KeyDecodingStrategy._convertFromSnakeCase(key), value)
}, uniquingKeysWith: { (first, _) in first })
case .custom(let converter):
self.container = Dictionary(container.map {
key, value in (converter(decoder.codingPath + [_JSONKey(stringValue: key, intValue: nil)]).stringValue, value)
}, uniquingKeysWith: { (first, _) in first })
}
self.codingPath = decoder.codingPath
}
// MARK: - KeyedDecodingContainerProtocol Methods
public var allKeys: [Key] {
return self.container.keys.compactMap { Key(stringValue: $0) }
}
public func contains(_ key: Key) -> Bool {
return self.container[key.stringValue] != nil
}
private func _errorDescription(of key: CodingKey) -> String {
switch decoder.options.keyDecodingStrategy {
case .convertFromSnakeCase:
// In this case we can attempt to recover the original value by reversing the transform
let original = key.stringValue
let converted = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(original)
if converted == original {
return "\(key) (\"\(original)\")"
} else {
return "\(key) (\"\(original)\"), converted to \(converted)"
}
default:
// Otherwise, just report the converted string
return "\(key) (\"\(key.stringValue)\")"
}
}
public func decodeNil(forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
return entry is NSNull
}
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \(_errorDescription(of: key))"))
}
guard let dictionary = value as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
}
let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
return KeyedDecodingContainer(container)
}
public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \(_errorDescription(of: key))"))
}
guard let array = value as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
}
return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
private func _superDecoder(forKey key: __owned CodingKey) throws -> Decoder {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
let value: Any = self.container[key.stringValue] ?? NSNull()
return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
public func superDecoder() throws -> Decoder {
return try _superDecoder(forKey: _JSONKey.super)
}
public func superDecoder(forKey key: Key) throws -> Decoder {
return try _superDecoder(forKey: key)
}
}
fileprivate struct _JSONUnkeyedDecodingContainer : UnkeyedDecodingContainer {
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _JSONDecoder
/// A reference to the container we're reading from.
private let container: [Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
/// The index of the element we're about to decode.
private(set) public var currentIndex: Int
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [Any]) {
self.decoder = decoder
self.container = container
self.codingPath = decoder.codingPath
self.currentIndex = 0
}
// MARK: - UnkeyedDecodingContainer Methods
public var count: Int? {
return self.container.count
}
public var isAtEnd: Bool {
return self.currentIndex >= self.count!
}
public mutating func decodeNil() throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
if self.container[self.currentIndex] is NSNull {
self.currentIndex += 1
return true
} else {
return false
}
}
public mutating func decode(_ type: Bool.Type) throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int.Type) throws -> Int {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int8.Type) throws -> Int8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int16.Type) throws -> Int16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int32.Type) throws -> Int32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int64.Type) throws -> Int64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt.Type) throws -> UInt {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Float.Type) throws -> Float {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Double.Type) throws -> Double {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: String.Type) throws -> String {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
guard !(value is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let dictionary = value as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
}
self.currentIndex += 1
let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
return KeyedDecodingContainer(container)
}
public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
guard !(value is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let array = value as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
}
self.currentIndex += 1
return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
public mutating func superDecoder() throws -> Decoder {
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Decoder.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get superDecoder() -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
self.currentIndex += 1
return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
}
extension _JSONDecoder : SingleValueDecodingContainer {
// MARK: SingleValueDecodingContainer Methods
private func expectNonNull<T>(_ type: T.Type) throws {
guard !self.decodeNil() else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead."))
}
}
public func decodeNil() -> Bool {
return self.storage.topContainer is NSNull
}
public func decode(_ type: Bool.Type) throws -> Bool {
try expectNonNull(Bool.self)
return try self.unbox(self.storage.topContainer, as: Bool.self)!
}
public func decode(_ type: Int.Type) throws -> Int {
try expectNonNull(Int.self)
return try self.unbox(self.storage.topContainer, as: Int.self)!
}
public func decode(_ type: Int8.Type) throws -> Int8 {
try expectNonNull(Int8.self)
return try self.unbox(self.storage.topContainer, as: Int8.self)!
}
public func decode(_ type: Int16.Type) throws -> Int16 {
try expectNonNull(Int16.self)
return try self.unbox(self.storage.topContainer, as: Int16.self)!
}
public func decode(_ type: Int32.Type) throws -> Int32 {
try expectNonNull(Int32.self)
return try self.unbox(self.storage.topContainer, as: Int32.self)!
}
public func decode(_ type: Int64.Type) throws -> Int64 {
try expectNonNull(Int64.self)
return try self.unbox(self.storage.topContainer, as: Int64.self)!
}
public func decode(_ type: UInt.Type) throws -> UInt {
try expectNonNull(UInt.self)
return try self.unbox(self.storage.topContainer, as: UInt.self)!
}
public func decode(_ type: UInt8.Type) throws -> UInt8 {
try expectNonNull(UInt8.self)
return try self.unbox(self.storage.topContainer, as: UInt8.self)!
}
public func decode(_ type: UInt16.Type) throws -> UInt16 {
try expectNonNull(UInt16.self)
return try self.unbox(self.storage.topContainer, as: UInt16.self)!
}
public func decode(_ type: UInt32.Type) throws -> UInt32 {
try expectNonNull(UInt32.self)
return try self.unbox(self.storage.topContainer, as: UInt32.self)!
}
public func decode(_ type: UInt64.Type) throws -> UInt64 {
try expectNonNull(UInt64.self)
return try self.unbox(self.storage.topContainer, as: UInt64.self)!
}
public func decode(_ type: Float.Type) throws -> Float {
try expectNonNull(Float.self)
return try self.unbox(self.storage.topContainer, as: Float.self)!
}
public func decode(_ type: Double.Type) throws -> Double {
try expectNonNull(Double.self)
return try self.unbox(self.storage.topContainer, as: Double.self)!
}
public func decode(_ type: String.Type) throws -> String {
try expectNonNull(String.self)
return try self.unbox(self.storage.topContainer, as: String.self)!
}
public func decode<T : Decodable>(_ type: T.Type) throws -> T {
try expectNonNull(type)
return try self.unbox(self.storage.topContainer, as: type)!
}
}
// MARK: - Concrete Value Representations
extension _JSONDecoder {
/// Returns the given value unboxed from a container.
fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber {
// TODO: Add a flag to coerce non-boolean numbers into Bools?
if number === kCFBooleanTrue as NSNumber {
return true
} else if number === kCFBooleanFalse as NSNumber {
return false
}
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let bool = value as? Bool {
return bool
*/
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int = number.intValue
guard NSNumber(value: int) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int
}
fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int8 = number.int8Value
guard NSNumber(value: int8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int8
}
fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int16 = number.int16Value
guard NSNumber(value: int16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int16
}
fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int32 = number.int32Value
guard NSNumber(value: int32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int32
}
fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int64 = number.int64Value
guard NSNumber(value: int64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int64
}
fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint = number.uintValue
guard NSNumber(value: uint) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint
}
fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint8 = number.uint8Value
guard NSNumber(value: uint8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint8
}
fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint16 = number.uint16Value
guard NSNumber(value: uint16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint16
}
fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint32 = number.uint32Value
guard NSNumber(value: uint32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint32
}
fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint64 = number.uint64Value
guard NSNumber(value: uint64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint64
}
fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse {
// We are willing to return a Float by losing precision:
// * If the original value was integral,
// * and the integral value was > Float.greatestFiniteMagnitude, we will fail
// * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24
// * If it was a Float, you will get back the precise value
// * If it was a Double or Decimal, you will get back the nearest approximation if it will fit
let double = number.doubleValue
guard abs(double) <= Double(Float.greatestFiniteMagnitude) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type)."))
}
return Float(double)
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let double = value as? Double {
if abs(double) <= Double(Float.max) {
return Float(double)
}
overflow = true
} else if let int = value as? Int {
if let float = Float(exactly: int) {
return float
}
overflow = true
*/
} else if let string = value as? String,
case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy {
if string == posInfString {
return Float.infinity
} else if string == negInfString {
return -Float.infinity
} else if string == nanString {
return Float.nan
}
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse {
// We are always willing to return the number as a Double:
// * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double
// * If it was a Float or Double, you will get back the precise value
// * If it was Decimal, you will get back the nearest approximation
return number.doubleValue
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let double = value as? Double {
return double
} else if let int = value as? Int {
if let double = Double(exactly: int) {
return double
}
overflow = true
*/
} else if let string = value as? String,
case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy {
if string == posInfString {
return Double.infinity
} else if string == negInfString {
return -Double.infinity
} else if string == nanString {
return Double.nan
}
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
return string
}
fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? {
guard !(value is NSNull) else { return nil }
switch self.options.dateDecodingStrategy {
case .deferredToDate:
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try Date(from: self)
case .secondsSince1970:
let double = try self.unbox(value, as: Double.self)!
return Date(timeIntervalSince1970: double)
case .millisecondsSince1970:
let double = try self.unbox(value, as: Double.self)!
return Date(timeIntervalSince1970: double / 1000.0)
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
let string = try self.unbox(value, as: String.self)!
guard let date = _iso8601Formatter.date(from: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted."))
}
return date
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case .formatted(let formatter):
let string = try self.unbox(value, as: String.self)!
guard let date = formatter.date(from: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter."))
}
return date
case .custom(let closure):
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try closure(self)
}
}
fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
guard !(value is NSNull) else { return nil }
switch self.options.dataDecodingStrategy {
case .deferredToData:
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try Data(from: self)
case .base64:
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
guard let data = Data(base64Encoded: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64."))
}
return data
case .custom(let closure):
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try closure(self)
}
}
fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? {
guard !(value is NSNull) else { return nil }
// Attempt to bridge from NSDecimalNumber.
if let decimal = value as? Decimal {
return decimal
} else {
let doubleValue = try self.unbox(value, as: Double.self)!
return Decimal(doubleValue)
}
}
fileprivate func unbox<T>(_ value: Any, as type: _JSONStringDictionaryDecodableMarker.Type) throws -> T? {
guard !(value is NSNull) else { return nil }
var result = [String : Any]()
guard let dict = value as? NSDictionary else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let elementType = type.elementType
for (key, value) in dict {
let key = key as! String
self.codingPath.append(_JSONKey(stringValue: key, intValue: nil))
defer { self.codingPath.removeLast() }
result[key] = try unbox_(value, as: elementType)
}
return result as? T
}
fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? {
return try unbox_(value, as: type) as? T
}
fileprivate func unbox_(_ value: Any, as type: Decodable.Type) throws -> Any? {
if type == Date.self || type == NSDate.self {
return try self.unbox(value, as: Date.self)
} else if type == Data.self || type == NSData.self {
return try self.unbox(value, as: Data.self)
} else if type == URL.self || type == NSURL.self {
guard let urlString = try self.unbox(value, as: String.self) else {
return nil
}
guard let url = URL(string: urlString) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Invalid URL string."))
}
return url
} else if type == Decimal.self || type == NSDecimalNumber.self {
return try self.unbox(value, as: Decimal.self)
} else if let stringKeyedDictType = type as? _JSONStringDictionaryDecodableMarker.Type {
return try self.unbox(value, as: stringKeyedDictType)
} else {
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try type.init(from: self)
}
}
}
//===----------------------------------------------------------------------===//
// Shared Key Types
//===----------------------------------------------------------------------===//
fileprivate struct _JSONKey : CodingKey {
public var stringValue: String
public var intValue: Int?
public init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
public init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
public init(stringValue: String, intValue: Int?) {
self.stringValue = stringValue
self.intValue = intValue
}
fileprivate init(index: Int) {
self.stringValue = "Index \(index)"
self.intValue = index
}
fileprivate static let `super` = _JSONKey(stringValue: "super")!
}
//===----------------------------------------------------------------------===//
// Shared ISO8601 Date Formatter
//===----------------------------------------------------------------------===//
// NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
fileprivate var _iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter
}()
//===----------------------------------------------------------------------===//
// Error Utilities
//===----------------------------------------------------------------------===//
extension EncodingError {
/// Returns a `.invalidValue` error describing the given invalid floating-point value.
///
///
/// - parameter value: The value that was invalid to encode.
/// - parameter path: The path of `CodingKey`s taken to encode this value.
/// - returns: An `EncodingError` with the appropriate path and debug description.
fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError {
let valueDescription: String
if value == T.infinity {
valueDescription = "\(T.self).infinity"
} else if value == -T.infinity {
valueDescription = "-\(T.self).infinity"
} else {
valueDescription = "\(T.self).nan"
}
let debugDescription = "Unable to encode \(valueDescription) directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded."
return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription))
}
}
| apache-2.0 | 88993cea7a1d04bfe9f8c2a39418dbc9 | 43.806756 | 323 | 0.647084 | 5.028564 | false | false | false | false |
piwik/piwik-sdk-ios | MatomoTrackerTests/QueueStub.swift | 1 | 1337 | @testable import MatomoTracker
final class QueueStub: Queue {
struct Callback {
typealias QueueEvents = (_ events: [Event], _ completion: ()->()) -> ()
typealias FirstEvents = (_ limit: Int, _ completion: (_ items: [Event])->()) -> ()
typealias EventCount = () -> (Int)
typealias RemoveEvents = (_ events: [Event], _ completion: ()->()) -> ()
}
var queueEvents: Callback.QueueEvents? = nil
var firstItems: Callback.FirstEvents? = nil
var countEvents: Callback.EventCount? = nil
var removeEventsCallback: Callback.RemoveEvents? = nil
init() {}
public var eventCount: Int { get {
return self.countEvents?() ?? 0
}
}
func enqueue(events: [Event], completion: (()->())?) {
if let closure = queueEvents {
closure(events, completion ?? {})
} else {
completion?()
}
}
func first(limit: Int, completion: ([Event]) -> ()) {
if let closure = firstItems {
closure(limit, completion)
} else {
completion([])
}
}
func remove(events: [Event], completion: () -> ()) {
if let closure = removeEventsCallback {
closure(events, completion)
} else {
completion()
}
}
}
| mit | c869712d66317d23a99591b712b97b2a | 27.446809 | 90 | 0.525804 | 4.658537 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/AssistantV1/Models/DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio.swift | 1 | 3933 | /**
* (C) Copyright IBM Corp. 2022.
*
* 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 IBMSwiftSDKCore
/**
DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio.
Enums with an associated value of DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio:
DialogNodeOutputGeneric
*/
public struct DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio: Codable, Equatable {
/**
The type of response returned by the dialog node. The specified response type must be supported by the client
application or channel.
*/
public var responseType: String
/**
The `https:` URL of the audio clip.
*/
public var source: String
/**
An optional title to show before the response.
*/
public var title: String?
/**
An optional description to show with the response.
*/
public var description: String?
/**
An array of objects specifying channels for which the response is intended. If **channels** is present, the
response is intended for a built-in integration and should not be handled by an API client.
*/
public var channels: [ResponseGenericChannel]?
/**
For internal use only.
*/
public var channelOptions: [String: JSON]?
/**
Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen.
*/
public var altText: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case responseType = "response_type"
case source = "source"
case title = "title"
case description = "description"
case channels = "channels"
case channelOptions = "channel_options"
case altText = "alt_text"
}
/**
Initialize a `DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio` with member variables.
- parameter responseType: The type of response returned by the dialog node. The specified response type must be
supported by the client application or channel.
- parameter source: The `https:` URL of the audio clip.
- parameter title: An optional title to show before the response.
- parameter description: An optional description to show with the response.
- parameter channels: An array of objects specifying channels for which the response is intended. If
**channels** is present, the response is intended for a built-in integration and should not be handled by an API
client.
- parameter channelOptions: For internal use only.
- parameter altText: Descriptive text that can be used for screen readers or other situations where the audio
player cannot be seen.
- returns: An initialized `DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio`.
*/
public init(
responseType: String,
source: String,
title: String? = nil,
description: String? = nil,
channels: [ResponseGenericChannel]? = nil,
channelOptions: [String: JSON]? = nil,
altText: String? = nil
)
{
self.responseType = responseType
self.source = source
self.title = title
self.description = description
self.channels = channels
self.channelOptions = channelOptions
self.altText = altText
}
}
| apache-2.0 | 108f2598dee5df385c7dfa56e720428f | 34.116071 | 120 | 0.691584 | 4.813953 | false | false | false | false |
seandavidmcgee/HumanKontactBeta | src/HumanKontact Extension/KeyboardControllerPage2.swift | 1 | 18725 | //
// KeyboardControllerPage2.swift
// keyboardTest
//
// Created by Sean McGee on 7/9/15.
// Copyright (c) 2015 3 Callistos Services. All rights reserved.
//
import WatchKit
import Foundation
import RealmSwift
class KeyboardControllerSecond: WKInterfaceController {
@IBOutlet weak var searchEntry: WKInterfaceGroup!
@IBOutlet weak var topLeftKey: WKInterfaceButton!
@IBOutlet weak var topLeftKeyLabel: WKInterfaceLabel!
@IBOutlet weak var topRightKey: WKInterfaceButton!
@IBOutlet weak var topRightKeyLabel: WKInterfaceLabel!
@IBOutlet weak var bottomLeftKey: WKInterfaceButton!
@IBOutlet weak var bottomLeftKeyLabel: WKInterfaceLabel!
@IBOutlet weak var bottomRightKey: WKInterfaceButton!
@IBOutlet weak var bottomRightKeyLabel: WKInterfaceLabel!
@IBOutlet weak var searchLabel2: WKInterfaceLabel!
@IBOutlet weak var closeButton: WKInterfaceButton!
@IBOutlet weak var deleteButton: WKInterfaceButton!
@IBAction func backToSearch() {
self.goToResults()
}
@IBAction func deleteSearch() {
if activeSearch.characters.count == 1 {
self.indexReset()
firstActivation = true
keyEntry = ""
activeSearch = ""
if selectionValues.count != 0 {
selectionValues.removeAll(keepCapacity: false)
}
self.roundToFour(keyValues.count)
overFlow = self.remFromFour(keyValues.count)
self.dynamicKeyboardLayout()
self.reloadTableData()
} else {
keyEntry = keyEntry.substringToIndex(keyEntry.endIndex.predecessor())
activeSearch = keyEntry
self.backBranch()
}
}
func refreshData() {
if let indexController = lookupWatchController {
selectionValues.removeAll(keepCapacity: false)
selectionValues = indexController.options!
let selections = indexController.branchSelecions!
myResults += selections
activeSearch = indexController.entrySoFar!
self.searchLabel2.setText(activeSearch)
self.roundToFour(selectionValues.count)
overFlow = self.remFromFour(selectionValues.count)
self.dynamicKeyboardLayout()
}
}
func goToResults() {
if activeSearch.isEmpty {
WKInterfaceController.reloadRootControllersWithNames(["Landing"], contexts: ["No"])
first = true
} else {
self.presentControllerWithName("Results", context: "No")
firstActivation = true
keyEntry = ""
self.searchLabel2.setText("")
returnFromResults = true
}
}
var currentPage: Int = 2
var populateKeys = [WKInterfaceLabel]()
var keysToDisplay = Int()
var selectedIndex: String!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
if firstActivation {
keysAppear(context!)
}
if returnFromResults == true {
searchEntry.setBackgroundImageNamed("KeyTopBarInactive")
}
}
override func willActivate() {
super.willActivate()
if !firstActivation {
keysAppear(pageContexts[currentPage - 1])
}
if !activeSearch.isEmpty {
deleteButton.setHidden(false)
self.searchLabel2.setText(activeSearch)
}
if returnFromResults == true {
self.dynamicKeyboardLayout()
returnFromResults = false
}
self.reloadTableData()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func keysAppear(context: AnyObject?) {
if let contextDict:Dictionary = context as! Dictionary<String,Int>! {
keysToDisplay = contextDict["keys"]! as Int
switch keysToDisplay {
case 4:
topLeftKey.setHidden(false)
topRightKey.setHidden(false)
bottomLeftKey.setHidden(false)
bottomRightKey.setHidden(false)
case 3:
topLeftKey.setHidden(false)
topRightKey.setHidden(false)
bottomLeftKey.setHidden(false)
case 2:
topLeftKey.setHidden(false)
topRightKey.setHidden(false)
case 1:
topLeftKey.setHidden(false)
default:
print("no keys")
}
}
}
func reloadTableData() {
let pageIndex = ((currentPage - 1) * 4)
populateKeys = [self.topLeftKeyLabel, self.topRightKeyLabel, self.bottomLeftKeyLabel, self.bottomRightKeyLabel]
var indexCount = 0
if firstActivation {
for index in pageIndex..<pageIndex + keysToDisplay {
let keyValue = keyValues[index] as! String
let stringCount = keyValue.characters.count
if stringCount < 15 {
let key = populateKeys[indexCount]
key.setText("\(keyValue.capitalizedString)")
self.responsiveKeys(stringCount, indexCount: indexCount)
} else {
self.responsiveLongKeys(keyValue.capitalizedString, indexCount: indexCount)
}
indexCount++
}
} else {
for index in pageIndex..<pageIndex + keysToDisplay {
let keyValue = "\(activeSearch)" + "\(selectionValues[index] as! String)"
let stringCount = keyValue.characters.count
if stringCount < 15 {
let key = populateKeys[indexCount]
key.setText("\(keyValue.capitalizedString)")
self.responsiveKeys(stringCount, indexCount: indexCount)
} else {
self.responsiveLongKeys(keyValue.capitalizedString, indexCount: indexCount)
}
indexCount++
}
}
if !activeSearch.isEmpty {
searchEntry.setBackgroundImageNamed("KeyEntryBarLight")
} else {
searchEntry.setBackgroundImageNamed("KeyTopBarLight")
}
self.closeButton.setEnabled(true)
}
func branchOptions(index: Int) {
let pageIndex = ((currentPage - 1) * 4)
let selectionIndex: Int = pageIndex + index
lookupWatchController?.selectOption(selectionIndex)
}
func responsiveKeys(stringCount: Int, indexCount: Int) {
if stringCount <= 2 {
switch indexCount {
case 0:
topLeftKey.setAlpha(1.0)
topLeftKey.setEnabled(true)
case 1:
topRightKey.setAlpha(1.0)
topRightKey.setEnabled(true)
case 2:
bottomLeftKey.setAlpha(1.0)
bottomLeftKey.setEnabled(true)
case 3:
bottomRightKey.setAlpha(1.0)
bottomRightKey.setEnabled(true)
default:
print("not long enough")
}
}
else if stringCount > 2 && stringCount < 8 {
switch indexCount {
case 0:
topLeftKey.setWidth(45.0 + (5.0 * (CGFloat(stringCount) - 2.0)))
topLeftKeyLabel.setWidth(45.0 + (5.0 * (CGFloat(stringCount) - 2.0)))
topLeftKey.setAlpha(1.0)
topLeftKey.setEnabled(true)
case 1:
topRightKey.setWidth(45.0 + (5.0 * (CGFloat(stringCount) - 2.0)))
topRightKeyLabel.setWidth(45.0 + (5.0 * (CGFloat(stringCount) - 2.0)))
topRightKey.setAlpha(1.0)
topRightKey.setEnabled(true)
case 2:
bottomLeftKey.setWidth(45.0 + (5.0 * (CGFloat(stringCount) - 2.0)))
bottomLeftKeyLabel.setWidth(45.0 + (5.0 * (CGFloat(stringCount/2) - 2.0)))
bottomLeftKey.setAlpha(1.0)
bottomLeftKey.setEnabled(true)
case 3:
bottomRightKey.setWidth(45.0 + (5.0 * (CGFloat(stringCount) - 2.0)))
bottomRightKeyLabel.setWidth(45.0 + (5.0 * (CGFloat(stringCount/2) - 2.0)))
bottomRightKey.setAlpha(1.0)
bottomRightKey.setEnabled(true)
default:
print("not long enough")
}
} else if stringCount >= 8 && stringCount < 15 {
switch indexCount {
case 0:
topLeftKey.setWidth(72)
topLeftKeyLabel.setWidth(55.0 + (5.0 * (CGFloat(stringCount/2) - 2.0)))
topLeftKey.setAlpha(1.0)
topLeftKey.setEnabled(true)
case 1:
topRightKey.setWidth(72)
topRightKeyLabel.setWidth(55.0 + (5.0 * (CGFloat(stringCount/2) - 2.0)))
topRightKey.setAlpha(1.0)
topRightKey.setEnabled(true)
case 2:
bottomLeftKey.setWidth(72)
bottomLeftKeyLabel.setWidth(55.0 + (5.0 * (CGFloat(stringCount/2) - 2.0)))
bottomLeftKey.setAlpha(1.0)
bottomLeftKey.setEnabled(true)
case 3:
bottomRightKey.setWidth(72)
bottomRightKeyLabel.setWidth(55.0 + (5.0 * (CGFloat(stringCount/2) - 2.0)))
bottomRightKey.setAlpha(1.0)
bottomRightKey.setEnabled(true)
default:
print("not long enough")
}
}
}
func responsiveLongKeys(value: String, indexCount: Int) {
let stringCountLong = 10
var ellipsisString: String! = ""
if let spaceIndex = value.characters.indexOf(" ") {
let index = value.startIndex.advancedBy(6)
let label: String = value.substringToIndex(index) + ".."
let remainder: String = value.substringFromIndex(spaceIndex.successor())
ellipsisString = label + remainder
}
switch indexCount {
case 0:
topLeftKey.setWidth(72)
topLeftKeyLabel.setWidth(52.0 + (5.0 * (CGFloat(stringCountLong/2) - 2.0)))
topLeftKeyLabel.setText(ellipsisString)
topLeftKey.setAlpha(1.0)
topLeftKey.setEnabled(true)
case 1:
topRightKey.setWidth(72)
topRightKeyLabel.setWidth(52.0 + (5.0 * (CGFloat(stringCountLong/2) - 2.0)))
topRightKeyLabel.setText(ellipsisString)
topRightKey.setAlpha(1.0)
topRightKey.setEnabled(true)
case 2:
bottomLeftKey.setWidth(72)
bottomLeftKeyLabel.setWidth(52.0 + (5.0 * (CGFloat(stringCountLong/2) - 2.0)))
bottomLeftKeyLabel.setText(ellipsisString)
bottomLeftKey.setAlpha(1.0)
bottomLeftKey.setEnabled(true)
case 3:
bottomRightKey.setWidth(72)
bottomRightKeyLabel.setWidth(52.0 + (5.0 * (CGFloat(stringCountLong/2) - 2.0)))
bottomRightKeyLabel.setText(ellipsisString)
bottomRightKey.setAlpha(1.0)
bottomRightKey.setEnabled(true)
default:
print("not long enough")
}
}
@IBAction func clearSearch() {
People.people = People.realm.filter("recent == true").sorted("recentIndex", ascending: false)
contactLimit = 15
peopleLimit = 15
People.contacts = People.realm.sorted("indexedOrder", ascending: true)
keyEntry = ""
activeSearch = ""
keyValues.removeAll(keepCapacity: false)
if selectionValues.count != 0 {
selectionValues.removeAll(keepCapacity: false)
}
first = true
self.indexReset()
WKInterfaceController.reloadRootControllersWithNames(["Search"], contexts: ["No"])
}
@IBAction func topLeftKeyPressed() {
self.buttonPressed(0)
}
@IBAction func topRightKeyPressed() {
self.buttonPressed(1)
}
@IBAction func bottomLeftKeyPressed() {
self.buttonPressed(2)
}
@IBAction func bottomRightKeyPressed() {
self.buttonPressed(3)
}
func buttonPressed(index: Int) {
firstActivation = false
let pageIndex = ((currentPage - 1) * 4)
keyIndexSelected = pageIndex + index
baseKey = keyEntry
var keyEntered: String!
if baseKey == "" {
keyEntered = keyValues[keyIndexSelected] as! String
keyEntry = keyEntered.capitalizedString
} else {
keyEntered = "\(baseKey)" + "\(selectionValues[keyIndexSelected] as! String)"
keyEntry = keyEntered.capitalizedString
}
// Query using a predicate string
var searchString: String! = ""
if let spaceIndex = keyEntry.characters.indexOf(" ") {
let lastName: String = keyEntry.substringToIndex(spaceIndex)
let firstName: String = keyEntry.substringFromIndex(spaceIndex.successor())
if firstName.characters.count > 0 && lastName.characters.count > 0 {
searchString = firstName + " " + lastName
} else if firstName.characters.count == 0 && lastName.characters.count > 0 {
searchString = lastName
} else if lastName.characters.count == 0 && firstName.characters.count > 0 {
searchString = firstName
}
}
var queriedSearch: Results<HKPerson>
if searchString == "" {
queriedSearch = People.realm.filter("firstName BEGINSWITH[c] '\(keyEntry)' OR lastName BEGINSWITH[c] '\(keyEntry)' OR fullName BEGINSWITH[c] '\(keyEntry)'")
} else {
queriedSearch = People.realm.filter("fullName BEGINSWITH[c] '\(keyEntry)' OR fullName BEGINSWITH[c] '\(searchString)' OR firstName BEGINSWITH[c] '\(searchString)' OR lastName BEGINSWITH[c] '\(searchString)' OR fullName == '\(keyEntry)' OR fullName == '\(searchString)'")
}
People.people = queriedSearch
activeSearch = keyEntry
peopleLimit = queriedSearch.count
if peopleLimit <= 6 {
self.goToResults()
} else {
self.branchOptions(index)
self.refreshData()
}
}
func indexReset() {
lookupWatchController?.restart()
dispatch_async(dispatch_get_main_queue()) {
if let indexController = lookupWatchController {
keyValues = indexController.options!
let selections = indexController.branchSelecions!
myResults += selections
activeSearch = indexController.entrySoFar!
self.searchLabel2.setText(activeSearch)
self.roundToFour(keyValues.count)
overFlow = self.remFromFour(keyValues.count)
self.dynamicKeyboardLayout()
self.reloadTableData()
}
}
}
func backBranch() {
lookupWatchController?.back()
self.refreshData()
}
func dynamicKeyboardLayout() {
if let numberOfKeyControllers = roundedNum as Int! {
if overFlow == 0 {
switch numberOfKeyControllers {
case 1:
pages = ["Keyboard1"]
pageContexts = [["keys":4]]
case 2:
pages = ["Keyboard1", "Keyboard2"]
pageContexts = [["keys":4],["keys":4]]
case 3:
pages = ["Keyboard1", "Keyboard2", "Keyboard3"]
pageContexts = [["keys":4],["keys":4],["keys":4]]
case 4:
pages = ["Keyboard1", "Keyboard2", "Keyboard3", "Keyboard4"]
pageContexts = [["keys":4],["keys":4],["keys":4],["keys":4]]
case 5:
pages = ["Keyboard1", "Keyboard2", "Keyboard3", "Keyboard4", "Keyboard5"]
pageContexts = [["keys":4],["keys":4],["keys":4],["keys":4],["keys":4]]
case 6:
pages = ["Keyboard1", "Keyboard2", "Keyboard3", "Keyboard4", "Keyboard5", "Keyboard6"]
pageContexts = [["keys":4],["keys":4],["keys":4],["keys":4],["keys":4],["keys":4]]
default:
pages = ["Results"]
pageContexts = []
pageNoContext = ["No"]
}
}
else {
switch numberOfKeyControllers {
case 0:
pages = ["Keyboard1"]
pageContexts = [["keys":overFlow]]
case 1:
pages = ["Keyboard1","Keyboard2"]
pageContexts = [["keys":4],["keys":overFlow]]
case 2:
pages = ["Keyboard1","Keyboard2", "Keyboard3"]
pageContexts = [["keys":4],["keys":4],["keys":overFlow]]
case 3:
pages = ["Keyboard1","Keyboard2", "Keyboard3", "Keyboard4"]
pageContexts = [["keys":4],["keys":4],["keys":4],["keys":overFlow]]
case 4:
pages = ["Keyboard1","Keyboard2", "Keyboard3", "Keyboard4", "Keyboard5"]
pageContexts = [["keys":4],["keys":4],["keys":4],["keys":4],["keys":overFlow]]
case 5:
pages = ["Keyboard1","Keyboard2","Keyboard3","Keyboard4","Keyboard5","Keyboard6"]
pageContexts = [["keys":4],["keys":4],["keys":4],["keys":4],["keys":4],["keys":overFlow]]
case 6:
pages = ["Keyboard1","Keyboard2","Keyboard3","Keyboard4","Keyboard5","Keyboard6","Keyboard7"]
pageContexts = [["keys":4],["keys":4],["keys":4],["keys":4],["keys":4],["keys":4],["keys":overFlow]]
default:
pages = ["Results"]
pageContexts = []
pageNoContext = ["No"]
}
}
}
if pageContexts.isEmpty {
self.presentControllerWithNames(pages, contexts: pageNoContext)
keyEntry = ""
activeSearch = ""
keyValues.removeAll(keepCapacity: false)
selectionValues.removeAll(keepCapacity: false)
} else {
WKInterfaceController.reloadRootControllersWithNames(pages, contexts: pageContexts)
}
}
} | mit | b8bc5d580f8f80be6b30d17a19374ae9 | 38.673729 | 282 | 0.550708 | 4.915988 | false | false | false | false |
srxboys/RXSwiftExtention | Pods/SwifterSwift/Source/Extensions/DoubleExtensions.swift | 1 | 4348 | //
// DoubleExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/6/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
// MARK: - Properties
public extension Double {
/// SwifterSwift: Absolute of double value.
public var abs: Double {
return Swift.abs(self)
}
/// SwifterSwift: String with number and current locale currency.
public var asLocaleCurrency: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale.current
return formatter.string(from: self as NSNumber)!
}
/// SwifterSwift: Ceil of double value.
public var ceil: Double {
return Foundation.ceil(self)
}
/// SwifterSwift: Radian value of degree input.
public var degreesToRadians: Double {
return Double.pi * self / 180.0
}
/// SwifterSwift: Floor of double value.
public var floor: Double {
return Foundation.floor(self)
}
/// SwifterSwift: Check if double is positive.
public var isPositive: Bool {
return self > 0
}
/// SwifterSwift: Check if double is negative.
public var isNegative: Bool {
return self < 0
}
/// SwifterSwift: Int.
public var int: Int {
return Int(self)
}
/// SwifterSwift: Float.
public var float: Float {
return Float(self)
}
/// SwifterSwift: CGFloat.
public var cgFloat: CGFloat {
return CGFloat(self)
}
/// SwifterSwift: String.
public var string: String {
return String(self)
}
/// SwifterSwift: Degree value of radian input.
public var radiansToDegrees: Double {
return self * 180 / Double.pi
}
}
// MARK: - Methods
extension Double {
/// SwifterSwift: Random double between two double values.
///
/// - Parameters:
/// - min: minimum number to start random from.
/// - max: maximum number random number end before.
/// - Returns: random double between two double values.
public static func random(between min: Double, and max: Double) -> Double {
return random(inRange: min...max)
}
/// SwifterSwift: Random double in a closed interval range.
///
/// - Parameter range: closed interval range.
public static func random(inRange range: ClosedRange<Double>) -> Double {
let delta = range.upperBound - range.lowerBound
return Double(arc4random()) / Double(UInt64(UINT32_MAX)) * delta + range.lowerBound
}
}
// MARK: - Initializers
public extension Double {
/// SwifterSwift: Created a random double between two double values.
///
/// - Parameters:
/// - min: minimum number to start random from.
/// - max: maximum number random number end before.
public init(randomBetween min: Double, and max: Double) {
self = Double.random(between: min, and: max)
}
/// SwifterSwift: Create a random double in a closed interval range.
///
/// - Parameter range: closed interval range.
public init(randomInRange range: ClosedRange<Double>) {
self = Double.random(inRange: range)
}
}
// MARK: - Operators
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ** : PowerPrecedence
/// SwifterSwift: Value of exponentiation.
///
/// - Parameters:
/// - lhs: base double.
/// - rhs: exponent double.
/// - Returns: exponentiation result (example: 4.4 ** 0.5 = 2.0976176963).
public func ** (lhs: Double, rhs: Double) -> Double {
// http://nshipster.com/swift-operators/
return pow(lhs, rhs)
}
prefix operator √
/// SwifterSwift: Square root of double.
///
/// - Parameter int: double value to find square root for
/// - Returns: square root of given double.
public prefix func √ (double: Double) -> Double {
// http://nshipster.com/swift-operators/
return sqrt(double)
}
infix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameters:
/// - lhs: double number
/// - rhs: double number
/// - Returns: tuple of plus-minus operation (example: 2.5 ± 1.5 -> (4, 1)).
public func ± (lhs: Double, rhs: Double) -> (Double, Double) {
// http://nshipster.com/swift-operators/
return (lhs + rhs, lhs - rhs)
}
prefix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameter int: double number
/// - Returns: tuple of plus-minus operation (example: ± 2.5 -> (2.5, -2.5)).
public prefix func ± (double: Double) -> (Double, Double) {
// http://nshipster.com/swift-operators/
return 0 ± double
}
| mit | 2f9b16ef597b17e8c0e62773b0ffc819 | 23.636364 | 85 | 0.683118 | 3.589404 | false | false | false | false |
LittoCats/coffee-mobile | CoffeeMobile/Base/Utils/CMCrypto.swift | 1 | 14133 | //
// Crypto.swift
// Crypto
//
// Created by 程巍巍 on 3/19/15.
// Copyright (c) 2015 Littocats. All rights reserved.
import Foundation
import CommonCrypto
struct CMCrypto {
static func MD5(#data: NSData) -> String{
let c_data = data.bytes
var md: [UInt8] = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
CC_MD5(c_data, CC_LONG(data.length), UnsafeMutablePointer<UInt8>(md))
var ret: String = ""
for index in 0 ..< Int(CC_MD5_DIGEST_LENGTH) {
ret += String(format: "%.2X", md[index])
}
return ret
}
static func MD5(#file: String) ->String?{
var inStream = NSInputStream(fileAtPath: file)
if inStream == nil {return nil}
inStream?.open()
if inStream!.streamStatus != NSStreamStatus.Open {return nil}
var hashObject: CC_MD5_CTX = CC_MD5state_st(A: 0, B: 0, C: 0, D: 0, Nl: 0, Nh: 0, data: (CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0),CC_LONG(0)), num: 0)
CC_MD5_Init(&hashObject)
var hasMoreData = true
var buffer = UnsafeMutablePointer<UInt8>.alloc(4096)
var readBytesCount = 0
while hasMoreData {
readBytesCount = inStream!.read(buffer, maxLength: 4096)
if readBytesCount == -1 {break}
if readBytesCount == 0 {hasMoreData = false; continue}
CC_MD5_Update(&hashObject, buffer, CC_LONG(readBytesCount))
}
buffer.dealloc(4096)
var md: [UInt8] = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
CC_MD5_Final(UnsafeMutablePointer<UInt8>(md), &hashObject)
var ret: String = ""
for index in 0 ..< Int(CC_MD5_DIGEST_LENGTH) {
ret += String(format: "%.2X", md[index])
}
return ret
}
static func Base64Encode(#data: NSData) -> String{
var inStream = NSInputStream(data: data)
inStream.open()
var buffer = UnsafeMutablePointer<UInt8>.alloc(3)
var bValue: Int = 0
var ret: NSMutableString = NSMutableString()
while inStream.read(buffer, maxLength: 3) == 3{
bValue = (Int(buffer[0]) << 16) + (Int(buffer[1]) << 8) + Int(buffer[2])
ret.appendString(base64_table[bValue >> 18])
ret.appendString(base64_table[bValue >> 12 & 0b111111])
ret.appendString(base64_table[bValue >> 6 & 0b111111])
ret.appendString(base64_table[bValue & 0b111111])
}
var remainBitLen = data.length%3
bValue = 0
memset(buffer + remainBitLen, 0, 3 - remainBitLen)
bValue = (Int(buffer[0]) << 16) | (Int(buffer[1]) << 8) | Int(buffer[2])
for index in 0 ... remainBitLen {
ret.appendString(base64_table[bValue >> (18 - index * 6) & 0b111111])
}
if remainBitLen != 0 { ret.appendString(remainBitLen == 1 ? "==" : "=")}
inStream.close()
buffer.dealloc(3)
return ret as String
}
static func Base64Decode(#data: String) -> NSData{
var inStream = NSInputStream(data: (data as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
inStream.open()
var buffer = UnsafeMutablePointer<UInt8>.alloc(4)
var bValue: Int = 0
var value: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.alloc(3)
var ret: NSMutableData = NSMutableData()
while inStream.read(buffer, maxLength: 4) == 4{
bValue = de_base64_table[Int(buffer[0])] << 18 | de_base64_table[Int(buffer[1])] << 12 | de_base64_table[Int(buffer[2])] << 6 | de_base64_table[Int(buffer[3])]
value[0] = UInt8(bValue >> 16)
value[1] = UInt8(bValue >> 8 & 0xff)
value[2] = UInt8(bValue & 0xff)
ret.appendBytes(value, length: 3)
}
// 处理最后三位
var additionalBitLen = 0
for index in 0 ... 3 {
if buffer[index] == 61 { // "="
buffer[index] = 0
additionalBitLen++
}
}
if additionalBitLen != 0 {
bValue = de_base64_table[Int(buffer[0])] << 18 | de_base64_table[Int(buffer[1])] << 12 | de_base64_table[Int(buffer[2])] << 6 | de_base64_table[Int(buffer[3])]
value[0] = UInt8(bValue >> 16)
value[1] = UInt8(bValue >> 8 & 0xff)
value[2] = UInt8(bValue & 0xff)
ret.replaceBytesInRange(NSMakeRange(ret.length - 3, 3), withBytes: value, length: 3 - additionalBitLen)
}
inStream.close()
value.dealloc(3)
buffer.dealloc(4)
return ret
}
// 对称加密
let aes128 = 1
enum SymmetricCryptType{
case AES128
case AES192
case AES256
case DES
case DES3
var keySize: Int{
// 32 位平台,swift 在进行类型检查时,0xFFFF0000 超出了 整型范围(32 整型,最高位为符号位),因此先将 rawValue 转为无符号整型,最后再转回整型
return Int(UInt(self.rawValue) & 0xFFFF0000) >> 16
}
var algorithm: CCAlgorithm{
return CCAlgorithm(self.rawValue & 0xFFFF)
}
private var rawValue: Int{
switch self {
case .AES128: return kCCKeySizeAES128 << 16 | kCCAlgorithmAES
case .AES192: return kCCKeySizeAES192 << 16 | kCCAlgorithmAES
case .AES256: return kCCKeySizeAES256 << 16 | kCCAlgorithmAES
case .DES: return kCCKeySizeDES << 16 | kCCAlgorithmDES
case .DES3: return kCCKeySize3DES << 16 | kCCAlgorithm3DES
}
}
private static let aes128: Int = kCCKeySizeAES128 << 16 | Int(kCCAlgorithmAES)
}
static func SymmetricEncrypt(data: NSData, withPassword password: String, type: SymmetricCryptType) ->NSData {
var keySize = type.keySize
return SymmetricCrypt(data: data, keyStr: password, keySize: type.keySize, algorithm: type.algorithm, operation: CCOperation(kCCEncrypt))
}
static func SymmetricDecrypt(data: NSData, withPassword password: String, type: SymmetricCryptType) ->NSData {
return SymmetricCrypt(data: data, keyStr: password, keySize: type.keySize, algorithm: type.algorithm, operation: CCOperation(kCCDecrypt))
}
// 非对称加密
// 使用公钥加密
static func RSAEncrypt(data: NSData, publicKey: NSData) ->NSData{
var secKey: SecKeyRef = RSAPublicKey(data: publicKey)
var dataLength = data.length
// Notice 这里有三个数据长度的变量:blockSize chiperTextLength plaintextLength
// When PKCS1 padding is performed, the maximum length of data that can be encrypted is the value returned by SecKeyGetBlockSize() - 11. (SecKey.h)
var blockSize = Int(SecKeyGetBlockSize(secKey)-11)
var blockCount = Int(ceil(CDouble(dataLength/Int(blockSize))) + 1)
var chiperTextLength: Int = 0
// 缓存待加密的数据块
var plainText: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.alloc(blockSize * sizeof(UInt8))
var plainTextLength = blockSize;
// 缓存加密后的数据
var chiperText: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.alloc(plainTextLength * sizeof(UInt8))
var encryptedData = NSMutableData()
for (var i = 0; i < blockCount; i++){
plainTextLength = min(blockSize, dataLength - i*blockSize)
data.getBytes(plainText, range: NSMakeRange(i * blockSize, plainTextLength))
var status: OSStatus = SecKeyEncrypt(secKey,
SecPadding(kSecPaddingPKCS1),
plainText, plainTextLength,
chiperText, &chiperTextLength
)
if status == noErr {
encryptedData.appendBytes(chiperText, length: Int(chiperTextLength))
}else{
i = blockCount
}
}
chiperText.dealloc(blockSize * sizeof(UInt8))
plainText.dealloc(plainTextLength * sizeof(UInt8))
return encryptedData
}
// 使用私钥解密
static func RSADecrypt(data: NSData, privateKey: NSData, password: String) ->NSData{
var dataLength = data.length
var secKey: SecKeyRef = RSAPrivateKey(data: privateKey, password: password)
// Notice 这里有三个数据长度的变量:blockSize chiperTextLength plaintextLength
var blockSize = Int(SecKeyGetBlockSize(secKey))
var blockCount = Int(ceil(CDouble(dataLength/Int(blockSize)))+1)
var chiperTextLength: Int = 0
// 缓存待加密的数据块
var plainText: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.alloc(blockSize * sizeof(UInt8))
var plainTextLength = blockSize;
// 缓存解密后的数据
var chiperText: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.alloc(plainTextLength * sizeof(UInt8))
var decryptedData = NSMutableData()
for (var i = 0; i < blockCount; i++) {
plainTextLength = min(blockSize, dataLength - i * blockSize);
data.getBytes(plainText, range: NSMakeRange(i * blockSize, plainTextLength))
var status: OSStatus = SecKeyDecrypt(secKey,
SecPadding(kSecPaddingPKCS1),
plainText, plainTextLength,
chiperText, &chiperTextLength);
if status == noErr {
decryptedData.appendBytes(chiperText, length: Int(chiperTextLength))
}else{
i = blockCount
}
}
chiperText.dealloc(blockSize * sizeof(UInt8))
plainText.dealloc(plainTextLength * sizeof(UInt8))
return decryptedData
}
}
extension CMCrypto {
private static func SymmetricCrypt(#data: NSData, keyStr: String, keySize: Int, algorithm: CCAlgorithm, operation: CCOperation) ->NSData{
var keyLength = ((keyStr as NSString).length/keySize+1)*keySize+1
var key = [CChar](count: keyLength, repeatedValue: 0)
keyStr.getCString(&key, maxLength: keyLength, encoding: NSUTF8StringEncoding)
var dataLength = data.length
var bufferSize = dataLength + kCCBlockSizeAES128
var buffer = UnsafeMutablePointer<Void>.alloc(Int(bufferSize))
var retLen = 0
var status: CCCryptorStatus = CCCrypt(
operation, algorithm,
CCOptions(kCCOptionPKCS7Padding | kCCOptionECBMode),
UnsafePointer<Void>(key), keySize,
nil,
data.bytes, dataLength,
buffer, bufferSize,
&retLen
)
var result: NSData!
if Int(status) == kCCSuccess{
result = NSData(bytesNoCopy: buffer, length: retLen)
}
return result
}
private static func RSAPrivateKey(#data: NSData, password: String) ->SecKey{
var options = [kSecImportExportPassphrase.takeRetainedValue() as String: password]
var items: Unmanaged<CFArray>?
var status = SecPKCS12Import(data, options, &items)
var nItems: NSArray = items!.takeRetainedValue()
var privateKey: Unmanaged<SecKey>?
if status == noErr && items != nil && nItems.count > 0 {
var identities: NSDictionary = nItems.objectAtIndex(0) as! NSDictionary
var identity = identities.objectForKey(kSecImportItemIdentity.takeRetainedValue() as String) as! SecIdentity
status = SecIdentityCopyPrivateKey(identity, &privateKey)
if status != noErr {privateKey = nil}
}
assert(privateKey != nil, "Crypto error : RSA privateKey key load faild.")
return privateKey!.takeRetainedValue()
}
private static func RSAPublicKey(#data: NSData) ->SecKey{
var certification: SecCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, data).takeRetainedValue()
var policy: SecPolicy = SecPolicyCreateBasicX509().takeRetainedValue()
var utrust: Unmanaged<SecTrust>?
var status: OSStatus = SecTrustCreateWithCertificates(certification, policy, &utrust);
var trust: SecTrust = utrust!.takeRetainedValue()
var trustResult = UnsafeMutablePointer<SecTrustResultType>()
if status == noErr { status = SecTrustEvaluate(trust, trustResult) }
var publicKey: SecKey? = status == noErr ? SecTrustCopyPublicKey(trust).takeRetainedValue() : nil
assert(publicKey != nil, "Crypto error : RSA public key load faild.")
return publicKey!
}
}
extension CMCrypto {
private static let base64_table = [
"A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X",
"Y", "Z", "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "0", "1", "2", "3",
"4", "5", "6", "7", "8", "9", "+", "/"
]
private static let de_base64_table = [
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3E,0x00,0x00,0x00,0x3F,
0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,
0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x00,0x00,0x00,0x00,0x00,
0x00,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0x00,0x00,0x00,0x00,0x00
]
}
| apache-2.0 | 8d163d2e26538129d1038dfaea0bbaa5 | 43.394231 | 282 | 0.599957 | 3.701497 | false | false | false | false |
wwdc14/SkyNet | SkyNet/Classes/Network/NetworkDetailViewController.swift | 1 | 5921 | //
// NetworkDetailViewController.swift
// Pods
//
// Created by FD on 14/08/2017.
//
//
import UIKit
class NetworkDetailViewController: UIViewController {
var totalModels: Int = 0
var successfulRequests: Int = 0
var failedRequests: Int = 0
var totalRequestSize: Int = 0
var totalResponseSize: Int = 0
var totalResponseTime: Float = 0
var fastestResponseTime: Float = 999
var slowestResponseTime: Float = 0
var selectedModel:NetworkModel = NetworkModel()
let detailTextView: UITextView = UITextView(frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "detail"
view.addSubview(detailTextView)
view.backgroundColor = UIColor.white
detailTextView.font = UIFont.systemFont(ofSize: 13)
detailTextView.frame = view.bounds
generateStatics()
detailTextView.frame = self.view.bounds
detailTextView.attributedText = getReportString()
detailTextView.isEditable = false
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(handleTap))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func handleTap() {
UIPasteboard.general.string = detailTextView.text
let label = UILabel()
label.text = "复制成功"
self.view.addSubview(label)
label.textAlignment = .center
label.backgroundColor = UIColor(white: 0, alpha: 0.3)
label.font = UIFont.systemFont(ofSize: 13)
label.textColor = UIColor.white
label.frame = CGRect(x: self.view.frame.maxX / 2 - 50, y: self.view.frame.maxY - 50, width: 100, height: 30)
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1) {
label.removeFromSuperview()
}
}
public func selectedModel(_ model: NetworkModel) {
self.selectedModel = model
}
func generateStatics() {
let models = NetworkModelMangaer.shared.getModels()
totalModels = models.count
for model in models {
// if model.isSuccessful() {
// successfulRequests += 1
// } else {
// failedRequests += 1
// }
//
// if (model.requestBodyLength != nil) {
// totalRequestSize += model.requestBodyLength!
// }
//
// if (model.responseBodyLength != nil) {
// totalResponseSize += model.responseBodyLength!
// }
if (model.timeInterval != nil) {
totalResponseTime += model.timeInterval!
if model.timeInterval! < self.fastestResponseTime {
self.fastestResponseTime = model.timeInterval!
}
if model.timeInterval! > self.slowestResponseTime {
self.slowestResponseTime = model.timeInterval!
}
}
}
}
func getReportString() -> NSAttributedString
{
var tempString: String
tempString = String()
if self.totalModels == 0 {
tempString += "[Avg response time] \n0.0s\n\n"
tempString += "[Fastest response time] \n0.0s\n\n"
} else {
tempString += "[Avg response time] \n\(Float(self.totalResponseTime/Float(self.totalModels)))s\n\n"
if self.fastestResponseTime == 999 {
tempString += "[Fastest response time] \n0.0s\n\n"
} else {
tempString += "[Fastest response time] \n\(self.fastestResponseTime)s\n\n"
}
}
tempString += "[Slowest response time] \n\(self.slowestResponseTime)s\n\n"
tempString += "[Request Body]\n \(self.selectedModel.getRequestBody())\n\n"
tempString += "[Response Body]\n \(self.selectedModel.getResponseBody())\n\n"
return formatNFXString(tempString)
}
func formatNFXString(_ string: String) -> NSAttributedString
{
var tempMutableString = NSMutableAttributedString()
tempMutableString = NSMutableAttributedString(string: string)
let l = string.count
let regexBodyHeaders = try! NSRegularExpression(pattern: "(\\-- Body \\--)|(\\-- Headers \\--)", options: NSRegularExpression.Options.caseInsensitive)
let matchesBodyHeaders = regexBodyHeaders.matches(in: string, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSMakeRange(0, l)) as Array<NSTextCheckingResult>
for match in matchesBodyHeaders {
tempMutableString.addAttribute(NSAttributedStringKey.font, value: UIFont.boldSystemFont(ofSize: 14), range: match.range)
tempMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.orange, range: match.range)
}
let regexKeys = try! NSRegularExpression(pattern: "\\[.+?\\]", options: NSRegularExpression.Options.caseInsensitive)
let matchesKeys = regexKeys.matches(in: string, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSMakeRange(0, l)) as Array<NSTextCheckingResult>
for match in matchesKeys {
tempMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.black, range: match.range)
}
return tempMutableString
}
func reloadData()
{
DispatchQueue.main.async { () -> Void in
self.detailTextView.attributedText = self.getReportString()
}
}
}
| mit | 5e7f308eb15df2fa632183d60ad488a7 | 34.620482 | 195 | 0.60071 | 5.036627 | false | true | false | false |
mlmc03/portfolio-v2 | Sources/App/Models/Project.swift | 1 | 3008 | import Vapor
import VaporPostgreSQL
import Fluent
final class Project: Model {
var id: Node?
var exists: Bool = false
var title: String
var subtitle: String
var description: String
var type: String
var image: String?
var store: String?
var link: String?
init(title: String, subtitle: String, description: String, type: String, image: String?, store: String?, link: String?) {
self.id = nil
self.title = title
self.subtitle = subtitle
self.description = description
self.type = type
self.image = image
self.store = store
self.link = link
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
title = try node.extract("title")
subtitle = try node.extract("subtitle")
description = try node.extract("description")
type = try node.extract("type")
image = try node.extract("image")
store = try node.extract("store")
link = try node.extract("link")
}
func makeNode(context: Context) throws -> Node {
var node: [String: Node] = [:]
node["id"] = id
node["title"] = title.makeNode()
node["subtitle"] = subtitle.makeNode()
node["description"] = description.makeNode()
node["type"] = type.makeNode()
if let image = image {
node["image"] = image.makeNode()
}
if let link = link {
node["link"] = link.makeNode()
}
if let store = store {
node["store"] = store.makeNode()
}
switch context {
case ProjectContext.all:
let allTags = try tags()
if allTags.count > 0 {
node["tags"] = try allTags.makeNode()
}
let allMedias = try medias()
if allMedias.count > 0 {
node["medias"] = try allMedias.makeNode()
}
default:
break
}
return try node.makeNode()
}
static func prepare(_ database: Database) throws {
try database.create("projects") { projects in
projects.id()
projects.string("title")
projects.string("subtitle")
projects.custom("description", type: "TEXT")
projects.string("type")
projects.string("image", optional: true)
projects.string("link", optional: true)
projects.string("store", optional: true)
}
}
static func revert(_ database: Database) throws {
try database.delete("projects")
}
}
extension Project {
func tags() throws -> [Tag] {
let tags: Siblings<Tag> = try siblings()
return try tags.all()
}
func medias() throws -> [Media] {
return try children(nil, Media.self).all()
}
}
public enum ProjectContext: Context {
case all
}
| lgpl-3.0 | f1a1cea46d30c2691b1f1d38a728bd26 | 26.59633 | 125 | 0.53391 | 4.502994 | false | false | false | false |
CoderAlexChan/AlexCocoa | Extension/Character+extension.swift | 1 | 2967 | //
// Character+Extension.swift
// Main
//
// Created by cwq on 16/12/23.
// Copyright © 2016年 BB. All rights reserved.
//
import Foundation
// MARK: - Properties
public extension Character {
/// SwifterSwift: Check if character is emoji.
public var isEmoji: Bool {
// http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji
guard let scalarValue = String(self).unicodeScalars.first?.value else {
return false
}
switch scalarValue {
case 0x3030, 0x00AE, 0x00A9,// Special Characters
0x1D000...0x1F77F, // Emoticons
0x2100...0x27BF, // Misc symbols and Dingbats
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs
return true
default:
return false
}
}
/// SwifterSwift: Check if character is number.
public var isNumber: Bool {
return Int(String(self)) != nil
}
/// SwifterSwift: Integer from character (if applicable).
public var int: Int? {
return Int(String(self))
}
/// SwifterSwift: String from character.
public var string: String {
return String(self)
}
public var isUppercased: Bool {
return String(self) == String(self).uppercased()
}
/// SwifterSwift: Check if character is lowercased.
public var isLowercased: Bool {
return String(self) == String(self).lowercased()
}
/// SwifterSwift: Check if character is white space.
public var isWhiteSpace: Bool {
return String(self) == " "
}
/// SwifterSwift: Return the character lowercased.
public var lowercased: Character {
return String(self).lowercased().characters.first!
}
/// SwifterSwift: Return the character uppercased.
public var uppercased: Character {
return String(self).uppercased().characters.first!
}
}
// MARK: - Operators
public extension Character {
/// SwifterSwift: Repeat character multiple times.
///
/// - Parameters:
/// - lhs: character to repeat.
/// - rhs: number of times to repeat character.
/// - Returns: string with character repeated n times.
static public func * (lhs: Character, rhs: Int) -> String {
var newString = ""
for _ in 0 ..< rhs {
newString += String(lhs)
}
return newString
}
/// SwifterSwift: Repeat character multiple times.
///
/// - Parameters:
/// - lhs: number of times to repeat character.
/// - rhs: character to repeat.
/// - Returns: string with character repeated n times.
static public func * (lhs: Int, rhs: Character) -> String {
var newString = ""
for _ in 0 ..< lhs {
newString += String(rhs)
}
return newString
}
}
| mit | 8edec7cd5472684ac36b25db7d7eef88 | 27.5 | 95 | 0.587719 | 4.430493 | false | false | false | false |
MakiZz/30DaysToLearnSwift3.0 | project 18 - 限制字数/project 18 - 限制字数/ViewController.swift | 1 | 3431 | //
// ViewController.swift
// project 18 - 限制字数
//
// Created by mk on 17/3/21.
// Copyright © 2017年 maki. All rights reserved.
//
import UIKit
class ViewController: UIViewController ,UITextViewDelegate,UITextFieldDelegate{
@IBOutlet weak var tweetTextView: UITextView!
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var countLabel: UILabel!
override var preferredStatusBarStyle: UIStatusBarStyle{
return UIStatusBarStyle.lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
tweetTextView.delegate = self
avatarImageView.layer.cornerRadius = avatarImageView.frame.width / 2
tweetTextView.backgroundColor = UIColor.clear
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyBoardWillShow(note:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyBoardWillHide(note:)), name: .UIKeyboardWillHide, object: nil)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let myTextViewString = tweetTextView.text!
countLabel.text = "\(140 - myTextViewString.characters.count)"
if range.length > 140 {
return false
}
let newLength = myTextViewString.characters.count + range.length
return newLength < 140
}
func keyBoardWillShow(note:NSNotification) {
let userInfo = note.userInfo
let keyBoardBounds = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let deltay = keyBoardBounds.size.height
let animation:(() -> Void) = {
self.bottomView.transform = CGAffineTransform.init(translationX: 0, y: -deltay)
}
if duration > 0 {
let options = UIViewAnimationOptions.init(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
UIView.animate(withDuration: duration, delay: 0, options: options, animations: animation, completion: nil)
}else {
animation()
}
}
func keyBoardWillHide(note:NSNotification) {
let userInfo = note.userInfo
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let animations:(() -> Void) = {
self.bottomView.transform = CGAffineTransform.identity
}
if duration > 0 {
let options = UIViewAnimationOptions.init(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
UIView.animate(withDuration: duration, delay: 0, options: options, animations: animations, completion: nil)
}else{
animations()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
}
| mit | 24f9664b7429e306629c1df31f4664bb | 29.535714 | 172 | 0.624269 | 5.690516 | false | false | false | false |
minikin/Algorithmics | Pods/PSOperations/PSOperations/BlockObserver.swift | 1 | 1583 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows how to implement the OperationObserver protocol.
*/
import Foundation
/**
The `BlockObserver` is a way to attach arbitrary blocks to significant events
in an `Operation`'s lifecycle.
*/
public struct BlockObserver: OperationObserver {
// MARK: Properties
private let startHandler: (Operation -> Void)?
private let cancelHandler: (Operation -> Void)?
private let produceHandler: ((Operation, NSOperation) -> Void)?
private let finishHandler: ((Operation, [NSError]) -> Void)?
public init(startHandler: (Operation -> Void)? = nil, cancelHandler: (Operation -> Void)? = nil, produceHandler: ((Operation, NSOperation) -> Void)? = nil, finishHandler: ((Operation, [NSError]) -> Void)? = nil) {
self.startHandler = startHandler
self.cancelHandler = cancelHandler
self.produceHandler = produceHandler
self.finishHandler = finishHandler
}
// MARK: OperationObserver
public func operationDidStart(operation: Operation) {
startHandler?(operation)
}
public func operationDidCancel(operation: Operation) {
cancelHandler?(operation)
}
public func operation(operation: Operation, didProduceOperation newOperation: NSOperation) {
produceHandler?(operation, newOperation)
}
public func operationDidFinish(operation: Operation, errors: [NSError]) {
finishHandler?(operation, errors)
}
}
| mit | a84e00ab9d5aadcf207eed2615d1cd0f | 32.638298 | 217 | 0.689437 | 5.133117 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.