repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
darkerk/v2ex | V2EX/Cells/FavoriteNodeViewCell.swift | 1 | 1724 | //
// FavoriteNodeViewCell.swift
// V2EX
//
// Created by darker on 2017/3/20.
// Copyright © 2017年 darker. All rights reserved.
//
import UIKit
import Kingfisher
class FavoriteNodeViewCell: UITableViewCell {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var countLabel: UILabel!
var node: Node? {
willSet {
if let model = newValue {
iconView.kf.setImage(with: URL(string: model.iconURLString), placeholder: #imageLiteral(resourceName: "slide_menu_setting"))
nameLabel.text = model.name
countLabel.text = " \(model.comments) "
countLabel.isHidden = model.comments == 0
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = AppStyle.shared.theme.cellBackgroundColor
contentView.backgroundColor = AppStyle.shared.theme.cellBackgroundColor
let selectedView = UIView()
selectedView.backgroundColor = AppStyle.shared.theme.cellSelectedBackgroundColor
self.selectedBackgroundView = selectedView
nameLabel.textColor = AppStyle.shared.theme.black64Color
countLabel.clipsToBounds = true
countLabel.layer.cornerRadius = 9
countLabel.backgroundColor = AppStyle.shared.theme.topicReplyCountBackgroundColor
countLabel.textColor = AppStyle.shared.theme.topicReplyCountTextColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | c99d42c9c3f1aeeea41a9ed3315b2df6 | 32.096154 | 140 | 0.665311 | 5.106825 | false | false | false | false |
Eccelor/material-components-ios | components/AppBar/examples/AppBarDelegateForwardingExample.swift | 1 | 5318 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import MaterialComponents
// This example builds upon AppBarTypicalUseExample.
class AppBarDelegateForwardingExample: UITableViewController {
let appBar = MDCAppBar()
convenience init() {
self.init(style: .plain)
}
override init(style: UITableViewStyle) {
super.init(style: style)
self.appBar.navigationBar.tintColor = UIColor.white
appBar.navigationBar.titleTextAttributes =
[ NSForegroundColorAttributeName: UIColor.white ]
self.addChildViewController(appBar.headerViewController)
self.title = "Delegate Forwarding"
let color = UIColor(white: 0.2, alpha:1)
appBar.headerViewController.headerView.backgroundColor = color
let mutator = MDCAppBarTextColorAccessibilityMutator()
mutator.mutate(appBar)
}
override func viewDidLoad() {
super.viewDidLoad()
// UITableViewController's tableView.delegate is self by default. We're setting it here for
// emphasis.
self.tableView.delegate = self
appBar.headerViewController.headerView.trackingScrollView = self.tableView
appBar.addSubviewsToParent()
self.tableView.layoutMargins = UIEdgeInsets.zero
self.tableView.separatorInset = UIEdgeInsets.zero
}
// The following four methods must be forwarded to the tracking scroll view in order to implement
// the Flexible Header's behavior.
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == self.appBar.headerViewController.headerView.trackingScrollView {
self.appBar.headerViewController.headerView.trackingScrollDidScroll()
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == self.appBar.headerViewController.headerView.trackingScrollView {
self.appBar.headerViewController.headerView.trackingScrollDidEndDecelerating()
}
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView,
willDecelerate decelerate: Bool) {
let headerView = self.appBar.headerViewController.headerView
if scrollView == headerView.trackingScrollView {
headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate)
}
}
override func scrollViewWillEndDragging(_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let headerView = self.appBar.headerViewController.headerView
if scrollView == headerView.trackingScrollView {
headerView.trackingScrollWillEndDragging(withVelocity: velocity,
targetContentOffset: targetContentOffset)
}
}
// MARK: Typical setup
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.title = "Delegate Forwarding (Swift)"
self.addChildViewController(appBar.headerViewController)
let color = UIColor(
red: CGFloat(0x03) / CGFloat(255),
green: CGFloat(0xA9) / CGFloat(255),
blue: CGFloat(0xF4) / CGFloat(255),
alpha: 1)
appBar.headerViewController.headerView.backgroundColor = color
appBar.navigationBar.tintColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
// MARK: Catalog by convention
extension AppBarDelegateForwardingExample {
class func catalogBreadcrumbs() -> [String] {
return ["App Bar", "Delegate Forwarding (Swift)"]
}
func catalogShouldHideNavigation() -> Bool {
return true
}
}
extension AppBarDelegateForwardingExample {
override var childViewControllerForStatusBarHidden: UIViewController? {
return appBar.headerViewController
}
override var childViewControllerForStatusBarStyle: UIViewController? {
return appBar.headerViewController
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
}
// MARK: - Typical application code (not Material-specific)
// MARK: UITableViewDataSource
extension AppBarDelegateForwardingExample {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
cell!.layoutMargins = UIEdgeInsets.zero
return cell!
}
}
| apache-2.0 | 92d7e163c8e23ba6f420f433675f14b5 | 31.625767 | 99 | 0.73317 | 5.307385 | false | false | false | false |
hoffmanjon/SwiftyBones | examples/BlinkingLed/main.swift | 1 | 467 | import Glibc
if let led = SBDigitalGPIO(id: "gpio30", direction: .OUT){
while(true) {
if let oldValue = led.getValue() {
print("Changing")
var newValue = (oldValue == DigitalGPIOValue.HIGH) ? DigitalGPIOValue.LOW : DigitalGPIOValue.HIGH
led.setValue(newValue)
usleep(150000)
}
}
} else {
print("Error init pin")
}
| mit | 8c0a7c0684ad9eeac8db44b48b689090 | 32.357143 | 121 | 0.488223 | 4.623762 | false | false | false | false |
daniele-elia/metronome | metronomo/ViewController.swift | 1 | 8603 | //
// ViewController.swift
// metronomo
//
// Created by Daniele Elia on 25/02/15.
// Copyright (c) 2015 Daniele Elia. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
@IBOutlet var labelBpm: UILabel!
@IBOutlet var btnStart: UIButton!
@IBOutlet var stepper: UIStepper!
@IBOutlet var labelBattiti: UILabel!
@IBOutlet var stepperBattiti: UIStepper!
@IBOutlet var labelNomeTempo: UILabel!
var myTimer: NSTimer?
var myTimerBattiti: NSTimer?
var player : AVAudioPlayer?
var myImageView: UIImageView!
let altezzaSchermo = UIScreen.mainScreen().bounds.size.height
let larghezzaSchermo = UIScreen.mainScreen().bounds.size.width
var tempo: Double = 1
var bpm: Double = 60
var battiti: Double = 1
let yImmagine: CGFloat = 60 //CGFloat(altezzaSchermo/2)
let larghezzaPallina: CGFloat = 60
let altezzaPallina:CGFloat = 60
var inizio = 1
var tempoIniziale: CFAbsoluteTime = 0
override func viewDidLoad() {
super.viewDidLoad()
var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
if let savedBpm = defaults.objectForKey("Bpm") as? String {
labelBpm.text = savedBpm
stepper.value = (labelBpm.text! as NSString).doubleValue
} else {
labelBpm.text = "\(Int(stepper.value))"
}
if let savedBattiti = defaults.objectForKey("Battiti") as? String {
labelBattiti.text = savedBattiti
stepperBattiti.value = (labelBattiti.text! as NSString).doubleValue
} else {
labelBattiti.text = "\(Int(stepperBattiti.value))"
}
var image = UIImage(named: "pallina")
myImageView = UIImageView(image: image!)
myImageView.frame = CGRect(x: CGFloat(30), y: yImmagine, width: larghezzaPallina, height: altezzaPallina)
view.addSubview(myImageView)
var audioSessionError: NSError?
let audioSession = AVAudioSession.sharedInstance()
audioSession.setActive(true, error: nil)
if audioSession.setCategory(AVAudioSessionCategoryPlayback, error: &audioSessionError){
debugPrintln("Successfully set the audio session")
} else {
debugPrintln("Could not set the audio session")
}
calcolaTempo()
nomeTempo()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* The delegate message that will let us know that the player
has finished playing an audio file */
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
//debugPrintln("Finished playing the song")
//sleep(1)
}
@IBAction func cambiaBpm(sender: AnyObject) {
labelBpm.text = "\(Int(stepper.value))"
calcolaTempo()
}
@IBAction func cambiaBattit(sender: UIStepper) {
labelBattiti.text = "\(Int(stepperBattiti.value))"
calcolaTempo()
}
func calcolaTempo() {
bpm = (labelBpm.text! as NSString).doubleValue
tempo = 60/bpm
battiti = (labelBattiti.text! as NSString).doubleValue
nomeTempo()
debugPrintln("tempo: \(tempo)")
var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(labelBpm.text, forKey: "Bpm")
defaults.setObject(labelBattiti.text, forKey: "Battiti")
defaults.synchronize()
}
@IBAction func startStop(sender: UIButton) {
calcolaTempo()
var lbl: String = "Start"
var img: String = "play"
if btnStart.titleLabel?.text == "Start" {
img = "stop"
lbl = "Stop"
inizio = 1
tempoIniziale = CFAbsoluteTimeGetCurrent()
myTimer = NSTimer.scheduledTimerWithTimeInterval(0.005,
target: self,
selector: "timerMethod:",
userInfo: nil,
repeats: true)
UIScreen.mainScreen().brightness = 0
} else {
myTimer?.invalidate()
self.myTimerBattiti?.invalidate()
myImageView.frame = CGRectMake(CGFloat(30), yImmagine, larghezzaPallina, altezzaPallina)
UIScreen.mainScreen().brightness = 0.2
}
btnStart.setTitle(lbl, forState: UIControlState.Normal)
let image = UIImage(named: img) as UIImage!
btnStart.setImage(image, forState: .Normal)
}
func timerMethod(sender: NSTimer){
if (CFAbsoluteTimeGetCurrent() - tempoIniziale) >= (tempo) {
click()
move()
tempoIniziale = CFAbsoluteTimeGetCurrent()
}
}
func move() {
var origine: CGFloat = 30
if myImageView.frame.origin.x == 30 {
origine = larghezzaSchermo - (myImageView.frame.width*2)
}
UIView.animateWithDuration(tempo, delay: 0.0, options: UIViewAnimationOptions.allZeros, animations: { () -> Void in
self.myImageView.frame = CGRectMake(origine, self.myImageView.frame.origin.y, self.myImageView.frame.size.width, self.myImageView.frame.size.height);
}, completion: nil)
}
func click() {
var file = NSBundle.mainBundle().URLForResource("toc", withExtension: "aiff")
var error:NSError?
/* Start the audio player */
self.player = AVAudioPlayer(contentsOfURL: file, error: &error)
/* Did we get an instance of AVAudioPlayer? */
if let theAudioPlayer = self.player {
theAudioPlayer.delegate = self;
if inizio == 1 {
self.player?.volume = 1
} else {
self.player?.volume = 0.2
//debugPrintln("0.5")
}
if theAudioPlayer.prepareToPlay() && theAudioPlayer.play(){
//debugPrintln("Successfully started playing")
} else {
debugPrintln("Failed to play \(error)")
}
} else {
/* Handle the failure of instantiating the audio player */
}
debugPrintln("battito: \(inizio)")
inizio = inizio + 1
if inizio > Int(battiti) {
inizio = 1
}
}
func nomeTempo() {
var n: String = "Largo"
switch bpm {
case 40...59: n = "Largo"
case 60...65: n = "Larghetto"
case 66...75: n = "Adagio"
case 76...107: n = "Andante"
case 108...119: n = "Moderato"
case 120...167: n = "Allegro"
case 168...199: n = "Presto"
case 200...250: n = "Prestissimo"
default: n = " "
}
labelNomeTempo.text = n
}
func handleInterruption(notification: NSNotification){
/* Audio Session is interrupted. The player will be paused here */
let interruptionTypeAsObject = notification.userInfo![AVAudioSessionInterruptionTypeKey] as! NSNumber
let interruptionType = AVAudioSessionInterruptionType(rawValue: interruptionTypeAsObject.unsignedLongValue)
if let type = interruptionType{
if type == .Ended{
/* resume the audio if needed */
} }
debugPrintln("interruption")
}
// ======== respond to remote controls
override func canBecomeFirstResponder() -> Bool {
return true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.becomeFirstResponder()
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
}
override func remoteControlReceivedWithEvent(event: UIEvent) {
/*
let rc = event.subtype
if let theAudioPlayer = self.player {
println("received remote control \(rc.rawValue)") // 101 = pause, 100 = play
switch rc {
case .RemoteControlTogglePlayPause:
if theAudioPlayer.playing { theAudioPlayer.pause() } else { theAudioPlayer.play() }
case .RemoteControlPlay:
theAudioPlayer.play()
case .RemoteControlPause:
theAudioPlayer.pause()
default:break
}
}
*/
}
}
| gpl-2.0 | cc8b64e63d42bb77fe709c4490f5c1dd | 30.628676 | 161 | 0.585145 | 4.981471 | false | false | false | false |
sameertotey/LimoService | LimoService/RequestInfoViewController.swift | 1 | 17153 | //
// RequestInfoViewController.swift
// LimoService
//
// Created by Sameer Totey on 4/22/15.
// Copyright (c) 2015 Sameer Totey. All rights reserved.
//
import UIKit
class RequestInfoViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var dateButton: UIButton!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var fromTextField: UITextField!
@IBOutlet weak var toTextField: UITextField!
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!
@IBOutlet weak var label4: UILabel!
@IBOutlet weak var label5: UILabel!
@IBOutlet weak var label6: UILabel!
@IBOutlet weak var line1: UIView!
@IBOutlet weak var line2: UIView!
@IBOutlet weak var line3: UIView!
@IBOutlet weak var line4: UIView!
@IBOutlet weak var fromImage: UIImageView!
@IBOutlet weak var toImage: UIImageView!
@IBOutlet weak var passengersImage: UIImageView!
@IBOutlet weak var bagsImage: UIImageView!
@IBOutlet weak var dateImage: UIImageView!
@IBOutlet var tapGestureRecognizer: UITapGestureRecognizer!
var savedLabel1: UILabel!
var savedLabel2: UILabel!
var savedLabel3: UILabel!
var savedLabel4: UILabel!
var savedLabel5: UILabel!
var savedLabel6: UILabel!
var savedLine1: UIView!
var savedLine2: UIView!
var savedLine3: UIView!
var savedLine4: UIView!
var savedFromImage: UIImageView!
var savedToImage: UIImageView!
var savedPassengersImage: UIImageView!
var savedBagsImage: UIImageView!
var savedDateImage: UIImageView!
var savedDatePicker: UIDatePicker!
var savedDateButton: UIButton!
var savedFromTextField: UITextField!
var savedToTextField: UITextField!
var limoRequest: LimoRequest? {
didSet {
updateUI()
}
}
weak var delegate: RequestInfoDelegate?
var date: NSDate? {
didSet {
if date != nil {
datePicker?.minimumDate = date!.earlierDate(NSDate())
datePicker?.date = date!
dateString = dateFormatter.stringFromDate(date!)
updateDatePickerLabel()
}
}
}
var dateString: String?
var enabled: Bool = true {
didSet {
dateButton.enabled = enabled
datePicker.enabled = enabled
fromTextField.enabled = enabled
}
}
private func updateUI() {
if let datePicker = datePicker {
if limoRequest == nil {
placeEditableView()
} else {
placeDisplayView()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// save a reference to all the views so that they are not deallocated by ARC
savedDatePicker = datePicker
savedDateButton = dateButton
savedLabel1 = label1
savedLabel2 = label2
savedLabel3 = label3
savedLabel4 = label4
savedLabel5 = label5
savedLabel6 = label6
let fromImageView = UIImageView(image: UIImage(named: "FromPin"))
fromTextField.leftView = fromImageView
fromTextField.leftViewMode = .Always
let toImageView = UIImageView(image: UIImage(named: "ToPin"))
toTextField.leftView = toImageView
toTextField.leftViewMode = .Always
savedFromTextField = fromTextField
savedToTextField = toTextField
savedFromImage = fromImage
savedToImage = toImage
savedDateImage = dateImage
savedPassengersImage = passengersImage
savedBagsImage = bagsImage
savedLine1 = line1
savedLine2 = line2
savedLine3 = line3
savedLine4 = line4
updateUI()
}
func configureDatePicker() {
datePicker?.datePickerMode = .DateAndTime
// Set min/max date for the date picker.
// As an example we will limit the date between now and 15 days from now.
let now = NSDate()
datePicker?.minimumDate = now
date = now
let currentCalendar = NSCalendar.currentCalendar()
let dateComponents = NSDateComponents()
dateComponents.day = 15
let fifteenDaysFromNow = currentCalendar.dateByAddingComponents(dateComponents, toDate: now, options: nil)
datePicker?.maximumDate = fifteenDaysFromNow
datePicker?.minuteInterval = 2
datePicker?.addTarget(self, action: "updateDatePickerLabel", forControlEvents: .ValueChanged)
updateDatePickerLabel()
}
/// A date formatter to format the `date` property of `datePicker`.
lazy var dateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .ShortStyle
return dateFormatter
}()
func updateDatePickerLabel() {
dateButton?.setTitle(dateFormatter.stringFromDate(datePicker.date), forState: .Normal)
if let date = datePicker?.date {
delegate?.dateUpdated(date, newDateString: dateFormatter.stringFromDate(date))
}
}
var datePickerHidden = false {
didSet {
if datePickerHidden != oldValue {
var viewsDict = Dictionary <String, UIView>()
viewsDict["dateButton"] = dateButton
viewsDict["datePicker"] = datePicker
viewsDict["fromTextField"] = fromTextField
viewsDict["toTextField"] = toTextField
view.subviews.map({ $0.removeFromSuperview() })
view.addSubview(dateButton)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[dateButton]-|", options: nil, metrics: nil, views: viewsDict))
if datePickerHidden {
view.addSubview(fromTextField)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[fromTextField]-|", options: nil, metrics: nil, views: viewsDict))
view.addSubview(toTextField)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[toTextField]-|", options: nil, metrics: nil, views: viewsDict))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[dateButton]-2-[fromTextField]-2-[toTextField]|", options: nil, metrics: nil, views: viewsDict))
} else {
view.addSubview(datePicker)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[datePicker]-|", options: nil, metrics: nil, views: viewsDict))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[dateButton][datePicker]|", options: nil, metrics: nil, views: viewsDict))
}
let heightNeeded: CGFloat
if datePickerHidden {
heightNeeded = dateButton.sizeThatFits(self.view.bounds.size).height + fromTextField.sizeThatFits(self.view.bounds.size).height + toTextField.sizeThatFits(self.view.bounds.size).height
} else {
heightNeeded = dateButton.sizeThatFits(self.view.bounds.size).height + datePicker.sizeThatFits(self.view.bounds.size).height
}
delegate?.neededHeight(heightNeeded)
}
}
}
// MARK: - Actions
@IBAction func buttonTouched(sender: UIButton) {
datePickerHidden = !datePickerHidden
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
var field: ActiveField
switch textField {
case fromTextField:
field = .From
delegate?.textFieldActivated(field)
case toTextField:
field = .To
delegate?.textFieldActivated(field)
default:
println("unknown text field")
}
return false
}
func placeEditableView() {
configureDatePicker()
if datePicker != nil {
datePickerHidden = !datePickerHidden
datePickerHidden = true
}
tapGestureRecognizer.enabled = false
}
func placeDisplayView() {
tapGestureRecognizer.enabled = true
var viewsDict = Dictionary <String, UIView>()
view.subviews.map({ $0.removeFromSuperview() })
label1.text = nil
label2.text = nil
label3.text = nil
label4.text = nil
label5.text = nil
label6.text = nil
[line1, line2, line3, line4].map({
$0.subviews.map({ $0.removeFromSuperview() })
})
viewsDict["line1"] = line1
viewsDict["line2"] = line2
viewsDict["line3"] = line3
viewsDict["line4"] = line4
viewsDict["label1"] = label1
viewsDict["label2"] = label2
viewsDict["label3"] = label3
viewsDict["label4"] = label4
viewsDict["label5"] = label5
viewsDict["label6"] = label6
viewsDict["fromImage"] = fromImage
viewsDict["toImage"] = toImage
viewsDict["passengersImage"] = passengersImage
viewsDict["bagsImage"] = bagsImage
view.addSubview(line1)
view.addSubview(line2)
view.addSubview(line3)
view.addSubview(line4)
setLines(viewsDict)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[line1]", options: nil, metrics: nil, views: viewsDict))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[line2]", options: nil, metrics: nil, views: viewsDict))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[line3]", options: nil, metrics: nil, views: viewsDict))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[line4]", options: nil, metrics: nil, views: viewsDict))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[line1][line2][line3][line4]", options: nil, metrics: nil, views: viewsDict))
view.setNeedsLayout()
view.layoutIfNeeded()
let heightNeeded = line1.sizeThatFits(view.bounds.size).height +
line2.sizeThatFits(view.bounds.size).height +
line3.sizeThatFits(view.bounds.size).height +
line4.sizeThatFits(view.bounds.size).height
delegate?.neededHeight(heightNeeded)
}
func setLines(viewsDict: Dictionary <String, UIView>) {
line1.removeConstraints(line1.constraints())
label1.text = limoRequest?.whenString
line1.addSubview(label1)
if let numPassengers = limoRequest?.numPassengers {
label2.text = "\(numPassengers) "
}
line1.addSubview(passengersImage)
line1.addSubview(label2)
if let numBags = limoRequest?.numBags {
label3.text = "\(numBags) "
}
line1.addSubview(bagsImage)
line1.addSubview(label3)
let label1Size = label1.sizeThatFits(view.bounds.size)
let label2Size = label2.sizeThatFits(view.bounds.size)
let label3Size = label3.sizeThatFits(view.bounds.size)
let passengersImageSize = passengersImage.sizeThatFits(view.bounds.size)
let bagsImageSize = bagsImage.sizeThatFits(view.bounds.size)
let line1Height = max(label1Size.height, label2Size.height, label3Size.height, passengersImageSize.height, bagsImageSize.height)
line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label1]-[passengersImage]-[label2]-[bagsImage]-[label3]-|", options: nil, metrics: nil, views: viewsDict))
line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label1]", options: nil, metrics: nil, views: viewsDict))
line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[passengersImage]", options: nil, metrics: nil, views: viewsDict))
line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label2]|", options: nil, metrics: nil, views: viewsDict))
line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[bagsImage]", options: nil, metrics: nil, views: viewsDict))
line1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label3]", options: nil, metrics: nil, views: viewsDict))
line1.addConstraint(NSLayoutConstraint(item: line1, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: line1Height))
line2.removeConstraints(line2.constraints())
if let fromAddress = limoRequest?.fromAddress, fromName = limoRequest?.fromName {
if !fromAddress.isEmpty {
label4.text = fromAddress.fullAddressString(fromName)
line2.addSubview(fromImage)
line2.addSubview(label4)
line2.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[fromImage]-[label4]-|", options: nil, metrics: nil, views: viewsDict))
line2.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[fromImage]", options: nil, metrics: nil, views: viewsDict))
line2.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label4]", options: nil, metrics: nil, views: viewsDict))
let label4Size = label4.sizeThatFits(view.bounds.size)
let fromImageSize = fromImage.sizeThatFits(view.bounds.size)
let line2Height = max(label4Size.height, fromImageSize.height)
line2.addConstraint(NSLayoutConstraint(item: line2, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: line2Height))
}
}
line3.removeConstraints(line3.constraints())
if let toAddress = limoRequest?.toAddress, toName = limoRequest?.toName {
if !toAddress.isEmpty {
label5.text = toAddress.fullAddressString(toName)
line3.addSubview(toImage)
line3.addSubview(label5)
line3.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[toImage]-[label5]-|", options: nil, metrics: nil, views: viewsDict))
line3.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[toImage]", options: nil, metrics: nil, views: viewsDict))
line3.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label5]", options: nil, metrics: nil, views: viewsDict))
let label5Size = label5.sizeThatFits(view.bounds.size)
let toImageSize = fromImage.sizeThatFits(view.bounds.size)
let line3Height = max(label5Size.height, toImageSize.height)
line3.addConstraint(NSLayoutConstraint(item: line3, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: line3Height))
}
}
// line3.setNeedsLayout()
// line3.layoutIfNeeded()
// line3.sizeToFit()
// let line3Size = line3.sizeThatFits(CGSizeMake(view.frame.width, 600))
line4.removeConstraints(line4.constraints())
if let comment = limoRequest?.comment {
label6.text = comment
line4.addSubview(label6)
line4.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label6]-|", options: nil, metrics: nil, views: viewsDict))
line4.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label6]", options: nil, metrics: nil, views: viewsDict))
line4.addConstraint(NSLayoutConstraint(item: line4, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: label6.sizeThatFits(view.bounds.size).height))
}
// if let toAddress = limoRequest?.toAddress {
// if !toAddress.isEmpty {
// labelLine3.text = "To: \(toAddress) "
// }
// }
// if let numBags = limoRequest?.numBags, numPassengers = limoRequest?.numPassengers, vehicle = limoRequest?.preferredVehicle {
// labelLine4.text = "Passengers:\(numPassengers) Bags:\(numBags) for \(vehicle)"
// }
// if let comment = limoRequest?.comment {
// labelLine5.text = comment
// }
}
@IBAction func viewTapped(sender: AnyObject) {
println("view was tapped.......")
delegate?.displayViewTapped()
}
}
extension String {
func fullAddressString(name: String) -> String {
let fullString: String
if self.hasPrefix(name) {
fullString = String(map(self.generate()) {
$0 == "\n" ? ";" : $0
})
} else {
fullString = String(map((name + ";" + self).generate()) {
$0 == "\n" ? ";" : $0
})
}
return fullString
}
}
| mit | ac2d3eaaa750a7927e54fd6499fbce5d | 41.775561 | 217 | 0.637789 | 5.0199 | false | false | false | false |
dalu93/SwiftHelpSet | Sources/Utilities/Resource.swift | 1 | 3424 | //
// Resource.swift
// SwiftHelpSet
//
// Created by Luca D'Alberti on 7/15/16.
// Copyright © 2016 dalu93. All rights reserved.
//
import Foundation
/**
Enum containing all the supported HTTP methods
*/
public enum HTTPMethod : String {
case GET
case POST
case PUT
case DELETE
case OPTIONS
case HEAD
case PATCH
case TRACE
case CONNECT
case ERROR
}
/**
* The `HTTPHeader` struct contains the needed informations to describe
* completely an HTTP header field
*/
public struct HTTPHeader {
/// The name of the HTTP header field
public let name: String
/// The value of the HTTP header field
public let value: String
}
// MARK: - DictionaryConvertible
extension HTTPHeader: DictionaryConvertible {
public func toDictionary() -> [String : String]? {
return [
name : value
]
}
}
// MARK: - Prefilled HTTPHeaders
public extension HTTPHeader {
static func HeaderWith(contentType: String) -> HTTPHeader {
return HTTPHeader(
name: "Content-Type",
value: contentType
)
}
static var JSONContentType: HTTPHeader {
return HTTPHeader.HeaderWith(contentType: "application/json")
}
}
/**
* The `Parameter` struct contains the needed informations to descibe
* a request parameter. It can be query parameter or body parameter
*/
public struct Parameter {
/// The parameter name
public let field: String
/// The parameter value
public let value: AnyObject
}
// MARK: - DictionaryConvertible
extension Parameter: DictionaryConvertible {
public func toDictionary() -> [String : AnyObject]? {
return [
field : value
]
}
}
/**
* The `Endpoint` struct contains all the info regarding
* the endpoint you are trying to reach
*/
public struct Endpoint {
/// The path
public let path : String
/// The HTTP method
public let method : HTTPMethod
/// The parameters
fileprivate let _parameters : [Parameter]?
/// The headers
fileprivate let _headers : [HTTPHeader]?
}
// MARK: - Computed properties
public extension Endpoint {
/// The encoded parameters, ready for the use
public var parameters: [String : AnyObject]? {
guard let parameters = _parameters else { return nil }
var encParameters: [String : AnyObject] = [:]
parameters.forEach {
guard let paramDict = $0.toDictionary() else { return }
encParameters += paramDict
}
return encParameters
}
/// The encoded headers, ready for the use
public var headers: [String : String]? {
guard let headers = _headers else { return nil }
var encHeaders: [String : String] = [:]
headers.forEach {
guard let headerDict = $0.toDictionary() else { return }
encHeaders += headerDict
}
return encHeaders
}
}
/**
* The `Resource` struct contains the information about how to retrieve a
* specific resource and how to parse it from a JSON response
*/
public struct Resource<A> {
/// The endpont to reach
public let endpoint : Endpoint
/// A closure that indicates how to convert the response in a generic object
public let parseJSON : (AnyObject) -> A?
}
| mit | 4e6d72ae3c57df162c635e0fb0eb175e | 22.128378 | 80 | 0.619924 | 4.767409 | false | false | false | false |
WickedColdfront/Slide-iOS | Slide for Reddit/CommentDepthCell.swift | 1 | 44817 | //
// UZTextViewCell.swift
// Slide for Reddit
//
// Created by Carlos Crane on 12/31/16.
// Copyright © 2016 Haptic Apps. All rights reserved.
//
import UIKit
import reddift
import UZTextView
import ImageViewer
import TTTAttributedLabel
import RealmSwift
import AudioToolbox
protocol UZTextViewCellDelegate: class {
func pushedMoreButton(_ cell: CommentDepthCell)
func pushedSingleTap(_ cell: CommentDepthCell)
func showCommentMenu(_ cell: CommentDepthCell)
func hideCommentMenu(_ cell: CommentDepthCell)
var menuShown : Bool {get set}
var menuId : String {get set}
}
class CommentMenuCell: UITableViewCell {
var upvote = UIButton()
var downvote = UIButton()
var reply = UIButton()
var more = UIButton()
var edit = UIButton()
var delete = UIButton()
var editShown = false
var archived = false
var comment : RComment?
var commentView: CommentDepthCell?
var parent : CommentViewController?
func setComment(comment: RComment, cell: CommentDepthCell, parent: CommentViewController){
self.comment = comment
self.parent = parent
self.commentView = cell
editShown = AccountController.isLoggedIn && comment.author == AccountController.currentName
archived = comment.archived
self.contentView.backgroundColor = ColorUtil.getColorForSub(sub: comment.subreddit)
updateConstraints()
}
func edit(_ s: AnyObject){
self.parent!.editComment()
}
func doDelete(_ s: AnyObject){
self.parent!.deleteComment(cell: commentView!)
}
func upvote(_ s: AnyObject){
parent!.vote(comment: comment!, dir: .up)
commentView!.refresh(comment: comment!, submissionAuthor: (parent!.submission?.author)!, text: commentView!.cellContent!)
parent!.hideCommentMenu(commentView!)
}
func downvote(_ s: AnyObject){
parent!.vote(comment: comment!, dir: .down)
commentView!.refresh(comment: comment!, submissionAuthor: (parent!.submission?.author)!, text: commentView!.cellContent!)
parent!.hideCommentMenu(commentView!)
}
func more(_ s: AnyObject) {
parent!.moreComment(commentView!)
}
func reply(_ s: AnyObject){
self.parent!.doReply()
}
var sideConstraint: [NSLayoutConstraint] = []
override func updateConstraints() {
super.updateConstraints()
var width = 375
width = width/(archived ? 1 : (editShown ? 6 : 4))
if(editShown){
edit.isHidden = false
delete.isHidden = false
} else {
edit.isHidden = true
delete.isHidden = true
}
if(archived){
edit.isHidden = true
delete.isHidden = true
upvote.isHidden = true
downvote.isHidden = true
reply.isHidden = true
}
let metrics:[String:Int]=["width":Int(width), "full": Int(self.contentView.frame.size.width)]
let views=["upvote": upvote, "downvote":downvote, "edit":edit, "delete":delete, "view":contentView, "more":more, "reply":reply] as [String : Any]
let replyStuff = !archived && AccountController.isLoggedIn ? "[reply(width)]-0-[downvote(width)]-0-[upvote(width)]-0-" : ""
let editStuff = (!archived && editShown) ? "[edit(width)]-0-[delete(width)]-0-" : ""
self.contentView.removeConstraints(sideConstraint)
sideConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:[more(width)]-0-\(editStuff)\(replyStuff)|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views)
sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[more(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views))
sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[edit(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views))
sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[delete(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views))
sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[reply(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views))
sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[downvote(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views))
sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[upvote(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views))
sideConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[view(60)]", options: NSLayoutFormatOptions(rawValue:0), metrics: metrics, views: views))
self.contentView.addConstraints(sideConstraint)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.upvote = UIButton.init(type: .custom)
self.downvote = UIButton.init(type: .custom)
self.reply = UIButton.init(type: .custom)
self.more = UIButton.init(type: .custom)
self.edit = UIButton.init(type: .custom)
self.delete = UIButton.init(type: .custom)
upvote.setImage(UIImage.init(named: "upvote")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal)
downvote.setImage(UIImage.init(named: "downvote")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal)
reply.setImage(UIImage.init(named: "reply")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal)
more.setImage(UIImage.init(named: "ic_more_vert_white")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal)
edit.setImage(UIImage.init(named: "edit")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal)
delete.setImage(UIImage.init(named: "delete")?.imageResize(sizeChange: CGSize.init(width: 30, height: 30)), for: .normal)
upvote.translatesAutoresizingMaskIntoConstraints = false
downvote.translatesAutoresizingMaskIntoConstraints = false
more.translatesAutoresizingMaskIntoConstraints = false
reply.translatesAutoresizingMaskIntoConstraints = false
edit.translatesAutoresizingMaskIntoConstraints = false
delete.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(upvote)
self.contentView.addSubview(more)
self.contentView.addSubview(downvote)
self.contentView.addSubview(reply)
self.contentView.addSubview(edit)
self.contentView.addSubview(delete)
upvote.addTarget(self, action: #selector(CommentMenuCell.upvote(_:)), for: UIControlEvents.touchUpInside)
downvote.addTarget(self, action: #selector(CommentMenuCell.downvote(_:)), for: UIControlEvents.touchUpInside)
more.addTarget(self, action: #selector(CommentMenuCell.more(_:)), for: UIControlEvents.touchUpInside)
reply.addTarget(self, action: #selector(CommentMenuCell.reply(_:)), for: UIControlEvents.touchUpInside)
edit.addTarget(self, action: #selector(CommentMenuCell.edit(_:)), for: UIControlEvents.touchUpInside)
delete.addTarget(self, action: #selector(CommentMenuCell.doDelete(_:)), for: UIControlEvents.touchUpInside)
updateConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CommentDepthCell: MarginedTableViewCell, TTTAttributedLabelDelegate, UIViewControllerPreviewingDelegate {
var moreButton: UIButton = UIButton()
var sideView: UIView = UIView()
var sideViewSpace: UIView = UIView()
var topViewSpace: UIView = UIView()
var title: TTTAttributedLabel = TTTAttributedLabel.init(frame: CGRect.zero)
var c: UIView = UIView()
var children: UILabel = UILabel()
var comment:RComment?
var depth:Int = 0
func attributedLabel(_ label: TTTAttributedLabel!, didLongPressLinkWith url: URL!, at point: CGPoint) {
if parent != nil{
let sheet = UIAlertController(title: url.absoluteString, message: nil, preferredStyle: .actionSheet)
sheet.addAction(
UIAlertAction(title: "Close", style: .cancel) { (action) in
sheet.dismiss(animated: true, completion: nil)
}
)
let open = OpenInChromeController.init()
if(open.isChromeInstalled()){
sheet.addAction(
UIAlertAction(title: "Open in Chrome", style: .default) { (action) in
_ = open.openInChrome(url, callbackURL: nil, createNewTab: true)
}
)
}
sheet.addAction(
UIAlertAction(title: "Open in Safari", style: .default) { (action) in
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
sheet.dismiss(animated: true, completion: nil)
}
)
sheet.addAction(
UIAlertAction(title: "Open", style: .default) { (action) in
/* let controller = WebViewController(nibName: nil, bundle: nil)
controller.url = url
let nav = UINavigationController(rootViewController: controller)
self.present(nav, animated: true, completion: nil)*/
}
)
sheet.addAction(
UIAlertAction(title: "Copy URL", style: .default) { (action) in
UIPasteboard.general.setValue(url, forPasteboardType: "public.url")
sheet.dismiss(animated: true, completion: nil)
}
)
sheet.modalPresentationStyle = .popover
if let presenter = sheet.popoverPresentationController {
presenter.sourceView = label
presenter.sourceRect = label.bounds
}
parent?.present(sheet, animated: true, completion: nil)
}
}
var parent: CommentViewController?
func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) {
parent?.doShow(url: url)
}
func upvote(){
}
var delegate: UZTextViewCellDelegate? = nil
var content: Object? = nil
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.title = TTTAttributedLabel(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
title.numberOfLines = 0
title.font = FontGenerator.fontOfSize(size: 12, submission: false)
title.isUserInteractionEnabled = true
title.delegate = self
title.textColor = ColorUtil.fontColor
self.children = UILabel(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 15))
children.numberOfLines = 1
children.font = FontGenerator.boldFontOfSize(size: 12, submission: false)
children.textColor = UIColor.white
children.layer.shadowOffset = CGSize(width: 0, height: 0)
children.layer.shadowOpacity = 0.4
children.layer.shadowRadius = 4
let padding = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
self.moreButton = UIButton(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
self.sideView = UIView(frame: CGRect(x: 0, y: 0, width: 4, height: CGFloat.greatestFiniteMagnitude))
self.sideViewSpace = UIView(frame: CGRect(x: 0, y: 0, width: 4, height: CGFloat.greatestFiniteMagnitude))
self.topViewSpace = UIView(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 4))
self.c = children.withPadding(padding: padding)
c.alpha = 0
c.backgroundColor = ColorUtil.accentColorForSub(sub: "")
c.layer.cornerRadius = 4
c.clipsToBounds = true
moreButton.translatesAutoresizingMaskIntoConstraints = false
sideView.translatesAutoresizingMaskIntoConstraints = false
sideViewSpace.translatesAutoresizingMaskIntoConstraints = false
topViewSpace.translatesAutoresizingMaskIntoConstraints = false
title.translatesAutoresizingMaskIntoConstraints = false
children.translatesAutoresizingMaskIntoConstraints = false
c.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(moreButton)
self.contentView.addSubview(sideView)
self.contentView.addSubview(sideViewSpace)
self.contentView.addSubview(topViewSpace)
self.contentView.addSubview(title)
self.contentView.addSubview(c)
moreButton.addTarget(self, action: #selector(CommentDepthCell.pushedMoreButton(_:)), for: UIControlEvents.touchUpInside)
let tapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(self.handleShortPress(_:)))
tapGestureRecognizer.cancelsTouchesInView = false
tapGestureRecognizer.delegate = self
self.title.addGestureRecognizer(tapGestureRecognizer)
long = UILongPressGestureRecognizer.init(target: self, action: #selector(self.handleLongPress(_:)))
long.minimumPressDuration = 0.25
long.delegate = self
self.addGestureRecognizer(long)
self.contentView.backgroundColor = ColorUtil.foregroundColor
sideViewSpace.backgroundColor = ColorUtil.backgroundColor
topViewSpace.backgroundColor = ColorUtil.backgroundColor
self.clipsToBounds = true
}
func doLongClick(){
timer!.invalidate()
AudioServicesPlaySystemSound(1519)
if(!self.cancelled){
if(false){
if(self.delegate!.menuShown ){ //todo check if comment id is the same as this comment id
self.showMenu(nil)
} else {
self.pushedSingleTap(nil)
}
} else {
self.showMenu(nil)
}
}
}
var timer : Timer?
var cancelled = false
func handleLongPress(_ sender: UILongPressGestureRecognizer){
if(sender.state == UIGestureRecognizerState.began){
cancelled = false
timer = Timer.scheduledTimer(timeInterval: 0.25,
target: self,
selector: #selector(self.doLongClick),
userInfo: nil,
repeats: false)
}
if (sender.state == UIGestureRecognizerState.ended) {
timer!.invalidate()
cancelled = true
}
}
func handleShortPress(_ sender: UIGestureRecognizer){
if(false || (self.delegate!.menuShown && delegate!.menuId == (content as! RComment).getId())) {
self.showMenu(sender)
} else {
self.pushedSingleTap(sender)
}
}
override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if(gestureRecognizer.view == self.title){
return self.title.link(at: touch.location(in: self.title)) == nil
}
return true
}
var long = UILongPressGestureRecognizer.init(target: self, action: nil)
func showMenu(_ sender: AnyObject?){
if let del = self.delegate {
if(del.menuShown && del.menuId == (content as! RComment).getId()){
del.hideCommentMenu(self)
} else {
del.showCommentMenu(self)
}
}
}
func vote(){
if(content is RComment){
let current = ActionStates.getVoteDirection(s: comment!)
let dir = (current == VoteDirection.none) ? VoteDirection.up : VoteDirection.none
var direction = dir
switch(ActionStates.getVoteDirection(s: comment!)){
case .up:
if(dir == .up){
direction = .none
}
break
case .down:
if(dir == .down){
direction = .none
}
break
default:
break
}
do {
try parent?.session?.setVote(direction, name: (comment!.name), completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success( _): break
}
})
} catch { print(error) }
ActionStates.setVoteDirection(s: comment!, direction: direction)
refresh(comment: content as! RComment, submissionAuthor: savedAuthor, text: cellContent!)
}
}
func more(_ par: CommentViewController){
let alertController = UIAlertController(title: "Comment by /u/\(comment!.author)", message: "", preferredStyle: .actionSheet)
let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
alertController.addAction(cancelActionButton)
let profile: UIAlertAction = UIAlertAction(title: "/u/\(comment!.author)'s profile", style: .default) { action -> Void in
par.show(ProfileViewController.init(name: self.comment!.author), sender: self)
}
alertController.addAction(profile)
let share: UIAlertAction = UIAlertAction(title: "Share comment permalink", style: .default) { action -> Void in
let activityViewController = UIActivityViewController(activityItems: [self.comment!.permalink], applicationActivities: nil)
par.present(activityViewController, animated: true, completion: {})
}
alertController.addAction(share)
if(AccountController.isLoggedIn){
let save: UIAlertAction = UIAlertAction(title: "Save", style: .default) { action -> Void in
par.saveComment(self.comment!)
}
alertController.addAction(save)
}
let report: UIAlertAction = UIAlertAction(title: "Report", style: .default) { action -> Void in
par.report(self.comment!)
}
alertController.addAction(report)
alertController.modalPresentationStyle = .popover
if let presenter = alertController.popoverPresentationController {
presenter.sourceView = moreButton
presenter.sourceRect = moreButton.bounds
}
par.parent?.present(alertController, animated: true, completion: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var sideConstraint: [NSLayoutConstraint]?
func collapse(childNumber: Int){
children.text = "+\(childNumber)"
UIView.animate(withDuration: 0.4, delay: 0.0, options:
UIViewAnimationOptions.curveEaseOut, animations: {
self.c.alpha = 1
}, completion: { finished in
})
}
func expand(){
UIView.animate(withDuration: 0.4, delay: 0.0, options:
UIViewAnimationOptions.curveEaseOut, animations: {
self.c.alpha = 0
}, completion: { finished in
})
}
var oldDepth = 0
func updateDepthConstraints(){
if(sideConstraint != nil){
self.contentView.removeConstraints(sideConstraint!)
}
let metrics=["marginTop": marginTop, "nmarginTop": -marginTop, "horizontalMargin":75,"top":0,"bottom":0,"separationBetweenLabels":0,"labelMinHeight":75, "sidewidth":4*(depth ), "width":sideWidth]
let views=["title": title, "topviewspace":topViewSpace, "more": moreButton, "side":sideView, "cell":self.contentView, "sideviewspace":sideViewSpace] as [String : Any]
sideConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(-8)-[sideviewspace(sidewidth)]-0-[side(width)]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views)
sideConstraint!.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-(-8)-[sideviewspace(sidewidth)]-0-[side(width)]-12-[title]-4-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
self.contentView.addConstraints(sideConstraint!)
}
var menuC : [NSLayoutConstraint] = []
func doHighlight(){
oldDepth = depth
depth = 1
updateDepthConstraints()
self.contentView.backgroundColor = ColorUtil.foregroundColor.add(overlay: ColorUtil.getColorForSub(sub: ((comment)!.subreddit)).withAlphaComponent(0.5))
}
func doUnHighlight(){
depth = oldDepth
updateDepthConstraints()
self.contentView.backgroundColor = ColorUtil.foregroundColor
}
override func updateConstraints() {
super.updateConstraints()
let metrics=["marginTop": marginTop, "nmarginTop": -marginTop, "horizontalMargin":75,"top":0,"bottom":0,"separationBetweenLabels":0,"labelMinHeight":75, "sidewidth":4*(depth ), "width":sideWidth]
let views=["title": title, "topviewspace":topViewSpace, "children":c, "more": moreButton, "side":sideView, "cell":self.contentView, "sideviewspace":sideViewSpace] as [String : Any]
contentView.bounds = CGRect.init(x: 0,y: 0, width: contentView.frame.size.width , height: contentView.frame.size.height + CGFloat(marginTop))
var constraint:[NSLayoutConstraint] = []
constraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-(-8)-[sideviewspace]-0-[side]-12-[title]-4-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[topviewspace]-0-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
if(!menuC.isEmpty){
self.contentView.removeConstraints(menuC)
}
menuC = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[topviewspace(marginTop)]-4-[title]-6-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views)
constraint.append(contentsOf:menuC)
constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-2-[more]-2-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-4-[children]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "H:[children]-4-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[topviewspace(marginTop)]-(nmarginTop)-[side]-(-1)-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
constraint.append(contentsOf:NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[topviewspace(marginTop)]-(nmarginTop)-[sideviewspace]-0-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
self.contentView.addConstraints(constraint)
updateDepthConstraints()
}
var sideWidth: Int = 0
var marginTop: Int = 0
func setMore(more: RMore, depth: Int){
self.depth = depth
loading = false
c.alpha = 0
self.contentView.backgroundColor = ColorUtil.foregroundColor
if (depth - 1 > 0) {
sideWidth = 4
marginTop = 1
let i22 = depth - 2;
if(SettingValues.disableColor){
if (i22 % 5 == 0) {
sideView.backgroundColor = GMColor.grey100Color()
} else if (i22 % 4 == 0) {
sideView.backgroundColor = GMColor.grey200Color()
} else if (i22 % 3 == 0) {
sideView.backgroundColor = GMColor.grey300Color()
} else if (i22 % 2 == 0) {
sideView.backgroundColor = GMColor.grey400Color()
} else {
sideView.backgroundColor = GMColor.grey500Color()
}
} else {
if (i22 % 5 == 0) {
sideView.backgroundColor = GMColor.blue500Color()
} else if (i22 % 4 == 0) {
sideView.backgroundColor = GMColor.green500Color()
} else if (i22 % 3 == 0) {
sideView.backgroundColor = GMColor.yellow500Color()
} else if (i22 % 2 == 0) {
sideView.backgroundColor = GMColor.orange500Color()
} else {
sideView.backgroundColor = GMColor.red500Color()
}
}
} else {
marginTop = 8
sideWidth = 0
}
var attr = NSMutableAttributedString()
if(more.children.isEmpty){
attr = NSMutableAttributedString(string: "Continue this thread")
} else {
attr = NSMutableAttributedString(string: "Load \(more.count) more")
}
let font = FontGenerator.fontOfSize(size: 16, submission: false)
let attr2 = attr.reconstruct(with: font, color: ColorUtil.fontColor, linkColor: .white)
title.setText(attr2)
updateDepthConstraints()
}
var numberOfDots = 3
var loading = false
func animateMore() {
loading = true
let attr = NSMutableAttributedString(string: "Loading...")
let font = FontGenerator.fontOfSize(size: 16, submission: false)
let attr2 = NSMutableAttributedString(attributedString: attr.reconstruct(with: font, color: ColorUtil.fontColor, linkColor: UIColor.blue))
title.setText(attr2)
/* possibly todo var timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { (timer) in
print("Firing")
let range = NSMakeRange(attr2.length - self.numberOfDots, self.numberOfDots)
attr2.addAttribute(NSForegroundColorAttributeName, value: UIColor.clear, range: range)
self.textView.attributedString = attr2
self.numberOfDots -= 1
if self.numberOfDots < 0 {
self.numberOfDots = 3
}
if(self.loading == false){
timer.invalidate()
}
}*/
}
func setComment(comment: RComment, depth: Int, parent: CommentViewController, hiddenCount: Int, date: Double, author: String?, text: NSAttributedString){
self.comment = comment
self.cellContent = text
self.contentView.backgroundColor = ColorUtil.foregroundColor
loading = false
if(self.parent == nil){
self.parent = parent
}
if(date != 0 && date < Double(comment.created.timeIntervalSince1970 )){
setIsNew(sub: comment.subreddit)
}
if(hiddenCount > 0){
c.alpha = 1
children.text = "+\(hiddenCount)"
} else {
c.alpha = 0
}
self.depth = depth
if (depth - 1 > 0) {
sideWidth = 4
marginTop = 1
let i22 = depth - 2;
if(SettingValues.disableColor){
if (i22 % 5 == 0) {
sideView.backgroundColor = GMColor.grey100Color()
} else if (i22 % 4 == 0) {
sideView.backgroundColor = GMColor.grey200Color()
} else if (i22 % 3 == 0) {
sideView.backgroundColor = GMColor.grey300Color()
} else if (i22 % 2 == 0) {
sideView.backgroundColor = GMColor.grey400Color()
} else {
sideView.backgroundColor = GMColor.grey500Color()
}
} else {
if (i22 % 5 == 0) {
sideView.backgroundColor = GMColor.blue500Color()
} else if (i22 % 4 == 0) {
sideView.backgroundColor = GMColor.green500Color()
} else if (i22 % 3 == 0) {
sideView.backgroundColor = GMColor.yellow500Color()
} else if (i22 % 2 == 0) {
sideView.backgroundColor = GMColor.orange500Color()
} else {
sideView.backgroundColor = GMColor.red500Color()
}
}
} else {
//marginTop = 8
marginTop = 1
sideWidth = 0
}
refresh(comment: comment, submissionAuthor: author, text: text)
if(!registered){
parent.registerForPreviewing(with: self, sourceView: title)
registered = true
}
updateDepthConstraints()
}
var cellContent: NSAttributedString?
var savedAuthor: String = ""
func refresh(comment: RComment, submissionAuthor: String?, text: NSAttributedString){
var color: UIColor
savedAuthor = submissionAuthor!
switch(ActionStates.getVoteDirection(s: comment)){
case .down:
color = ColorUtil.downvoteColor
break
case .up:
color = ColorUtil.upvoteColor
break
default:
color = ColorUtil.fontColor
break
}
let scoreString = NSMutableAttributedString(string: ((comment.scoreHidden ? "[score hidden]" : "\(getScoreText(comment: comment))") + (comment.controversiality > 0 ? "†" : "" )), attributes: [NSForegroundColorAttributeName: color])
let endString = NSMutableAttributedString(string:" • \(DateFormatter().timeSince(from: comment.created, numericDates: true))" + (comment.isEdited ? ("(edit \(DateFormatter().timeSince(from: comment.edited, numericDates: true)))") : ""), attributes: [NSForegroundColorAttributeName: ColorUtil.fontColor])
let authorString = NSMutableAttributedString(string: "\u{00A0}\(comment.author)\u{00A0}", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: ColorUtil.fontColor])
let flairTitle = NSMutableAttributedString.init(string: "\u{00A0}\(comment.flair)\u{00A0}", attributes: [kTTTBackgroundFillColorAttributeName: ColorUtil.backgroundColor, NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: ColorUtil.fontColor, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3])
let pinned = NSMutableAttributedString.init(string: "\u{00A0}PINNED\u{00A0}", attributes: [kTTTBackgroundFillColorAttributeName: GMColor.green500Color(), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3])
let gilded = NSMutableAttributedString.init(string: "\u{00A0}x\(comment.gilded) ", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false)])
let spacer = NSMutableAttributedString.init(string: " ")
let userColor = ColorUtil.getColorForUser(name: comment.author)
if (comment.distinguished == "admin") {
authorString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor.init(hexString: "#E57373"), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length))
} else if (comment.distinguished == "special") {
authorString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor.init(hexString: "#F44336"), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length))
} else if (comment.distinguished == "moderator") {
authorString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor.init(hexString: "#81C784"), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length))
} else if (AccountController.currentName == comment.author) {
authorString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor.init(hexString: "#FFB74D"), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length))
} else if(submissionAuthor != nil && comment.author == submissionAuthor) {
authorString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor.init(hexString: "#64B5F6"), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length))
} else if (userColor != ColorUtil.baseColor) {
authorString.addAttributes([kTTTBackgroundFillColorAttributeName: userColor, NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length))
}
let infoString = NSMutableAttributedString(string: "\u{00A0}")
infoString.append(authorString)
let tag = ColorUtil.getTagForUser(name: comment.author)
if(!tag.isEmpty){
let tagString = NSMutableAttributedString(string: "\u{00A0}\(tag)\u{00A0}", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: ColorUtil.fontColor])
tagString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor(rgb: 0x2196f3), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: authorString.length))
infoString.append(spacer)
infoString.append(tagString)
}
infoString.append(NSAttributedString(string:" • ", attributes: [NSFontAttributeName: FontGenerator.fontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: ColorUtil.fontColor]))
infoString.append(scoreString)
infoString.append(endString)
if(!comment.flair.isEmpty){
infoString.append(spacer)
infoString.append(flairTitle)
}
if(comment.pinned){
infoString.append(spacer)
infoString.append(pinned)
}
if(comment.gilded > 0){
infoString.append(spacer)
let gild = NSMutableAttributedString.init(string: "G", attributes: [kTTTBackgroundFillColorAttributeName: GMColor.amber500Color(), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3])
infoString.append(gild)
if(comment.gilded > 1){
infoString.append(gilded)
}
}
infoString.append(NSAttributedString.init(string: "\n"))
infoString.append(text)
if(!setLinkAttrs){
let activeLinkAttributes = NSMutableDictionary(dictionary: title.activeLinkAttributes)
activeLinkAttributes[NSForegroundColorAttributeName] = ColorUtil.accentColorForSub(sub: comment.subreddit)
title.activeLinkAttributes = activeLinkAttributes as NSDictionary as! [AnyHashable: Any]
title.linkAttributes = activeLinkAttributes as NSDictionary as! [AnyHashable: Any]
setLinkAttrs = true
}
title.setText(infoString)
}
var setLinkAttrs = false
func setIsContext(){
self.contentView.backgroundColor = GMColor.yellow500Color().withAlphaComponent(0.5)
}
func setIsNew(sub: String){
self.contentView.backgroundColor = ColorUtil.getColorForSub(sub: sub).withAlphaComponent(0.5)
}
func getScoreText(comment: RComment) -> Int {
var submissionScore = comment.score
switch (ActionStates.getVoteDirection(s: comment)) {
case .up:
if(comment.likes != .up){
if(comment.likes == .down){
submissionScore += 1
}
submissionScore += 1
}
break
case .down:
if(comment.likes != .down){
if(comment.likes == .up){
submissionScore -= 1
}
submissionScore -= 1
}
break
case .none:
if(comment.likes == .up && comment.author == AccountController.currentName){
submissionScore -= 1
}
}
return submissionScore
}
var registered:Bool = false
func previewingContext(_ previewingContext: UIViewControllerPreviewing,
viewControllerForLocation location: CGPoint) -> UIViewController? {
let locationInTextView = title.convert(location, to: title)
if let (url, rect) = getInfo(locationInTextView: locationInTextView) {
previewingContext.sourceRect = title.convert(rect, from: title)
if let controller = parent?.getControllerForUrl(baseUrl: url){
return controller
}
}
return nil
}
func getInfo(locationInTextView: CGPoint) -> (URL, CGRect)? {
if let attr = title.link(at: locationInTextView) {
if let url = attr.result.url {
return (url, title.bounds)
}
}
return nil
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
if(viewControllerToCommit is GalleryViewController || viewControllerToCommit is YouTubeViewController){
parent?.presentImageGallery(viewControllerToCommit as! GalleryViewController)
} else {
parent?.show(viewControllerToCommit, sender: parent )
}
}
func pushedMoreButton(_ sender: AnyObject?) {
if let delegate = self.delegate {
delegate.pushedMoreButton(self)
}
}
func longPressed(_ sender: AnyObject?) {
if self.delegate != nil {
}
}
func pushedSingleTap(_ sender: AnyObject?) {
if let delegate = self.delegate {
delegate.pushedSingleTap(self)
}
}
class func margin() -> UIEdgeInsets {
return UIEdgeInsetsMake(4, 0, 2, 0)
}
}
extension UIColor {
func add(overlay: UIColor) -> UIColor {
var bgR: CGFloat = 0
var bgG: CGFloat = 0
var bgB: CGFloat = 0
var bgA: CGFloat = 0
var fgR: CGFloat = 0
var fgG: CGFloat = 0
var fgB: CGFloat = 0
var fgA: CGFloat = 0
self.getRed(&bgR, green: &bgG, blue: &bgB, alpha: &bgA)
overlay.getRed(&fgR, green: &fgG, blue: &fgB, alpha: &fgA)
let r = fgA * fgR + (1 - fgA) * bgR
let g = fgA * fgG + (1 - fgA) * bgG
let b = fgA * fgB + (1 - fgA) * bgB
return UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
}
extension UIView {
func withPadding(padding: UIEdgeInsets) -> UIView {
let container = UIView()
self.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(self)
container.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "|-(\(padding.left))-[view]-(\(padding.right))-|"
, options: [], metrics: nil, views: ["view": self]))
container.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:|-(\(padding.top)@999)-[view]-(\(padding.bottom)@999)-|",
options: [], metrics: nil, views: ["view": self]))
return container
}
}
| apache-2.0 | 7d7d7c1e450df54f0e807f7e698ea679 | 46.518558 | 452 | 0.602656 | 5.356844 | false | false | false | false |
nalexn/ViewInspector | Tests/ViewInspectorTests/ViewSearchTests.swift | 1 | 12708 | import XCTest
import Combine
import SwiftUI
@testable import ViewInspector
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private struct Test {
struct InnerView: View, Inspectable {
var body: some View {
Button(action: { }, label: {
HStack { Text("Btn") }
}).mask(Group {
Text("Test", tableName: "Test", bundle: (try? .testResources()) ?? .main)
})
}
}
struct MainView: View, Inspectable {
var body: some View {
AnyView(Group {
SwiftUI.EmptyView()
.padding()
.overlay(HStack {
SwiftUI.EmptyView()
.id("5")
InnerView()
.padding(15)
.tag(9)
})
Text("123")
.font(.footnote)
.tag(4)
.id(7)
.background(Button("xyz", action: { }))
Divider()
.modifier(Test.Modifier(text: "modifier_0"))
.padding()
.modifier(Test.Modifier(text: "modifier_1"))
})
}
}
struct ConditionalView: View, Inspectable {
let falseCondition = false
let trueCondition = true
var body: some View {
HStack {
if falseCondition {
Text("1")
}
Text("2")
if trueCondition {
Text("3")
}
}
}
}
struct Modifier: ViewModifier, Inspectable {
let text: String
func body(content: Modifier.Content) -> some View {
AnyView(content.overlay(Text(text)))
}
}
struct NonInspectableView: View {
var body: some View {
SwiftUI.EmptyView()
}
}
struct EmptyView: View, Inspectable {
var body: some View {
Text("empty")
}
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
struct ConflictingViewTypeNamesStyle: ButtonStyle {
public func makeBody(configuration: Configuration) -> some View {
Group {
Test.EmptyView()
Label("", image: "")
configuration.label
}
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
final class ViewSearchTests: XCTestCase {
func testFindAll() throws {
let testView = Test.MainView()
XCTAssertEqual(try testView.inspect().findAll(ViewType.ZStack.self).count, 0)
XCTAssertEqual(try testView.inspect().findAll(ViewType.HStack.self).count, 2)
XCTAssertEqual(try testView.inspect().findAll(ViewType.Button.self).count, 2)
XCTAssertEqual(try testView.inspect().findAll(ViewType.Text.self).map({ try $0.string() }),
["Btn", "Test_en", "123", "xyz", "modifier_0", "modifier_1"])
XCTAssertEqual(try testView.inspect().findAll(Test.InnerView.self).count, 1)
XCTAssertEqual(try testView.inspect().findAll(where: { (try? $0.overlay()) != nil }).count, 3)
}
func testFindText() throws {
let testView = Test.MainView()
XCTAssertEqual(try testView.inspect().find(text: "123").pathToRoot,
"view(MainView.self).anyView().group().text(1)")
XCTAssertEqual(try testView.inspect().find(text: "Test_en").pathToRoot,
"""
view(MainView.self).anyView().group().emptyView(0).overlay().hStack()\
.view(InnerView.self, 1).button().mask().group().text(0)
""")
XCTAssertEqual(try testView.inspect().find(text: "Btn").pathToRoot,
"""
view(MainView.self).anyView().group().emptyView(0).overlay().hStack()\
.view(InnerView.self, 1).button().labelView().hStack().text(0)
""")
XCTAssertEqual(try testView.inspect().find(text: "xyz").pathToRoot,
"view(MainView.self).anyView().group().text(1).background().button().labelView().text()")
XCTAssertEqual(try testView.inspect().find(text: "modifier_0").pathToRoot,
"""
view(MainView.self).anyView().group().divider(2).modifier(Modifier.self)\
.anyView().viewModifierContent().overlay().text()
""")
XCTAssertEqual(try testView.inspect().find(text: "modifier_1").pathToRoot,
"""
view(MainView.self).anyView().group().divider(2).modifier(Modifier.self, 1)\
.anyView().viewModifierContent().overlay().text()
""")
XCTAssertEqual(try testView.inspect().find(
textWhere: { _, attr -> Bool in
try attr.font() == .footnote
}).string(), "123")
XCTAssertThrows(try testView.inspect().find(text: "unknown"),
"Search did not find a match")
XCTAssertThrows(try testView.inspect().find(ViewType.Text.self, relation: .parent),
"Search did not find a match")
}
func testSkipFound() throws {
let testView = Test.MainView()
let depthOrdered = try testView.inspect().findAll(ViewType.Text.self)
.map { try $0.string() }
XCTAssertEqual(depthOrdered, ["Btn", "Test_en", "123", "xyz", "modifier_0", "modifier_1"])
for index in 0..<depthOrdered.count {
let string = try testView.inspect().find(ViewType.Text.self,
traversal: .depthFirst,
skipFound: index).string()
XCTAssertEqual(string, depthOrdered[index])
}
XCTAssertThrows(try testView.inspect().find(
ViewType.Text.self, traversal: .depthFirst, skipFound: depthOrdered.count),
"Search did only find 6 matches")
}
func testFindLocalizedTextWithLocaleParameter() throws {
let testView = Test.MainView()
XCTAssertThrows(try testView.inspect().find(text: "Test"),
"Search did not find a match")
XCTAssertNoThrow(try testView.inspect().find(text: "Test",
locale: Locale(identifier: "fr")))
XCTAssertNoThrow(try testView.inspect().find(text: "Test_en"))
XCTAssertNoThrow(try testView.inspect().find(text: "Test_en",
locale: Locale(identifier: "en")))
XCTAssertNoThrow(try testView.inspect().find(text: "Test_en_au",
locale: Locale(identifier: "en_AU")))
XCTAssertNoThrow(try testView.inspect().find(text: "Тест_ru",
locale: Locale(identifier: "ru")))
XCTAssertThrows(try testView.inspect().find(text: "Тест_ru",
locale: Locale(identifier: "en")),
"Search did not find a match")
}
func testFindLocalizedTextWithGlobalDefault() throws {
let testView = Test.MainView()
let defaultLocale = Locale.testsDefault
Locale.testsDefault = Locale(identifier: "ru")
XCTAssertNoThrow(try testView.inspect().find(text: "Тест_ru"))
Locale.testsDefault = defaultLocale
}
func testFindButton() throws {
let testView = Test.MainView()
XCTAssertNoThrow(try testView.inspect().find(button: "Btn"))
XCTAssertNoThrow(try testView.inspect().find(button: "xyz"))
XCTAssertThrows(try testView.inspect().find(button: "unknown"),
"Search did not find a match")
}
func testFindViewWithId() throws {
let testView = Test.MainView()
XCTAssertNoThrow(try testView.inspect().find(viewWithId: "5").emptyView())
XCTAssertNoThrow(try testView.inspect().find(viewWithId: 7).text())
XCTAssertThrows(try testView.inspect().find(viewWithId: 0),
"Search did not find a match")
}
func testFindViewWithTag() throws {
let testView = Test.MainView()
XCTAssertNoThrow(try testView.inspect().find(viewWithTag: 4).text())
XCTAssertNoThrow(try testView.inspect().find(viewWithTag: 9).view(Test.InnerView.self))
XCTAssertThrows(try testView.inspect().find(viewWithTag: 0),
"Search did not find a match")
}
func testFindCustomView() throws {
let testView = Test.MainView()
XCTAssertNoThrow(try testView.inspect().find(Test.InnerView.self))
XCTAssertNoThrow(try testView.inspect().find(Test.InnerView.self, containing: "Btn"))
XCTAssertThrows(try testView.inspect().find(Test.InnerView.self, containing: "123"),
"Search did not find a match")
}
func testFindForConditionalView() throws {
let testView = Test.ConditionalView()
let texts = try testView.inspect().findAll(ViewType.Text.self)
let values = try texts.map { try $0.string() }
XCTAssertEqual(values, ["2", "3"])
}
func testFindMatchingBlockerView() {
let view = AnyView(Test.NonInspectableView().id(5))
XCTAssertNoThrow(try view.inspect().find(viewWithId: 5))
let err = "Search did not find a match. Possible blockers: NonInspectableView"
XCTAssertThrows(try view.inspect().find(ViewType.EmptyView.self,
traversal: .breadthFirst), err)
XCTAssertThrows(try view.inspect().find(ViewType.EmptyView.self,
traversal: .depthFirst), err)
}
func testConflictingViewTypeNames() throws {
guard #available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
else { throw XCTSkip() }
let style = Test.ConflictingViewTypeNamesStyle()
let sut = try style.inspect(isPressed: true)
XCTAssertEqual(try sut.find(text: "empty").pathToRoot,
"group().view(EmptyView.self, 0).text()")
XCTAssertEqual(try sut.find(ViewType.Label.self).pathToRoot,
"group().label(1)")
XCTAssertEqual(try sut.find(ViewType.StyleConfiguration.Label.self).pathToRoot,
"group().styleConfigurationLabel(2)")
}
func testShapesSearching() throws {
let sut = Group {
Circle().inset(by: 5)
Rectangle()
Ellipse().offset(x: 2, y: 3)
}
XCTAssertThrows(try sut.inspect().find(text: "none"),
"Search did not find a match")
let testRect = CGRect(x: 0, y: 0, width: 10, height: 100)
let refPath = Ellipse().offset(x: 2, y: 3).path(in: testRect)
let ellipse = try sut.inspect().find(where: {
try $0.shape().path(in: testRect) == refPath
})
XCTAssertEqual(ellipse.pathToRoot, "group().shape(2)")
}
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
private extension Test {
struct AccessibleView: View, Inspectable {
var body: some View {
Button(action: { }, label: {
HStack {
Text("text1").accessibilityLabel(Text("text1_access"))
}
}).mask(Group {
Text("text2").accessibilityIdentifier("text2_access")
})
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewSearchTests {
func testFindViewWithAccessibilityLabel() throws {
guard #available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
else { throw XCTSkip() }
let sut = Test.AccessibleView()
XCTAssertEqual(try sut.inspect().find(viewWithAccessibilityLabel: "text1_access").pathToRoot,
"view(AccessibleView.self).button().labelView().hStack().text(0)")
XCTAssertThrows(
try sut.inspect().find(viewWithAccessibilityLabel: "abc"),
"Search did not find a match"
)
}
func testFindViewWithAccessibilityIdentifier() throws {
guard #available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
else { throw XCTSkip() }
let sut = Test.AccessibleView()
XCTAssertEqual(try sut.inspect().find(viewWithAccessibilityIdentifier: "text2_access").pathToRoot,
"view(AccessibleView.self).button().mask().group().text(0)")
XCTAssertThrows(
try sut.inspect().find(viewWithAccessibilityIdentifier: "abc"),
"Search did not find a match"
)
}
}
| mit | 8191955286b6d7f1347a8e8c8242ceb6 | 41.604027 | 106 | 0.556238 | 4.6866 | false | true | false | false |
austinzheng/swift | benchmark/single-source/Exclusivity.swift | 28 | 3495 | //===--- Exclusivity.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A set of tests for measuring the enforcement overhead of memory access
// exclusivity rules.
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let Exclusivity = [
// At -Onone
// 25% swift_beginAccess
// 15% tlv_get_addr
// 15% swift_endAccess
BenchmarkInfo(
name: "ExclusivityGlobal",
runFunction: run_accessGlobal,
tags: [.runtime, .cpubench]
),
// At -Onone
// 23% swift_retain
// 22% swift_release
// 9% swift_beginAccess
// 3% swift_endAccess
BenchmarkInfo(
name: "ExclusivityInMatSet",
runFunction: run_accessInMatSet,
tags: [.runtime, .cpubench, .unstable]
),
// At -Onone
// 25% swift_release
// 23% swift_retain
// 16% swift_beginAccess
// 8% swift_endAccess
BenchmarkInfo(
name: "ExclusivityIndependent",
runFunction: run_accessIndependent,
tags: [.runtime, .cpubench]
),
]
// Initially these benchmarks only measure access checks at -Onone. In
// the future, access checks will also be emitted at -O.
// Measure memory access checks on a trivial global.
// ---
public var globalCounter: Int = 0
// TODO:
// - Merge begin/endAccess when no calls intervene (~2x speedup).
// - Move Swift runtime into the OS (~2x speedup).
// - Whole module analysis can remove exclusivity checks (> 10x speedup now, 4x speedup with runtime in OS).
// (The global's "public" qualifier should make the benchmark immune to this optimization.)
@inline(never)
public func run_accessGlobal(_ N: Int) {
globalCounter = 0
for _ in 1...10000*N {
globalCounter += 1
}
CheckResults(globalCounter == 10000*N)
}
// Measure memory access checks on a class property.
//
// Note: The end_unpaired_access forces a callback on the property's
// materializeForSet!
// ---
// Hopefully the optimizer will not see this as "final" and optimize away the
// materializeForSet.
public class C {
public var counter = 0
func inc() {
counter += 1
}
}
// Thunk
@inline(never)
func updateClass(_ c: C) {
c.inc()
}
// TODO: Replacing materializeForSet accessors with yield-once
// accessors should make the callback overhead go away.
@inline(never)
public func run_accessInMatSet(_ N: Int) {
let c = C()
for _ in 1...10000*N {
updateClass(c)
}
CheckResults(c.counter == 10000*N)
}
// Measure nested access to independent objects.
//
// A single access set is still faster than hashing for up to four accesses.
// ---
struct Var {
var val = 0
}
@inline(never)
func update(a: inout Var, b: inout Var, c: inout Var, d: inout Var) {
a.val += 1
b.val += 1
c.val += 1
d.val += 1
}
@inline(never)
public func run_accessIndependent(_ N: Int) {
var a = Var()
var b = Var()
var c = Var()
var d = Var()
let updateVars = {
update(a: &a, b: &b, c: &c, d: &d)
}
for _ in 1...1000*N {
updateVars()
}
CheckResults(a.val == 1000*N && b.val == 1000*N && c.val == 1000*N
&& d.val == 1000*N)
}
| apache-2.0 | e13f22a122d7c680365dcb4a347ad3bd | 24.326087 | 108 | 0.622031 | 3.710191 | false | false | false | false |
codestergit/swift | test/Serialization/class.swift | 2 | 2164 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend -emit-object -emit-module -o %t %S/Inputs/def_class.swift -disable-objc-attr-requires-foundation-module
// RUN: llvm-bcanalyzer %t/def_class.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -emit-sil -Xllvm -sil-disable-pass="External Defs To Decls" -sil-debug-serialization -I %t %s | %FileCheck %s -check-prefix=SIL
// RUN: echo "import def_class; struct A : ClassProto {}" | not %target-swift-frontend -typecheck -I %t - 2>&1 | %FileCheck %s -check-prefix=CHECK-STRUCT
// CHECK-NOT: UnknownCode
// CHECK-STRUCT: non-class type 'A' cannot conform to class protocol 'ClassProto'
// Make sure we can "merge" def_class.
// RUN: %target-swift-frontend -emit-module -o %t-merged.swiftmodule %t/def_class.swiftmodule -module-name def_class
import def_class
var a : Empty
var b = TwoInts(a: 1, b: 2)
var computedProperty : ComputedProperty
var sum = b.x + b.y + computedProperty.value
var intWrapper = ResettableIntWrapper()
var r : Resettable = intWrapper
r.reset()
r.doReset()
class AnotherIntWrapper : SpecialResettable, ClassProto {
init() { value = 0 }
var value : Int
func reset() {
value = 0
}
func compute() {
value = 42
}
}
var intWrapper2 = AnotherIntWrapper()
r = intWrapper2
r.reset()
var c : Cacheable = intWrapper2
c.compute()
c.reset()
var p = Pair(a: 1, b: 2.5)
p.first = 2
p.second = 5.0
struct Int {}
var gc = GenericCtor<Int>()
gc.doSomething()
a = StillEmpty()
r = StillEmpty()
var bp = BoolPair<Bool>()
bp.bothTrue()
var rawBP : Pair<Bool, Bool>
rawBP = bp
var rev : SpecialPair<Double>
rev.first = 42
var comp : Computable = rev
var simpleSub = ReadonlySimpleSubscript()
var subVal = simpleSub[4]
var complexSub = ComplexSubscript()
complexSub[4, false] = complexSub[3, true]
var rsrc = Resource()
getReqPairLike()
// SIL-LABEL: sil public_external [transparent] [serialized] @_T0s1poiS2i_SitF : $@convention(thin) (Int, Int) -> Int {
func test(_ sharer: ResourceSharer) {}
class HasNoOptionalReqs : ObjCProtoWithOptional { }
HasNoOptionalReqs()
OptionalImplementer().unrelated()
extension def_class.ComputedProperty { }
| apache-2.0 | fc207c4f71df2d500c3b12b84a22402b | 23.314607 | 158 | 0.703789 | 3.136232 | false | false | false | false |
belatrix/iOSAllStarsRemake | AllStars/AllStars/iPhone/Classes/Profile/EditProfileViewController.swift | 1 | 11504 | //
// EditProfileViewController.swift
// AllStars
//
// Created by Flavio Franco Tunqui on 6/2/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import UIKit
class EditProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate {
@IBOutlet weak var viewHeader : UIView!
@IBOutlet weak var imgUser : UIImageView!
@IBOutlet weak var edtFirstName : UITextField!
@IBOutlet weak var edtLastName : UITextField!
@IBOutlet weak var edtSkypeId : UITextField!
@IBOutlet weak var tableLocations : UITableView!
@IBOutlet weak var scrollContent : UIScrollView!
@IBOutlet weak var constraintHeightContent : NSLayoutConstraint!
@IBOutlet weak var viewLoading : UIView!
@IBOutlet weak var lblErrorMessage : UILabel!
@IBOutlet weak var actUpdating : UIActivityIndicatorView!
@IBOutlet weak var actLocations : UIActivityIndicatorView!
@IBOutlet weak var btnCancel : UIButton!
@IBOutlet weak var btnUploadPhoto : UIButton!
@IBOutlet weak var viewFirstName : UIView!
@IBOutlet weak var viewLastName : UIView!
@IBOutlet weak var viewSkypeId : UIView!
// photo
var imagePickerController = UIImagePickerController()
var hasNewImage = false
var selectedImage = UIImage()
var objUser : User?
var arrayLocations = NSMutableArray()
var isNewUser : Bool?
override func viewDidLoad() {
super.viewDidLoad()
setViews()
// imagePicker
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
self.updateUserInfo()
}
// MARK: - Style
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
// MARK: - UI
func setViews() {
if (isNewUser!) {
btnCancel.hidden = true
}
OSPCrop.makeRoundView(self.imgUser)
self.view.backgroundColor = UIColor.colorPrimary()
viewHeader.backgroundColor = UIColor.colorPrimary()
viewFirstName.backgroundColor = UIColor.colorPrimary()
viewLastName.backgroundColor = UIColor.colorPrimary()
viewSkypeId.backgroundColor = UIColor.colorPrimary()
btnUploadPhoto.backgroundColor = UIColor.belatrix()
}
func lockScreen() {
self.view.userInteractionEnabled = false
self.actUpdating.startAnimating()
}
func unlockScreen() {
self.view.userInteractionEnabled = true
self.actUpdating.stopAnimating()
}
// MARK: - IBActions
@IBAction func btnUploadPhotoTIU(sender: UIButton) {
self.view.endEditing(true)
let alert: UIAlertController = UIAlertController(title: "upload_from".localized, message: nil, preferredStyle: .ActionSheet)
let cameraAction = UIAlertAction(title: "camera".localized, style: .Default,
handler: {(alert: UIAlertAction) in
self.imagePickerController.sourceType = .Camera
self.presentViewController(self.imagePickerController, animated: true, completion: { imageP in })
})
let galleryAction = UIAlertAction(title: "gallery".localized, style: .Default,
handler: {(alert: UIAlertAction) in
self.imagePickerController.sourceType = .SavedPhotosAlbum
self.presentViewController(self.imagePickerController, animated: true, completion: { imageP in })
})
let cancelAction = UIAlertAction(title: "Cancel".localized, style: .Cancel,
handler: nil)
alert.addAction(cameraAction)
alert.addAction(galleryAction)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: {})
}
@IBAction func btnCancelTUI(sender: UIButton) {
self.view.endEditing(true)
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func btnDoneTUI(sender: UIButton) {
self.view.endEditing(true)
updateDataUser()
}
@IBAction func textFieldVCh(sender: UITextField) {
if (sender == edtFirstName) {
objUser!.user_first_name = edtFirstName.text
} else if (sender == edtLastName) {
objUser!.user_last_name = edtLastName.text
} else if (sender == edtSkypeId) {
objUser!.user_skype_id = edtSkypeId.text
}
}
// MARK: - UITableViewDelegate, UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrayLocations.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "LocationTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! LocationTableViewCell
let locationBE = self.arrayLocations[indexPath.row] as! LocationBE
cell.objLocationBE = locationBE
cell.updateData()
if (locationBE.location_pk == objUser!.user_location_id) {
cell.accessoryType = .Checkmark
} else {
cell.accessoryType = .None
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let locationBE = self.arrayLocations[indexPath.row] as! LocationBE
objUser!.user_location_id = locationBE.location_pk
tableView.reloadData()
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 36
}
// MARK: - UIImagePickerController delegates
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
hasNewImage = true
selectedImage = pickedImage
self.imgUser.image = selectedImage
} else {
hasNewImage = false
}
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - WebServices
func listLocations() -> Void {
self.actLocations.startAnimating()
ProfileBC.listLocations {(arrayLocations) in
self.actLocations.stopAnimating()
self.arrayLocations = arrayLocations!
self.lblErrorMessage.text = "no_availables_locations".localized
self.viewLoading.alpha = CGFloat(!Bool(self.arrayLocations.count))
let height = Int(self.scrollContent.bounds.size.height) - 113
let newHeight = Int(self.tableLocations.frame.origin.y) + self.arrayLocations.count * 36
self.constraintHeightContent.constant = newHeight > height ? CGFloat(newHeight) : CGFloat(height)
self.tableLocations.reloadData()
}
}
func updateDataUser() -> Void {
ProfileBC.updateInfoToUser(objUser!, newUser: isNewUser!, hasImage: hasNewImage, withController: self, withCompletion: {(user) in
self.view.userInteractionEnabled = true
self.actUpdating.stopAnimating()
if (user != nil) {
if (self.hasNewImage) {
self.updatePhotoUser()
} else {
if (user!.user_base_profile_complete!) {
if (self.isNewUser!) {
self.openTabBar()
} else {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
}
})
}
func updatePhotoUser() -> Void {
lockScreen()
let imageData = UIImageJPEGRepresentation(selectedImage, 0.5)
ProfileBC.updatePhotoToUser(objUser!, withController: self, withImage: imageData!, withCompletion: {(user) in
self.unlockScreen()
if (user != nil) {
if (user!.user_base_profile_complete!) {
if (self.isNewUser!) {
self.openTabBar()
} else {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
})
}
// MARK: - Other
func openTabBar() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.login()
appDelegate.addShortcutItems()
}
// MARK: - Configuration
func updateDataUserUI() -> Void {
if let firstName = self.objUser?.user_first_name {
edtFirstName.text = firstName
}
if let lastName = self.objUser?.user_last_name {
edtLastName.text = lastName
}
if let skypeId = self.objUser?.user_skype_id {
edtSkypeId.text = skypeId
}
if let url_photo = self.objUser?.user_avatar{
if (url_photo != "") {
OSPImageDownloaded.descargarImagenEnURL(url_photo, paraImageView: self.imgUser, conPlaceHolder: self.imgUser.image)
} else {
self.imgUser!.image = UIImage(named: "ic_user.png")
}
} else {
self.imgUser!.image = UIImage(named: "ic_user.png")
}
}
func updateUserInfo() -> Void {
self.updateDataUserUI()
self.listLocations()
}
// MARK: - UITextField delegates
func textFieldShouldReturn(textField: UITextField!) -> Bool {
if (textField == edtFirstName) {
edtLastName.becomeFirstResponder()
} else if (textField == edtLastName) {
edtSkypeId.becomeFirstResponder()
}
textField.resignFirstResponder()
return true
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SkillsViewController" {
let skillsNC = segue.destinationViewController as! UINavigationController
let skillsVC = skillsNC.topViewController as! UserSkillsViewController
skillsVC.objUser = self.objUser!
}
}
}
| mit | 73d3bb7fb4ffe90bdd13c481601ccf82 | 34.285276 | 203 | 0.571068 | 5.737157 | false | false | false | false |
vector-im/vector-ios | RiotSwiftUI/Modules/Spaces/SpaceCreation/SpaceCreationEmailInvites/Coordinator/SpaceCreationEmailInvitesCoordinator.swift | 1 | 5458 | // File created from SimpleUserProfileExample
// $ createScreen.sh Spaces/SpaceCreation/SpaceCreationEmailInvites SpaceCreationEmailInvites
/*
Copyright 2021 New Vector Ltd
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 UIKit
import SwiftUI
final class SpaceCreationEmailInvitesCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: SpaceCreationEmailInvitesCoordinatorParameters
private let spaceCreationEmailInvitesHostingController: UIViewController
private var spaceCreationEmailInvitesViewModel: SpaceCreationEmailInvitesViewModelProtocol
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var callback: ((SpaceCreationEmailInvitesCoordinatorAction) -> Void)?
// MARK: - Setup
@available(iOS 14.0, *)
init(parameters: SpaceCreationEmailInvitesCoordinatorParameters) {
self.parameters = parameters
let service = SpaceCreationEmailInvitesService(session: parameters.session)
let viewModel = SpaceCreationEmailInvitesViewModel(creationParameters: parameters.creationParams, service: service)
let view = SpaceCreationEmailInvites(viewModel: viewModel.context)
.addDependency(AvatarService.instantiate(mediaManager: parameters.session.mediaManager))
spaceCreationEmailInvitesViewModel = viewModel
let hostingController = VectorHostingController(rootView: view)
hostingController.isNavigationBarHidden = true
spaceCreationEmailInvitesHostingController = hostingController
}
// MARK: - Public
func start() {
MXLog.debug("[SpaceCreationEmailInvitesCoordinator] did start.")
spaceCreationEmailInvitesViewModel.completion = { [weak self] result in
MXLog.debug("[SpaceCreationEmailInvitesCoordinator] SpaceCreationEmailInvitesViewModel did complete with result: \(result).")
guard let self = self else { return }
switch result {
case .cancel:
self.callback?(.cancel)
case .back:
self.callback?(.back)
case .done:
self.callback?(.done)
case .inviteByUsername:
self.callback?(.inviteByUsername)
case .needIdentityServiceTerms(let baseUrl, let accessToken):
self.presentIdentityServerTerms(with: baseUrl, accessToken: accessToken)
case .identityServiceFailure(let error):
self.showIdentityServiceFailure(error)
}
}
}
func toPresentable() -> UIViewController {
return self.spaceCreationEmailInvitesHostingController
}
// MARK: - Identity service
private var serviceTermsModalCoordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter?
private func presentIdentityServerTerms(with baseUrl: String?, accessToken: String?) {
guard let baseUrl = baseUrl, let accessToken = accessToken else {
showIdentityServiceFailure(nil)
return
}
let presenter = ServiceTermsModalCoordinatorBridgePresenter(session: parameters.session, baseUrl: baseUrl, serviceType: MXServiceTypeIdentityService, accessToken: accessToken)
presenter.delegate = self
presenter.present(from: self.toPresentable(), animated: true)
serviceTermsModalCoordinatorBridgePresenter = presenter
}
private func showIdentityServiceFailure(_ error: Error?) {
let alertController = UIAlertController(title: VectorL10n.findYourContactsIdentityServiceError, message: nil, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: VectorL10n.ok, style: .default, handler: nil))
self.toPresentable().present(alertController, animated: true, completion: nil);
}
}
extension SpaceCreationEmailInvitesCoordinator: ServiceTermsModalCoordinatorBridgePresenterDelegate {
func serviceTermsModalCoordinatorBridgePresenterDelegateDidAccept(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter) {
coordinatorBridgePresenter.dismiss(animated: true) {
self.serviceTermsModalCoordinatorBridgePresenter = nil;
self.callback?(.done)
}
}
func serviceTermsModalCoordinatorBridgePresenterDelegateDidDecline(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter, session: MXSession) {
coordinatorBridgePresenter.dismiss(animated: true) {
self.serviceTermsModalCoordinatorBridgePresenter = nil;
}
}
func serviceTermsModalCoordinatorBridgePresenterDelegateDidClose(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter) {
coordinatorBridgePresenter.dismiss(animated: true) {
self.serviceTermsModalCoordinatorBridgePresenter = nil;
}
}
}
| apache-2.0 | fe9b4cfc5bbfcd2c7248524e38a2244b | 43.016129 | 183 | 0.729388 | 6.288018 | false | false | false | false |
muyang00/YEDouYuTV | YEDouYuZB/YEDouYuZB/Home/Views/CollectionAmuseHeadCell.swift | 1 | 1849 | //
// CollectionAmuseHeadCell.swift
// YEDouYuZB
//
// Created by yongen on 17/4/1.
// Copyright © 2017年 yongen. All rights reserved.
//
import UIKit
let kAmuseCellID = "kAmuseCellID"
class CollectionAmuseHeadCell: UICollectionViewCell {
@IBOutlet weak var collectionView: UICollectionView!
var groups : [AnchorGroup]? {
didSet{
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kAmuseCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let itemW = collectionView.bounds.width / 4
let itemH = collectionView.bounds.height / 2
layout.itemSize = CGSize(width: itemW, height: itemH)
}
}
extension CollectionAmuseHeadCell : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAmuseCellID, for: indexPath) as! CollectionGameCell
//cell.backgroundColor = UIColor.randomColor()
cell.baseGame = self.groups![indexPath.item]
cell.clipsToBounds = true
return cell
}
}
extension CollectionAmuseHeadCell : UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("CollectionAmuseHeadCell")
}
}
| apache-2.0 | 6b2776788b7d090d6a02adbf5390c89a | 32.563636 | 127 | 0.698267 | 5.350725 | false | false | false | false |
slightair/syu | Syu/Model/APIDocumentation.swift | 1 | 3115 | import Foundation
import SQLite
import RxSwift
class APIDocumentation {
let resourcesPath: URL
var mapDBPath: URL {
return resourcesPath.appendingPathComponent("external/map.db", isDirectory: false)
}
var cacheDBPath: URL {
return resourcesPath.appendingPathComponent("external/cache.db", isDirectory: false)
}
var indexDBPath: URL {
return SearchIndexCreator.indexFilePath
}
var mapDB: Connection!
var cacheDB: Connection!
var indexDB: Connection!
required init(xcodePath: URL) {
resourcesPath = xcodePath.appendingPathComponent("../SharedFrameworks/DNTDocumentationSupport.framework/Resources", isDirectory: true).standardizedFileURL
}
convenience init?() {
guard let xcodePath = Xcode.currentPath else {
return nil
}
self.init(xcodePath: xcodePath)
}
func prepare(completion: @escaping (() -> Void)) {
createSearchIndexIfNeeded {
self.openDatabases()
completion()
}
}
private func createSearchIndexIfNeeded(completion: @escaping (() -> Void)) {
if SearchIndexCreator.existsIndexFile {
completion()
} else {
let creator = SearchIndexCreator(resourcesPath: resourcesPath)
creator.createSearchIndex { _ in
completion()
}
}
}
private func openDatabases() {
mapDB = try? Connection(mapDBPath.absoluteString, readonly: true)
cacheDB = try? Connection(cacheDBPath.absoluteString, readonly: true)
indexDB = try? Connection(indexDBPath.absoluteString, readonly: true)
}
func search(keyword: String) -> Observable<[SearchIndex]> {
let query = Table("search_indexes").select(SearchIndex.Column.name,
SearchIndex.Column.type,
SearchIndex.Column.requestKey)
.filter(SearchIndex.Column.name.like("\(keyword)%"))
.limit(30)
return Observable<[SearchIndex]>.create { observer in
do {
let indexes = try self.indexDB.prepare(query).map { record in
SearchIndex(name: record[SearchIndex.Column.name],
type: record[SearchIndex.Column.type],
requestKey: record[SearchIndex.Column.requestKey])
}
observer.onNext(indexes)
observer.onCompleted()
} catch let e {
observer.onError(e)
}
return Disposables.create()
}
}
func responseData(of key: String) -> ResponseData? {
let requestKey = Expression<String>("request_key")
let responseData = Expression<ResponseData>("response_data")
let query = Table("response").select(responseData).filter(requestKey == key)
if let row = try? cacheDB.pluck(query), let record = row {
return record[responseData]
} else {
return nil
}
}
}
| mit | edd54abe0b410f88376bc45a7339bf7e | 31.789474 | 162 | 0.588764 | 5.244108 | false | false | false | false |
ruddfawcett/Notepad | Notepad/Style.swift | 1 | 674 | //
// Style.swift
// Notepad
//
// Created by Rudd Fawcett on 10/14/16.
// Copyright © 2016 Rudd Fawcett. All rights reserved.
//
import Foundation
public struct Style {
var regex: NSRegularExpression!
public var attributes: [NSAttributedString.Key: Any] = [:]
public init(element: Element, attributes: [NSAttributedString.Key: Any]) {
self.regex = element.toRegex()
self.attributes = attributes
}
public init(regex: NSRegularExpression, attributes: [NSAttributedString.Key: Any]) {
self.regex = regex
self.attributes = attributes
}
public init() {
self.regex = Element.unknown.toRegex()
}
}
| mit | 8c5e88f9e6699b619d67a718eed6678f | 23.035714 | 88 | 0.653789 | 3.982249 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/ProgressViewController.swift | 1 | 4913 | //
// ProgressViewController.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2014-06-07.
//
// ---------------------------------------------------------------------------
//
// © 2014-2022 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import Cocoa
final class ProgressViewController: NSViewController {
// MARK: Private Properties
@objc private dynamic let progress: Progress
@objc private dynamic let message: String
private let closesAutomatically: Bool
private let appliesDescriptionImmediately: Bool
private var progressSubscriptions: Set<AnyCancellable> = []
private var completionSubscriptions: Set<AnyCancellable> = []
@IBOutlet private weak var indicator: NSProgressIndicator?
@IBOutlet private weak var descriptionField: NSTextField?
@IBOutlet private weak var button: NSButton?
// MARK: -
// MARK: Lifecycle
/// Initialize view with given progress instance.
///
/// - Parameters:
/// - coder: The coder to instantiate the view from a storyboard.
/// - progress: The progress instance to indicate.
/// - message: The text to display as the message label of the indicator.
/// - closesAutomatically: Whether dismiss the view when the progress is finished.
/// - appliesDescriptionImmediately: Whether throttle the update of the description field.
init?(coder: NSCoder, progress: Progress, message: String, closesAutomatically: Bool = true, appliesDescriptionImmediately: Bool = false) {
assert(!progress.isCancelled)
assert(!progress.isFinished)
self.progress = progress
self.message = message
self.closesAutomatically = closesAutomatically
self.appliesDescriptionImmediately = appliesDescriptionImmediately
super.init(coder: coder)
progress.publisher(for: \.isFinished)
.filter { $0 }
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in self?.done() }
.store(in: &self.completionSubscriptions)
progress.publisher(for: \.isCancelled)
.filter { $0 }
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in self?.dismiss(nil) }
.store(in: &self.completionSubscriptions)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear() {
super.viewWillAppear()
guard
let indicator = self.indicator,
let descriptionField = self.descriptionField
else { return assertionFailure() }
self.progressSubscriptions.removeAll()
self.progress.publisher(for: \.fractionCompleted, options: .initial)
.throttle(for: 0.2, scheduler: DispatchQueue.main, latest: true)
.assign(to: \.doubleValue, on: indicator)
.store(in: &self.progressSubscriptions)
self.progress.publisher(for: \.localizedDescription, options: .initial)
.throttle(for: self.appliesDescriptionImmediately ? 0 : 0.1, scheduler: DispatchQueue.main, latest: true)
.assign(to: \.stringValue, on: descriptionField)
.store(in: &self.progressSubscriptions)
}
override func viewDidDisappear() {
super.viewDidDisappear()
self.progressSubscriptions.removeAll()
self.completionSubscriptions.removeAll()
}
// MARK: Public Methods
/// Change the state of progress to finished.
func done() {
self.completionSubscriptions.removeAll()
if self.closesAutomatically {
return self.dismiss(self)
}
guard let button = self.button else { return assertionFailure() }
self.descriptionField?.stringValue = self.progress.localizedDescription
button.title = "OK".localized
button.action = #selector(dismiss(_:) as (Any?) -> Void)
button.keyEquivalent = "\r"
}
// MARK: Actions
/// Cancel current process.
@IBAction func cancel(_ sender: Any?) {
self.progress.cancel()
}
}
| apache-2.0 | 24fe82c90dc65365c834204bddfa7f7e | 31.104575 | 143 | 0.617264 | 5.058702 | false | false | false | false |
wangshuaidavid/WSDynamicAlbumMaker | WSDynamicAlbumMakerDemo/WSDynamicAlbumMaker/WSDynamicAlbumMaker.swift | 1 | 9964 | //
// WSDynamicAlbumMaker.swift
// WSDynamicAlbumMakerDemo
//
// Created by ennrd on 4/25/15.
// Copyright (c) 2015 ws. All rights reserved.
//
import Foundation
import AVFoundation
import CoreMedia
import AssetsLibrary
public typealias WSDynamicAlbumMakerExportCompletionBlock = (NSURL!, NSError!) -> Void
public class WSDynamicAlbumMaker {
public class var sharedInstance: WSDynamicAlbumMaker {
struct Static {
static let instance: WSDynamicAlbumMaker = WSDynamicAlbumMaker()
}
return Static.instance
}
public func createDynamicAlbum (#videoURL: NSURL, renderLayer:CALayer, duration: Float, completionBlock: WSDynamicAlbumMakerExportCompletionBlock!) {
self.goCreateDynamicAlbum(videoURL: videoURL, audioURL: nil, renderLayer: renderLayer, duration: duration, isSaveToPhotosAlbum: false, completionBlock: completionBlock)
}
public func createDynamicAlbum (#videoURL: NSURL, audioURL: NSURL!, renderLayer:CALayer, duration: Float, completionBlock: WSDynamicAlbumMakerExportCompletionBlock!) {
self.goCreateDynamicAlbum(videoURL: videoURL, audioURL: audioURL, renderLayer: renderLayer, duration: duration, isSaveToPhotosAlbum: false, completionBlock: completionBlock)
}
public func createDynamicAlbum (#videoURL: NSURL, audioURL: NSURL!, renderLayer:CALayer, duration: Float, isSaveToPhotosAlbum: Bool, completionBlock: WSDynamicAlbumMakerExportCompletionBlock!) {
self.goCreateDynamicAlbum(videoURL: videoURL, audioURL: audioURL, renderLayer: renderLayer, duration: duration, isSaveToPhotosAlbum: isSaveToPhotosAlbum, completionBlock: completionBlock)
}
}
//MARK: Utility functions
extension WSDynamicAlbumMaker {
public func getCoreAnimationBeginTimeAtZero() -> CFTimeInterval {
return AVCoreAnimationBeginTimeAtZero
}
public func querySizeWithAssetURL(#videoURL: NSURL) -> CGSize {
let videoAsset = AVURLAsset(URL: videoURL, options: nil)
return self.querySize(video: videoAsset)
}
private func querySize(#video: AVAsset) -> CGSize {
let videoAssetTrack = video.tracksWithMediaType(AVMediaTypeVideo).first as! AVAssetTrack
let videoTransform = videoAssetTrack.preferredTransform
var isVideoAssetPortrait = false
if (videoTransform.a == 0 && videoTransform.b == 1.0 && videoTransform.c == -1.0 && videoTransform.d == 0) {
isVideoAssetPortrait = true
}
if (videoTransform.a == 0 && videoTransform.b == -1.0 && videoTransform.c == 1.0 && videoTransform.d == 0) {
isVideoAssetPortrait = true
}
var natureSize = CGSizeZero
if isVideoAssetPortrait {
natureSize = CGSizeMake(videoAssetTrack.naturalSize.height, videoAssetTrack.naturalSize.width)
} else {
natureSize = videoAssetTrack.naturalSize
}
return natureSize
}
}
//MARK: Main process functions
extension WSDynamicAlbumMaker {
private func goCreateDynamicAlbum (#videoURL: NSURL, audioURL: NSURL!, renderLayer:CALayer, duration: Float, isSaveToPhotosAlbum: Bool, completionBlock: WSDynamicAlbumMakerExportCompletionBlock!) {
// 0 - Get AVAsset from NSURL
let videoAsset = AVURLAsset(URL: videoURL, options: nil)
// 1 - Prepare VideoAssetTrack and DurationTimeRange for further use
let videoAssetTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo).first as! AVAssetTrack
let durationCMTime = CMTimeMakeWithSeconds(Float64(duration), 30)
let durationTimeRange = CMTimeRangeMake(kCMTimeZero, durationCMTime)
// 2 - Create AVMutableComposition object. This object will hold your AVMutableCompositionTrack instances.
let mixComposition = AVMutableComposition()
// 3 - Get Video track
let videoTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid))
videoTrack.insertTimeRange(durationTimeRange, ofTrack: videoAssetTrack, atTime: kCMTimeZero, error: nil)
// 3.0 - Handle Audio asset
if let audiourl_ = audioURL {
let audioAsset = AVURLAsset(URL: audiourl_, options: nil)
let audioAssetTrack = audioAsset.tracksWithMediaType(AVMediaTypeAudio).first as! AVAssetTrack
let audioTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid))
audioTrack.insertTimeRange(durationTimeRange, ofTrack: audioAssetTrack, atTime: kCMTimeZero, error: nil)
}
// 3.1 - Create AVMutableVideoCompositionInstruction
let mainInstruction = AVMutableVideoCompositionInstruction()
mainInstruction.timeRange = durationTimeRange
// 3.2 - Create an AVMutableVideoCompositionLayerInstruction for the video track and fix the orientation.
let videolayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
videolayerInstruction.setTransform(videoAssetTrack.preferredTransform, atTime: kCMTimeZero)
videolayerInstruction.setOpacity(0.0, atTime: videoAsset.duration)
// 3.3 - Add instructions
mainInstruction.layerInstructions = [videolayerInstruction]
let mainCompositionInst = AVMutableVideoComposition()
let naturalSize = self.querySize(video: videoAsset)
let renderWidth = naturalSize.width
let renderHeight = naturalSize.height
mainCompositionInst.renderSize = CGSizeMake(renderWidth, renderHeight)
mainCompositionInst.instructions = [mainInstruction]
mainCompositionInst.frameDuration = CMTimeMake(1, 30)
self.applyVideoEffectsToComposition(mainCompositionInst, size: naturalSize, overlayLayer: renderLayer)
// 4 - Get path
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentDirectory = paths.first as! String
let randomInt = arc4random() % 1000
let fullPathDocs = documentDirectory.stringByAppendingPathComponent("CreatedVideo-\(randomInt).mov")
let createdVideoURL = NSURL.fileURLWithPath(fullPathDocs)
// 5 - Create exporter
let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
exporter.outputURL = createdVideoURL
exporter.outputFileType = AVFileTypeQuickTimeMovie
exporter.shouldOptimizeForNetworkUse = true
exporter.videoComposition = mainCompositionInst
exporter.exportAsynchronouslyWithCompletionHandler {
let outputURL = exporter.outputURL
switch (exporter.status) {
case AVAssetExportSessionStatus.Completed:
if isSaveToPhotosAlbum {
self.exportCompletionHandleSaveToAssetLibrary(outputURL, block: completionBlock)
}else {
self.exportCompletionHandleNotSaveToAssetLibrary(outputURL, block: completionBlock)
}
break;
case AVAssetExportSessionStatus.Failed:
self.exportCompletionHandleWithError(-1, message: "Exporting Failed", block: completionBlock)
break;
case AVAssetExportSessionStatus.Cancelled:
self.exportCompletionHandleWithError(-2, message: "Exporting Cancelled", block: completionBlock)
break;
default:
self.exportCompletionHandleWithError(0, message: "Exporting Unkown error occured", block: completionBlock)
break;
}
}
}
private func exportCompletionHandleNotSaveToAssetLibrary(fileAssetURL: NSURL, block: WSDynamicAlbumMakerExportCompletionBlock) {
dispatch_async(dispatch_get_main_queue(), {
block(fileAssetURL, nil)
})
}
private func exportCompletionHandleSaveToAssetLibrary(fileAssetURL: NSURL, block: WSDynamicAlbumMakerExportCompletionBlock) {
let library = ALAssetsLibrary()
if library.videoAtPathIsCompatibleWithSavedPhotosAlbum(fileAssetURL) {
library.writeVideoAtPathToSavedPhotosAlbum(fileAssetURL, completionBlock: { (assetURL, error) -> Void in
NSFileManager.defaultManager().removeItemAtURL(fileAssetURL, error: nil)
dispatch_async(dispatch_get_main_queue(), {
block(assetURL, error)
})
})
}
}
private func exportCompletionHandleWithError(code: Int, message: String, block: WSDynamicAlbumMakerExportCompletionBlock) {
dispatch_async(dispatch_get_main_queue(), {
block(nil, NSError(domain: "Video_Export", code: code, userInfo: ["ErrorMsg": message]))
})
}
private func applyVideoEffectsToComposition(composition: AVMutableVideoComposition, size:CGSize, overlayLayer: CALayer) {
let parentLayer = CALayer()
let videoLayer = CALayer()
parentLayer.frame = CGRectMake(0, 0, size.width, size.height)
videoLayer.frame = CGRectMake(0, 0, size.width, size.height)
parentLayer.addSublayer(videoLayer)
parentLayer.addSublayer(overlayLayer)
composition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, inLayer: parentLayer)
}
}
| apache-2.0 | 8dfa1a4184774a486bafd99e664eb85d | 41.220339 | 201 | 0.679145 | 6.116636 | false | false | false | false |
phimage/Prephirences | Sources/Prephirences.swift | 1 | 6367 | //
// Prephirences.swift
// Prephirences
/*
The MIT License (MIT)
Copyright (c) 2017 Eric Marchand (phimage)
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
/* Preferences manager class that contains some Preferences */
open class Prephirences {
/** Shared preferences. Could be replaced by any other preferences */
public static var sharedInstance: PreferencesType = MutableDictionaryPreferences()
// casting shortcut for sharedInstance
public static var sharedMutableInstance: MutablePreferencesType? {
return sharedInstance as? MutablePreferencesType
}
// MARK: register by key
fileprivate static var _instances = [PrephirencesKey: PreferencesType]()
/* Get Preferences for PrephirencesKey */
fileprivate class func instance(forKey key: PrephirencesKey, orRegister newOne: PreferencesType? = nil) -> PreferencesType? {
if let value = self._instances[key] {
return value
} else if let toRegister = newOne {
registerInstance(toRegister, forKey: key)
}
return newOne
}
/* Add Preferences for PrephirencesKey */
fileprivate class func register(preferences: PreferencesType, forKey key: PrephirencesKey) {
self._instances[key] = preferences
}
/* Remove Preferences for PrephirencesKey */
fileprivate class func unregisterPreferences(forKey key: PrephirencesKey) -> PreferencesType? {
return self._instances.removeValue(forKey: key)
}
/* Get Preferences for key */
open class func instance<Key: Hashable>(forKey key: Key, orRegister newOne: PreferencesType? = nil) -> PreferencesType? {
return self.instance(forKey: PrephirencesKey(key), orRegister: newOne)
}
/* Add Preferences for key */
open class func registerInstance<Key: Hashable>(_ preferences: PreferencesType, forKey key: Key) {
self.register(preferences: preferences, forKey: PrephirencesKey(key))
}
/* Remove Preferences for key */
open class func unregisterInstance<Key: Hashable>(forKey key: Key) -> PreferencesType? {
return self.unregisterPreferences(forKey: PrephirencesKey(key))
}
/* allow to use subscript with desired key type */
public static func instances<KeyType: Hashable>() -> PrephirencesForType<KeyType> {
return PrephirencesForType<KeyType>()
}
static func isEmpty<T>(_ value: T?) -> Bool {
return value == nil
}
public static func unraw<T>(_ object: T.RawValue?) -> T? where T: RawRepresentable, T.RawValue: PreferenceObject {
if let rawValue = object {
return T(rawValue: rawValue)
}
return nil
}
public static func raw<T>(_ value: T?) -> T.RawValue? where T: RawRepresentable, T.RawValue: PreferenceObject {
return value?.rawValue
}
}
/* Allow to access or modify Preferences according to key type */
open class PrephirencesForType<Key: Hashable> {
open subscript(key: PreferenceKey) -> PreferencesType? {
get {
return Prephirences.instance(forKey: key)
}
set {
if let value = newValue {
Prephirences.registerInstance(value, forKey: key)
} else {
_ = Prephirences.unregisterInstance(forKey: key)
}
}
}
}
/* Generic key for dictionary */
struct PrephirencesKey: Hashable, Equatable {
fileprivate let underlying: Any
fileprivate let hashFunc: (inout Hasher) -> Void
fileprivate let equalityFunc: (Any) -> Bool
init<T: Hashable>(_ key: T) {
underlying = key
hashFunc = { key.hash(into: &$0) }
equalityFunc = {
if let other = $0 as? T {
return key == other
}
return false
}
}
func hash(into hasher: inout Hasher) {
hashFunc(&hasher)
}
}
internal func == (left: PrephirencesKey, right: PrephirencesKey) -> Bool {
return left.equalityFunc(right.underlying)
}
// MARK: archive/unarchive
extension Prephirences {
public static func unarchive(fromPreferences preferences: PreferencesType, forKey key: PreferenceKey) -> PreferenceObject? {
if let data = preferences.data(forKey: key) {
return unarchive(data)
}
return nil
}
public static func archive(object value: PreferenceObject?, intoPreferences preferences: MutablePreferencesType, forKey key: PreferenceKey) {
if let toArchive: PreferenceObject = value {
let data = archive(toArchive)
preferences.set(data, forKey: key)
} else {
preferences.removeObject(forKey: key)
}
}
public static func unarchive(_ data: Data) -> PreferenceObject? {
return NSKeyedUnarchiver.unarchiveObject(with: data)
}
public static func archive(_ object: PreferenceObject) -> Data {
return NSKeyedArchiver.archivedData(withRootObject: object)
}
}
extension PreferencesType {
public func unarchiveObject(forKey key: PreferenceKey) -> PreferenceObject? {
return Prephirences.unarchive(fromPreferences: self, forKey: key)
}
}
extension MutablePreferencesType {
public func set(objectToArchive value: PreferenceObject?, forKey key: PreferenceKey) {
Prephirences.archive(object: value, intoPreferences: self, forKey: key)
}
}
| mit | 84e2bce68796897feaef7c4a6a19f9a8 | 34.372222 | 145 | 0.685409 | 4.939488 | false | false | false | false |
AbelSu131/ios-charts | Charts/Classes/Renderers/HorizontalBarChartRenderer.swift | 1 | 19136 | //
// HorizontalBarChartRenderer.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
import UIKit
public class HorizontalBarChartRenderer: BarChartRenderer
{
private var xOffset: CGFloat = 0.0;
private var yOffset: CGFloat = 0.0;
public override init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(delegate: delegate, animator: animator, viewPortHandler: viewPortHandler);
}
internal override func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int)
{
CGContextSaveGState(context);
var barData = delegate!.barChartRendererData(self);
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self);
var dataSetOffset = (barData.dataSetCount - 1);
var groupSpace = barData.groupSpace;
var groupSpaceHalf = groupSpace / 2.0;
var barSpace = dataSet.barSpace;
var barSpaceHalf = barSpace / 2.0;
var containsStacks = dataSet.isStacked;
var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency);
var entries = dataSet.yVals as! [BarChartDataEntry];
var barWidth: CGFloat = 0.5;
var phaseY = _animator.phaseY;
var barRect = CGRect();
var barShadow = CGRect();
var y: Double;
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++)
{
var e = entries[j];
// calculate the x-position, depending on datasetcount
var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(j) + groupSpaceHalf;
var vals = e.values;
if (!containsStacks || vals == nil)
{
y = e.value;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0);
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0);
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue;
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break;
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = viewPortHandler.contentLeft;
barShadow.origin.y = barRect.origin.y;
barShadow.size.width = viewPortHandler.contentWidth;
barShadow.size.height = barRect.size.height;
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor);
CGContextFillRect(context, barShadow);
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor);
CGContextFillRect(context, barRect);
}
else
{
var all = e.value;
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0);
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0);
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
barShadow.origin.x = viewPortHandler.contentLeft;
barShadow.origin.y = barRect.origin.y;
barShadow.size.width = viewPortHandler.contentWidth;
barShadow.size.height = barRect.size.height;
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor);
CGContextFillRect(context, barShadow);
}
// fill the stack
for (var k = 0; k < vals.count; k++)
{
all -= vals[k];
y = vals[k] + all;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = y >= 0.0 ? CGFloat(y) : 0.0;
var left = y <= 0.0 ? CGFloat(y) : 0.0;
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
// Skip to next bar
break;
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break;
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor);
CGContextFillRect(context, barRect);
}
}
}
CGContextRestoreGState(context);
}
internal override func prepareBarHighlight(#x: CGFloat, y: Double, barspacehalf: CGFloat, from: Double, trans: ChartTransformer, inout rect: CGRect)
{
let barWidth: CGFloat = 0.5;
var top = x - barWidth + barspacehalf;
var bottom = x + barWidth - barspacehalf;
var left = y >= from ? CGFloat(y) : CGFloat(from);
var right = y <= from ? CGFloat(y) : CGFloat(from);
rect.origin.x = left;
rect.origin.y = top;
rect.size.width = right - left;
rect.size.height = bottom - top;
trans.rectValueToPixelHorizontal(&rect, phaseY: _animator.phaseY);
}
public override func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint]
{
return trans.generateTransformedValuesHorizontalBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY);
}
public override func drawValues(#context: CGContext)
{
// if values are drawn
if (passesCheck())
{
var barData = delegate!.barChartRendererData(self);
var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self);
var dataSets = barData.dataSets;
var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self);
var drawValuesForWholeStackEnabled = delegate!.barChartIsDrawValuesForWholeStackEnabled(self);
var textAlign = drawValueAboveBar ? NSTextAlignment.Left : NSTextAlignment.Right;
let valueOffsetPlus: CGFloat = 5.0;
var posOffset: CGFloat;
var negOffset: CGFloat;
for (var i = 0, count = barData.dataSetCount; i < count; i++)
{
var dataSet = dataSets[i];
if (!dataSet.isDrawValuesEnabled)
{
continue;
}
var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency);
var valueFont = dataSet.valueFont;
var valueTextColor = dataSet.valueTextColor;
var yOffset = -valueFont.lineHeight / 2.0;
var formatter = dataSet.valueFormatter;
if (formatter === nil)
{
formatter = defaultValueFormatter;
}
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var entries = dataSet.yVals as! [BarChartDataEntry];
var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i);
// if only single values are drawn (sum)
if (!drawValuesForWholeStackEnabled)
{
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue;
}
var val = entries[j].value;
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
drawValue(
context: context,
value: valueText,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
}
else
{
// if each value of a potential stack should be drawn
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
var e = entries[j];
var vals = e.values;
// we still draw stacked bars, but there is one non-stacked in between
if (vals == nil)
{
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue;
}
var val = e.value;
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
drawValue(
context: context,
value: valueText,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
else
{
var transformed = [CGPoint]();
var cnt = 0;
var add = e.value;
for (var k = 0; k < vals.count; k++)
{
add -= vals[cnt];
transformed.append(CGPoint(x: (CGFloat(vals[cnt]) + CGFloat(add)) * _animator.phaseY, y: 0.0));
cnt++;
}
trans.pointValuesToPixel(&transformed);
for (var k = 0; k < transformed.count; k++)
{
var val = vals[k];
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
var x = transformed[k].x + (val >= 0 ? posOffset : negOffset);
var y = valuePoints[j].y;
if (!viewPortHandler.isInBoundsX(x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(y))
{
continue;
}
drawValue(context: context,
value: valueText,
xPos: x,
yPos: y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
}
}
}
}
}
}
internal override func passesCheck() -> Bool
{
var barData = delegate!.barChartRendererData(self);
if (barData === nil)
{
return false;
}
return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleY;
}
} | apache-2.0 | cf7d72bb748add1d8fd69912bbd78a10 | 42.29638 | 171 | 0.425481 | 6.697935 | false | false | false | false |
pedromsantos/Ellis | Ellis/Keys/Key.swift | 1 | 6010 | public enum Key: Int
{
case AMajor
case AFlatMajor
case BMajor
case BFlatMajor
case CMajor
case CSharpMajor
case DMajor
case DFlatMajor
case EMajor
case EFlatMajor
case FMajor
case FSharpMajor
case GMajor
case GFlatMajor
case AMinor
case AFlatMinor
case ASharpMinor
case BMinor
case BFlatMinor
case CMinor
case CSharpMinor
case DMinor
case EFlatMinor
case EMinor
case FMinor
case FSharpMinor
case GMinor
case GSharpMinor
private static let fifths =
[Note.F, Note.C, Note.G, Note.D, Note.A, Note.E, Note.B]
private static let allValues =
[
(Relative: Key.FSharpMinor, Root: Note.A, Accidents: 3, Quality: KeyQuality.Major),
(Relative: Key.FMinor, Root: Note.AFlat, Accidents: -4, Quality: KeyQuality.Major),
(Relative: Key.GSharpMinor, Root: Note.B, Accidents: 5, Quality: KeyQuality.Major),
(Relative: Key.GMinor, Root: Note.BFlat, Accidents: -2, Quality: KeyQuality.Major),
(Relative: Key.AMinor, Root: Note.C, Accidents: 0, Quality: KeyQuality.Major),
(Relative: Key.BFlatMinor, Root: Note.CSharp, Accidents: 7, Quality: KeyQuality.Major),
(Relative: Key.BMinor, Root: Note.D, Accidents: 2, Quality: KeyQuality.Major),
(Relative: Key.BFlatMinor, Root: Note.DFlat, Accidents: -5, Quality: KeyQuality.Major),
(Relative: Key.CSharpMinor, Root: Note.E, Accidents: 4, Quality: KeyQuality.Major),
(Relative: Key.CMinor, Root: Note.EFlat, Accidents: -3, Quality: KeyQuality.Major),
(Relative: Key.DMinor, Root: Note.F, Accidents: -1, Quality: KeyQuality.Major),
(Relative: Key.EFlatMinor, Root: Note.FSharp, Accidents: 6, Quality: KeyQuality.Major),
(Relative: Key.EMinor, Root: Note.G, Accidents: 1, Quality: KeyQuality.Major),
(Relative: Key.EFlatMinor, Root: Note.GFlat, Accidents: -6, Quality: KeyQuality.Major),
(Relative: Key.CMajor, Root: Note.A, Accidents: 0, Quality: KeyQuality.Minor),
(Relative: Key.BMajor, Root: Note.AFlat, Accidents: -7, Quality: KeyQuality.Minor),
(Relative: Key.CSharpMinor, Root: Note.ASharp, Accidents: 7, Quality: KeyQuality.Minor),
(Relative: Key.DMajor, Root: Note.B, Accidents: 2, Quality: KeyQuality.Minor),
(Relative: Key.DFlatMajor, Root: Note.BFlat, Accidents: -5, Quality: KeyQuality.Minor),
(Relative: Key.EFlatMajor, Root: Note.C, Accidents: -3, Quality: KeyQuality.Minor),
(Relative: Key.EMajor, Root: Note.CSharp, Accidents: 4, Quality: KeyQuality.Minor),
(Relative: Key.FMajor, Root: Note.D, Accidents: -1, Quality: KeyQuality.Minor),
(Relative: Key.GFlatMajor, Root: Note.EFlat, Accidents: -6, Quality: KeyQuality.Minor),
(Relative: Key.GMajor, Root: Note.E, Accidents: 1, Quality: KeyQuality.Minor),
(Relative: Key.AFlatMajor, Root: Note.F, Accidents: -4, Quality: KeyQuality.Minor),
(Relative: Key.AMajor, Root: Note.FSharp, Accidents: 3, Quality: KeyQuality.Minor),
(Relative: Key.BFlatMajor, Root: Note.G, Accidents: -2, Quality: KeyQuality.Minor),
(Relative: Key.BMajor, Root: Note.GSharp, Accidents: 5, Quality: KeyQuality.Minor)
]
public var rootName: String
{
return root.Name
}
public var keyNotes:[Note]
{
return generateKeyNotes()
}
public var KeyNoteNames:[String]
{
return generateKeyNotes().map({ (note:Note) in return note.Name })
}
public func i() -> Note
{
return generateKeyNotes()[0]
}
public func ii() -> Note
{
return generateKeyNotes()[1]
}
public func iii() -> Note
{
return generateKeyNotes()[2]
}
public func iv() -> Note
{
return generateKeyNotes()[3]
}
public func v() -> Note
{
return generateKeyNotes()[4]
}
public func vi() -> Note
{
return generateKeyNotes()[5]
}
public func vii() -> Note
{
return self.quality == KeyQuality.Minor
? generateKeyNotes()[6].sharp()
: generateKeyNotes()[6]
}
public var quality: KeyQuality
{
return Key.allValues[self.rawValue].Quality
}
public var relativeKey: Key
{
return Key.allValues[self.rawValue].Relative
}
public func degreeForNote(note:Note) -> Int
{
return generateKeyNotes().indexOf(note)! + 1
}
private func generateKeyNotes() -> [Note]
{
if self.accidents < 0
{
return sortKeyNotes(createKeyFromFlatAccidents())
}
if self.accidents > 0
{
return sortKeyNotes(createKeyFromSharpAccidents())
}
return sortKeyNotes(Key.fifths);
}
private func createKeyFromFlatAccidents() -> [Note]
{
var keyNotes = Array(Key.fifths.reverse())
let max = (-1) * accidents
for i in 0 ..< max
{
keyNotes[i] = keyNotes[i].flat()
}
return keyNotes
}
private func createKeyFromSharpAccidents() -> [Note]
{
var keyNotes = Key.fifths
let max = accidents
for i in 0 ..< max
{
keyNotes[i] = keyNotes[i].sharp()
}
return keyNotes
}
private func sortKeyNotes(notes: [Note]) -> [Note]
{
var sortedkeyNotes = notes.sort({ n1, n2 in return n2 > n1 })
if(sortedkeyNotes.first == root)
{
return sortedkeyNotes
}
var last: Note? = nil
while(last != root)
{
last = sortedkeyNotes.last
sortedkeyNotes.removeLast()
sortedkeyNotes.insert(last!, atIndex: 0)
}
return sortedkeyNotes
}
private var root: Note
{
return Key.allValues[self.rawValue].Root
}
private var accidents: Int
{
return Key.allValues[self.rawValue].Accidents
}
} | mit | cec082afed95162f5be9f934ddfb82a0 | 28.321951 | 96 | 0.607321 | 3.988056 | false | false | false | false |
wuzhenli/MyDailyTestDemo | swiftTest/swifter-tips+swift+3.0/Swifter.playground/Pages/property-observer.xcplaygroundpage/Contents.swift | 2 | 1492 |
import Foundation
class MyClass {
let oneYearInSecond: TimeInterval = 365 * 24 * 60 * 60
var date: NSDate {
willSet {
let d = date
print("即将将日期从 \(d) 设定至 \(newValue)")
}
didSet {
if (date.timeIntervalSinceNow > oneYearInSecond) {
print("设定的时间太晚了!")
date = NSDate().addingTimeInterval(oneYearInSecond)
}
print("已经将日期从 \(oldValue) 设定至 \(date)")
}
}
init() {
date = NSDate()
}
}
let foo = MyClass()
foo.date = foo.date.addingTimeInterval(10086)
// 输出
// 即将将日期从 2014-08-23 12:47:36 +0000 设定至 2014-08-23 15:35:42 +0000
// 已经将日期从 2014-08-23 12:47:36 +0000 设定至 2014-08-23 15:35:42 +0000
// 365 * 24 * 60 * 60 = 31_536_000
foo.date = foo.date.addingTimeInterval(100_000_000)
// 输出
// 即将将日期从 2014-08-23 13:24:14 +0000 设定至 2017-10-23 23:10:54 +0000
// 设定的时间太晚了!
// 已经将日期从 2014-08-23 13:24:14 +0000 设定至 2015-08-23 13:24:14 +0000
class A {
var number :Int {
get {
print("get")
return 1
}
set {print("set")}
}
}
class B: A {
override var number: Int {
willSet {print("willSet")}
didSet {print("didSet")}
}
}
let b = B()
b.number = 0
// 输出
// get
// willSet
// set
// didSet
| apache-2.0 | 5ef29396ca0ca461efc949c8ccc5f1ac | 18.647059 | 67 | 0.527695 | 3.34 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Controller/Home/CHome.swift | 1 | 769 | import UIKit
class CHome:CController
{
let model:MHome
private weak var viewHome:VHome!
override init()
{
model = MHome()
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func loadView()
{
let viewHome:VHome = VHome(controller:self)
self.viewHome = viewHome
view = viewHome
}
//MARK: public
func selected(item:MHomeItem)
{
guard
let controller:CController = item.selected()
else
{
return
}
parentController.push(
controller:controller,
horizontal:CParent.TransitionHorizontal.fromRight)
}
}
| mit | 4ccff30b4c08615a083ddb26566e02e8 | 16.477273 | 62 | 0.513654 | 5.161074 | false | false | false | false |
weekenlee/Dodo | Dodo/Utils/UnderKeyboardDistrib.swift | 5 | 6026 | //
// An iOS libary for moving content from under the keyboard.
//
// https://github.com/exchangegroup/UnderKeyboard
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// UnderKeyboardLayoutConstraint.swift
//
// ----------------------------
import UIKit
/**
Adjusts the length (constant value) of the bottom layout constraint when keyboard shows and hides.
*/
@objc public class UnderKeyboardLayoutConstraint: NSObject {
private weak var bottomLayoutConstraint: NSLayoutConstraint?
private weak var bottomLayoutGuide: UILayoutSupport?
private var keyboardObserver = UnderKeyboardObserver()
private var initialConstraintConstant: CGFloat = 0
private var minMargin: CGFloat = 10
private var viewToAnimate: UIView?
public override init() {
super.init()
keyboardObserver.willAnimateKeyboard = keyboardWillAnimate
keyboardObserver.animateKeyboard = animateKeyboard
keyboardObserver.start()
}
deinit {
stop()
}
/// Stop listening for keyboard notifications.
public func stop() {
keyboardObserver.stop()
}
/**
Supply a bottom Auto Layout constraint. Its constant value will be adjusted by the height of the keyboard when it appears and hides.
- parameter bottomLayoutConstraint: Supply a bottom layout constraint. Its constant value will be adjusted when keyboard is shown and hidden.
- parameter view: Supply a view that will be used to animate the constraint. It is usually the superview containing the view with the constraint.
- parameter minMargin: Specify the minimum margin between the keyboard and the bottom of the view the constraint is attached to. Default: 10.
- parameter bottomLayoutGuide: Supply an optional bottom layout guide (like a tab bar) that will be taken into account during height calculations.
*/
public func setup(bottomLayoutConstraint: NSLayoutConstraint,
view: UIView, minMargin: CGFloat = 10,
bottomLayoutGuide: UILayoutSupport? = nil) {
initialConstraintConstant = bottomLayoutConstraint.constant
self.bottomLayoutConstraint = bottomLayoutConstraint
self.minMargin = minMargin
self.bottomLayoutGuide = bottomLayoutGuide
self.viewToAnimate = view
// Keyboard is already open when setup is called
if let currentKeyboardHeight = keyboardObserver.currentKeyboardHeight
where currentKeyboardHeight > 0 {
keyboardWillAnimate(currentKeyboardHeight)
}
}
func keyboardWillAnimate(height: CGFloat) {
guard let bottomLayoutConstraint = bottomLayoutConstraint else { return }
let layoutGuideHeight = bottomLayoutGuide?.length ?? 0
let correctedHeight = height - layoutGuideHeight
if height > 0 {
let newConstantValue = correctedHeight + minMargin
if newConstantValue > initialConstraintConstant {
// Keyboard height is bigger than the initial constraint length.
// Increase constraint length.
bottomLayoutConstraint.constant = newConstantValue
} else {
// Keyboard height is NOT bigger than the initial constraint length.
// Show the initial constraint length.
bottomLayoutConstraint.constant = initialConstraintConstant
}
} else {
bottomLayoutConstraint.constant = initialConstraintConstant
}
}
func animateKeyboard(height: CGFloat) {
viewToAnimate?.layoutIfNeeded()
}
}
// ----------------------------
//
// UnderKeyboardObserver.swift
//
// ----------------------------
import UIKit
/**
Detects appearance of software keyboard and calls the supplied closures that can be used for changing the layout and moving view from under the keyboard.
*/
public final class UnderKeyboardObserver: NSObject {
public typealias AnimationCallback = (height: CGFloat) -> ()
let notificationCenter: NSNotificationCenter
/// Function that will be called before the keyboard is shown and before animation is started.
public var willAnimateKeyboard: AnimationCallback?
/// Function that will be called inside the animation block. This can be used to call `layoutIfNeeded` on the view.
public var animateKeyboard: AnimationCallback?
/// Current height of the keyboard. Has value `nil` if unknown.
public var currentKeyboardHeight: CGFloat?
public override init() {
notificationCenter = NSNotificationCenter.defaultCenter()
super.init()
}
deinit {
stop()
}
/// Start listening for keyboard notifications.
public func start() {
stop()
notificationCenter.addObserver(self, selector: Selector("keyboardNotification:"), name:UIKeyboardWillShowNotification, object: nil);
notificationCenter.addObserver(self, selector: Selector("keyboardNotification:"), name:UIKeyboardWillHideNotification, object: nil);
}
/// Stop listening for keyboard notifications.
public func stop() {
notificationCenter.removeObserver(self)
}
// MARK: - Notification
func keyboardNotification(notification: NSNotification) {
let isShowing = notification.name == UIKeyboardWillShowNotification
if let userInfo = notification.userInfo,
let height = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue().height,
let duration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
let correctedHeight = isShowing ? height : 0
willAnimateKeyboard?(height: correctedHeight)
UIView.animateWithDuration(duration,
delay: NSTimeInterval(0),
options: UIViewAnimationOptions(rawValue: animationCurveRawNSN.unsignedLongValue),
animations: { [weak self] in
self?.animateKeyboard?(height: correctedHeight)
},
completion: nil
)
currentKeyboardHeight = correctedHeight
}
}
}
| mit | 1eb626d16e9062882c581f79791997ff | 31.224599 | 153 | 0.715234 | 5.948667 | false | false | false | false |
dejavu1988/google-services | ios/gcm/GcmExampleSwift/ViewController.swift | 21 | 3259 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
@objc(ViewController) // match the ObjC symbol name inside Storyboard
class ViewController: UIViewController {
@IBOutlet weak var registeringLabel: UILabel!
@IBOutlet weak var registrationProgressing: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateRegistrationStatus:",
name: appDelegate.registrationKey, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showReceivedMessage:",
name: appDelegate.messageKey, object: nil)
registrationProgressing.hidesWhenStopped = true
registrationProgressing.startAnimating()
}
func updateRegistrationStatus(notification: NSNotification) {
registrationProgressing.stopAnimating()
if let info = notification.userInfo as? Dictionary<String,String> {
if let error = info["error"] {
registeringLabel.text = "Error registering!"
showAlert("Error registering with GCM", message: error)
} else if let _ = info["registrationToken"] {
registeringLabel.text = "Registered!"
let message = "Check the xcode debug console for the registration token that you " +
" can use with the demo server to send notifications to your device"
showAlert("Registration Successful!", message: message)
}
} else {
print("Software failure. Guru meditation.")
}
}
func showReceivedMessage(notification: NSNotification) {
if let info = notification.userInfo as? Dictionary<String,AnyObject> {
if let aps = info["aps"] as? Dictionary<String, String> {
showAlert("Message received", message: aps["alert"]!)
}
} else {
print("Software failure. Guru meditation.")
}
}
func showAlert(title:String, message:String) {
if #available(iOS 8.0, *) {
let alert = UIAlertController(title: title,
message: message, preferredStyle: .Alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .Destructive, handler: nil)
alert.addAction(dismissAction)
self.presentViewController(alert, animated: true, completion: nil)
} else {
// Fallback on earlier versions
let alert = UIAlertView.init(title: title, message: message, delegate: nil,
cancelButtonTitle: "Dismiss")
alert.show()
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| apache-2.0 | 3e43ea9d13168183b67b5b1677eae420 | 37.341176 | 97 | 0.7085 | 4.778592 | false | false | false | false |
mirkofetter/TUIOSwift | TUIOSwift/TuioTime.swift | 1 | 9021 | //
// TuioTime.swift
// TUIOSwift
//
// Created by Mirko Fetter on 21.02.17.
// Copyright © 2017 grugru. All rights reserved.
//
import Foundation
/**
* The TuioTime class is a simple structure that is used to reprent the time that has elapsed since the session start.
* The time is internally represented as seconds and fractions of microseconds which should be more than sufficient for gesture related timing requirements.
* Therefore at the beginning of a typical TUIO session the static method initSession() will set the reference time for the session.
* Another important static method getSessionTime will return a TuioTime object representing the time elapsed since the session start.
* The class also provides various addtional convience method, which allow some simple time arithmetics.
*
* @author Mirko Fetter
* @version 0.9
*
* 1:1 Swift port of the TUIO 1.1 Java Library by Martin Kaltenbrunner
*/
class TuioTime {
/**
* the time since session start in seconds
*/
internal var seconds:CLong = 0;
/**
* time fraction in microseconds
*/
internal var micro_seconds:CLong = 0;
/**
* the session start time in seconds
*/
internal static var start_seconds:CLong = 0;
/**
* start time fraction in microseconds
*/
internal static var start_micro_seconds:CLong = 0;
/**
* the associated frame ID
*/
internal var frame_id:CLong = 0;
/**
* The default constructor takes no arguments and sets
* the Seconds and Microseconds attributes of the newly created TuioTime both to zero.
*/
init() {
self.seconds = 0;
self.micro_seconds = 0;
}
/**
* This constructor takes the provided time represented in total Milliseconds
* and assigs this value to the newly created TuioTime.
*
* @param msec the total time in Millseconds
*/
init ( msec:CLong) {
self.seconds = msec/1000;
self.micro_seconds = 1000*(msec%1000);
}
/**
* This constructor takes the provided time represented in Seconds and Microseconds
* and assigs these value to the newly created TuioTime.
*
* @param sec the total time in seconds
* @param usec the microseconds time component
*/
init (sec:CLong, usec:CLong) {
self.seconds = sec;
self.micro_seconds = usec;
}
/**
* This constructor takes the provided TuioTime
* and assigs its Seconds and Microseconds values to the newly created TuioTime.
*
* @param ttime the TuioTime used to copy
*/
init(ttime:TuioTime) {
self.seconds = ttime.getSeconds();
self.micro_seconds = ttime.getMicroseconds();
}
/**
* This constructor takes the provided TuioTime
* and assigs its Seconds and Microseconds values to the newly created TuioTime.
*
* @param ttime the TuioTime used to copy
* @param the Frame ID to associate
*/
init(ttime:TuioTime, f_id:CLong) {
self.seconds = ttime.getSeconds();
self.micro_seconds = ttime.getMicroseconds();
self.frame_id = f_id;
}
/**
* Sums the provided time value represented in total Microseconds to this TuioTime.
*
* @param us the total time to add in Microseconds
* @return the sum of this TuioTime with the provided argument in microseconds
*/
func add(us:CLong) -> TuioTime{
let sec:CLong = seconds + us/1000000;
let usec:CLong = micro_seconds + us%1000000;
return TuioTime(sec: sec,usec: usec);
}
/**
* Sums the provided TuioTime to the private Seconds and Microseconds attributes.
*
* @param ttime the TuioTime to add
* @return the sum of this TuioTime with the provided TuioTime argument
*/
func add( ttime: TuioTime) -> TuioTime{
var sec:CLong = seconds + ttime.getSeconds();
var usec:CLong = micro_seconds + ttime.getMicroseconds();
sec += usec/1000000;
usec = usec%1000000;
return TuioTime(sec:sec,usec:usec);
}
/**
* Subtracts the provided time represented in Microseconds from the private Seconds and Microseconds attributes.
*
* @param us the total time to subtract in Microseconds
* @return the subtraction result of this TuioTime minus the provided time in Microseconds
*/
func subtract(us:CLong) -> TuioTime{
var sec:CLong = seconds - us/1000000;
var usec:CLong = micro_seconds - us%1000000;
if (usec<0) {
usec += 1000000;
sec-=1;
}
return TuioTime(sec:sec,usec:usec);
}
/**
* Subtracts the provided TuioTime from the private Seconds and Microseconds attributes.
*
* @param ttime the TuioTime to subtract
* @return the subtraction result of this TuioTime minus the provided TuioTime
*/
func subtract( ttime: TuioTime) -> TuioTime{
var sec:CLong = seconds - ttime.getSeconds();
var usec:CLong = micro_seconds - ttime.getMicroseconds();
if (usec<0) {
usec += 1000000;
sec-=1;
}
return TuioTime(sec:sec,usec:usec);
}
/**
* Takes a TuioTime argument and compares the provided TuioTime to the private Seconds and Microseconds attributes.
*
* @param ttime the TuioTime to compare
* @return true if the two TuioTime have equal Seconds and Microseconds attributes
*/
func equals( ttime: TuioTime) -> Bool{
if ((seconds==ttime.getSeconds()) && (micro_seconds==ttime.getMicroseconds())) {
return true;
}else {
return false;
}
}
/**
* Resets the seconds and micro_seconds attributes to zero.
*/
func reset() {
seconds = 0;
micro_seconds = 0;
}
/**
* Returns the TuioTime Seconds component.
* @return the TuioTime Seconds component
*/
func getSeconds()->CLong {
return seconds;
}
/**
* Returns the TuioTime Microseconds component.
* @return the TuioTime Microseconds component
*/
func getMicroseconds() ->CLong {
return micro_seconds;
}
/**
* Returns the total TuioTime in Milliseconds.
* @return the total TuioTime in Milliseconds
*/
func getTotalMilliseconds()-> CLong{
return seconds*1000+micro_seconds/1000;
}
/**
* This static method globally resets the TUIO session time.
*/
static func initSession() {
let startTime:TuioTime = getSystemTime();
start_seconds = startTime.getSeconds();
start_micro_seconds = startTime.getMicroseconds();
}
/**
* Returns the present TuioTime representing the time since session start.
* @return the present TuioTime representing the time since session start
*/
static func getSessionTime()->TuioTime{
let sessionTime:TuioTime = getSystemTime().subtract(ttime: getStartTime());
return sessionTime;
}
/**
* Returns the absolut TuioTime representing the session start.
* @return the absolut TuioTime representing the session start
*/
static func getStartTime()->TuioTime{
return TuioTime(sec: self.start_seconds, usec: self.start_micro_seconds)
}
/**
* Returns the absolut TuioTime representing the current system time.
* @return the absolut TuioTime representing the current system time
*/
static func getSystemTime()->TuioTime{
//ToDo check if this equals Java long usec = System.nanoTime()/1000;
//--
let time = mach_absolute_time();
var timeBaseInfo = mach_timebase_info_data_t()
mach_timebase_info(&timeBaseInfo)
let elapsedNano = (time * UInt64(timeBaseInfo.numer) / UInt64(timeBaseInfo.denom))/1000;
let usec:CLong = CLong(elapsedNano);
//--
return TuioTime(sec: usec/1000000,usec: usec%1000000);
}
/**
* associates a Frame ID to this TuioTime.
* @param f_id the Frame ID to associate
*/
func setFrameID( f_id:CLong) {
frame_id=f_id;
}
/**
* Returns the Frame ID associated to this TuioTime.
* @return the Frame ID associated to this TuioTime
*/
func getFrameID() -> CLong {
return frame_id;
}
static func getSystemTimeMillis()->CLong{
//ToDo check if this equals Java long usec = System.nanoTime()/1000;
//--
let time = mach_absolute_time();
var timeBaseInfo = mach_timebase_info_data_t()
mach_timebase_info(&timeBaseInfo)
let elapsedNano = (time * UInt64(timeBaseInfo.numer) / UInt64(timeBaseInfo.denom))/1000;
return CLong(elapsedNano);
}
}
| mit | 376dcbe5c88bae57988f820d5ef0979e | 29.066667 | 156 | 0.616297 | 4.647089 | false | false | false | false |
ZevEisenberg/Padiddle | Padiddle/Padiddle/Utilities/HelpImageHandler.swift | 1 | 1530 | //
// HelpImageProtocol.swift
// Padiddle
//
// Created by Zev Eisenberg on 1/22/16.
// Copyright © 2016 Zev Eisenberg. All rights reserved.
//
import Foundation
import UIKit.UIImage
import WebKit
/// Handle asset://assetName requests from WKWebView and return the appropriate
/// image asset. Built with the help of https://medium.com/glose-team/custom-scheme-handling-and-wkwebview-in-ios-11-72bc5113e344
class HelpImageHandler: NSObject, WKURLSchemeHandler {
static var colorButtonImage: UIImage?
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
guard
let url = urlSchemeTask.request.url,
url.scheme == "asset",
let imageName = url.host
else { return }
var image: UIImage?
switch imageName {
case "recordButton":
image = UIImage.recordButtonImage()
case "colorButton":
image = HelpImageHandler.colorButtonImage
default:
image = UIImage(named: imageName)
}
guard
let existingImage = image,
let imageData = existingImage.pngData()
else { return }
let urlResponse = URLResponse(url: url, mimeType: "image/png", expectedContentLength: imageData.count, textEncodingName: nil)
urlSchemeTask.didReceive(urlResponse)
urlSchemeTask.didReceive(imageData)
urlSchemeTask.didFinish()
}
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
}
}
| mit | 768033a63bec74655fb119413cca1e9c | 29.58 | 133 | 0.656638 | 4.704615 | false | false | false | false |
khillman84/music-social | music-social/music-social/FancyView.swift | 1 | 580 | //
// FancyView.swift
// music-social
//
// Created by Kyle Hillman on 4/22/17.
// Copyright © 2017 Kyle Hillman. All rights reserved.
//
import UIKit
class FancyView: UIView {
override func awakeFromNib() {
super.awakeFromNib()
//Set the shadow size and look
layer.shadowColor = UIColor(red: gShadowGray, green: gShadowGray, blue: gShadowGray, alpha: 0.6).cgColor
layer.shadowOpacity = 0.8
layer.shadowRadius = 5.0
layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
layer.cornerRadius = 2.0
}
}
| mit | 941dba7f2c3dcfd28cae25bc5890ba64 | 23.125 | 112 | 0.632124 | 3.784314 | false | false | false | false |
AcaiBowl/Closurable | Closurable/Releasable.swift | 1 | 780 | //
// Releasable.swift
// Closurable
//
// Created by Toru Asai on 2017/09/07.
// Copyright © 2017年 AcaiBowl. All rights reserved.
//
import Foundation
public protocol Releasable {
func release()
}
public final class ActionReleasable: Releasable {
private var _observer: Any?
private var _action: (() -> Void)?
public init(with observer: Any, action: @escaping () -> Void) {
_observer = observer
_action = action
}
public func release() {
_action?()
_observer = nil
}
}
public final class NoOptionalReleasable: Releasable {
private var _observer: Any?
public init(with observer: Any) {
_observer = observer
}
public func release() {
_observer = nil
}
}
| mit | 2a20ef4f5554db9c67e4f8bba05fa353 | 18.425 | 67 | 0.599743 | 3.904523 | false | false | false | false |
ViacomInc/Router | Source/Router.swift | 1 | 3871 | ////////////////////////////////////////////////////////////////////////////
// Copyright 2015 Viacom Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////
import UIKit
public typealias RouteHandler = (_ req: Request) -> Void
open class Router {
fileprivate var orderedRoutes = [Route]()
fileprivate var routes = [Route: RouteHandler]()
public init() {}
/**
Binds a route to a router
- parameter aRoute: A string reprsentation of the route. It can include url params, for example id in /video/:id
- parameter callback: Triggered when a route is matched
*/
open func bind(_ aRoute: String, callback: @escaping RouteHandler) {
do {
let route = try Route(aRoute: aRoute)
orderedRoutes.append(route)
routes[route] = callback
} catch let error as Route.RegexResult {
print(error.debugDescription)
} catch {
fatalError("[\(aRoute)] unknown bind error")
}
}
/**
Matches an incoming URL to a route present in the router. Returns nil if none are matched.
- parameter url: An URL of an incoming request to the router
- returns: The matched route or nil
*/
open func match(_ url: URL) -> Route? {
guard let routeComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return nil
}
// form the host/path url
let host = routeComponents.host.flatMap({"/\($0)"}) ?? ""
let path = routeComponents.path
let routeToMatch = "\(host)\(path)"
let queryParams = routeComponents.queryItems
var urlParams = [URLQueryItem]()
// match the route!
for route in orderedRoutes {
guard let pattern = route.routePattern else {
continue
}
var regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: pattern,
options: .caseInsensitive)
} catch let error as NSError {
fatalError(error.localizedDescription)
}
let matches = regex.matches(in: routeToMatch, options: [],
range: NSMakeRange(0, routeToMatch.characters.count))
// check if routeToMatch has matched
if matches.count > 0 {
let match = matches[0]
// gather url params
for i in 1 ..< match.numberOfRanges {
let name = route.urlParamKeys[i-1]
let value = (routeToMatch as NSString).substring(with: match.rangeAt(i))
urlParams.append(URLQueryItem(name: name, value: value))
}
// fire callback
if let callback = routes[route] {
callback(Request(aRoute: route, urlParams: urlParams, queryParams: queryParams))
}
// return route that was matched
return route
}
}
// nothing matched
return nil
}
}
| apache-2.0 | 60046aa428da45360ca790742897434c | 35.17757 | 120 | 0.536554 | 5.421569 | false | false | false | false |
sublimter/Meijiabang | KickYourAss/KickYourAss/LCYMyCommentTableViewCell.swift | 3 | 1647 | //
// LCYMyCommentTableViewCell.swift
// KickYourAss
//
// Created by eagle on 15/2/11.
// Copyright (c) 2015年 多思科技. All rights reserved.
//
import UIKit
class LCYMyCommentTableViewCell: UITableViewCell {
@IBOutlet private weak var avatarImageView: UIImageView!
var imagePath: String? {
didSet {
if let path = imagePath {
avatarImageView.setImageWithURL(NSURL(string: path), placeholderImage: UIImage(named: "avatarPlaceholder"))
} else {
avatarImageView.image = UIImage(named: "avatarPlaceholder")
}
}
}
@IBOutlet weak var nickNameLabel: UILabel!
@IBOutlet private var starImageViews: [UIImageView]!
/// 作品积分
var markCount: Double = 0 {
didSet {
for tinker in starImageViews {
if Double(tinker.tag) > markCount {
tinker.image = UIImage(named: "AboutMeHeaderEmpty")
} else {
tinker.image = UIImage(named: "AboutMeHeader")
}
}
}
}
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
class var identifier: String {
return "LCYMyCommentTableViewCellIdentifier"
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
avatarImageView.roundedCorner = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | e6ede662c0e21c4a20446b4217ae1995 | 25.704918 | 123 | 0.594843 | 4.906627 | false | false | false | false |
peferron/algo | EPI/Heaps/Compute the k closest stars/swift/test.swift | 1 | 1505 | import Darwin
func == (lhs: [Coordinates], rhs: [Coordinates]) -> Bool {
guard lhs.count == rhs.count else {
return false
}
for (index, element) in lhs.enumerated() {
guard rhs[index] == element else {
return false
}
}
return true
}
let tests: [(stars: [Coordinates], k: Int, closest: [Coordinates])] = [
(
stars: [],
k: 10,
closest: []
),
(
stars: [
(3, 0, 0),
(2, 0, 0),
],
k: 10,
closest: [
(3, 0, 0),
(2, 0, 0),
]
),
(
stars: [
(3, 0, 0),
(0, 7, 0),
(2, 0, 0),
(5, 2, 0),
(0, 4, 0),
(0, 1, 1),
(1, 2, 3),
],
k: 1,
closest: [
(0, 1, 1),
]
),
(
stars: [
(3, 0, 0),
(0, 7, 0),
(2, 0, 0),
(5, 2, 0),
(0, 4, 0),
(0, 1, 1),
(1, 2, 3),
],
k: 4,
closest: [
(1, 2, 3),
(3, 0, 0),
(2, 0, 0),
(0, 1, 1),
]
),
]
for test in tests {
let actual = closest(stars: test.stars, count: test.k)
guard actual == test.closest else {
print("For test stars \(test.stars) and k \(test.k), " +
"expected k closest stars to be \(test.closest), but were \(actual)")
exit(1)
}
}
| mit | 1e49825d9e57270feb64608b1addc384 | 19.337838 | 81 | 0.33289 | 3.412698 | false | true | false | false |
whitehawks/CommoniOSViews | CommoniOSViews/Classes/UIViews/GradientView.swift | 1 | 1712 | //
// GradientView.swift
// Pods
//
// Created by Sharif Khaleel on 6/12/17.
//
//
import Foundation
import UIKit
@IBDesignable
public class GradientView: UIView {
@IBInspectable var startColor: UIColor = .black { didSet { updateColors() }}
@IBInspectable var endColor: UIColor = .white { didSet { updateColors() }}
@IBInspectable var startLocation: Double = 0 { didSet { updateLocations() }}
@IBInspectable var endLocation: Double = 1 { didSet { updateLocations() }}
@IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }}
@IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }}
override public class var layerClass: AnyClass { return CAGradientLayer.self }
var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer }
func updatePoints() {
if horizontalMode {
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5)
} else {
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1)
}
}
func updateLocations() {
gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
}
func updateColors() {
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
}
override public func layoutSubviews() {
super.layoutSubviews()
updatePoints()
updateLocations()
updateColors()
}
}
| mit | 5e3f91c414fbff98d0fc198693d2e99a | 34.666667 | 97 | 0.632009 | 4.367347 | false | false | false | false |
ayunav/AudioKit | Tests/Tests/AKSimpleWaveGuideModel.swift | 3 | 1753 | //
// main.swift
// AudioKit
//
// Created by Nick Arner and Aurelius Prochazka on 11/30/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: NSTimeInterval = 11.0
class Instrument : AKInstrument {
override init() {
super.init()
let filename = "AKSoundFiles.bundle/Sounds/PianoBassDrumLoop.wav"
let audio = AKFileInput(filename: filename)
let mono = AKMix(monoAudioFromStereoInput: audio)
let simpleWaveGuideModel = AKSimpleWaveGuideModel(input: mono)
let cutoffLine = AKLine(firstPoint: 1000.ak, secondPoint: 5000.ak, durationBetweenPoints: testDuration.ak)
let frequencyLine = AKLine(firstPoint: 12.ak, secondPoint: 1000.ak, durationBetweenPoints: testDuration.ak)
let feedbackLine = AKLine(firstPoint: 0.ak, secondPoint: 0.8.ak, durationBetweenPoints: testDuration.ak)
simpleWaveGuideModel.cutoff = cutoffLine
simpleWaveGuideModel.frequency = frequencyLine
simpleWaveGuideModel.feedback = feedbackLine
setAudioOutput(simpleWaveGuideModel)
enableParameterLog(
"Cutoff = ",
parameter: simpleWaveGuideModel.cutoff,
timeInterval:0.1
)
enableParameterLog(
"Frequency = ",
parameter: simpleWaveGuideModel.frequency,
timeInterval:0.1
)
enableParameterLog(
"Feedback = ",
parameter: simpleWaveGuideModel.feedback,
timeInterval:0.1
)
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
instrument.play()
NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
| mit | 5356d80c503e26c37be5b8231b5c0b56 | 27.737705 | 115 | 0.681689 | 5.066474 | false | true | false | false |
PaulWoodIII/tipski | TipskyiOS/Tipski/AddEmojiViewController.swift | 1 | 4020 | //
// AddEmojiViewController.swift
// Tipski
//
// Created by Paul Wood on 9/15/16.
// Copyright © 2016 Paul Wood. All rights reserved.
//
import Foundation
import UIKit
protocol AddEmojiDelegate : class {
func didAddEmoji(tipEmoji: TipEmoji)
}
class AddEmojiViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITextFieldDelegate {
weak var delegate : AddEmojiDelegate?
@IBOutlet weak var emojiTextField: UITextField!
@IBOutlet weak var tipTextField: UITextField!
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var collectionView: UICollectionView!
var filteredEmojis : [Emoji] = Emoji.allEmojis
var newItem = TipEmoji(emoji: "",tipAmount: 0)
override func viewDidLoad() {
super.viewDidLoad()
collectionView.isHidden = true
Appearance.createWellFromView(view: containerView)
Appearance.createInput(textField: emojiTextField)
Appearance.createInput(textField: tipTextField)
Appearance.createSubmitButton(button: addButton)
}
@IBAction func emojiTextDidChange(_ textField: UITextField) {
if let text = textField.text ,
text != "",
!collectionView.isHidden {
filteredEmojis = Emoji.allEmojis.filter() {
return ($0.fts as NSString).localizedCaseInsensitiveContains(text)
}
print(filteredEmojis)
}
collectionView.reloadData()
if let newText = emojiTextField.text,
newText.isEmoji {
newItem.emoji = newText
}
}
@IBAction func tipAmountDidChange(_ sender: AnyObject) {
if let newTip = tipTextField.text,
let tipDouble = Double(newTip){
newItem.tipAmount = tipDouble
}
else {
newItem.tipAmount = Double(0)
}
}
@IBAction func addButtonPressed(_ sender: AnyObject) {
if newItem.isValid() {
delegate?.didAddEmoji(tipEmoji: newItem)
}
else {
//Display Error
}
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filteredEmojis.count
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EmojiCollectionViewCell", for: indexPath)
print(cell.subviews)
let label = cell.viewWithTag(1) as! UILabel
label.text = filteredEmojis[indexPath.row].char
return cell
}
//
func textFieldDidBeginEditing(_ textField: UITextField) {
// became first responder
if textField == emojiTextField {
//display the UICollectionView
collectionView.isHidden = false
}
}
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason){
if textField == emojiTextField {
collectionView.isHidden = true
}
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == emojiTextField {
emojiTextDidChange(textField)
}
return true
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
let char = filteredEmojis[indexPath.row].char
if char.isEmoji {
emojiTextField.text = char
newItem.emoji = char
}
else {
//display error in emoji text field
}
emojiTextField.resignFirstResponder()
}
}
| mit | 7ba093cf52bdcf1a8546acdf9aed9ab7 | 29.915385 | 136 | 0.63996 | 5.597493 | false | false | false | false |
hzalaz/analytics-ios | Example/Tests/FileStorageTest.swift | 1 | 3867 | //
// FileStorageTest.swift
// Analytics
//
// Copyright © 2016 Segment. All rights reserved.
//
import Quick
import Nimble
import Analytics
class FileStorageTest : QuickSpec {
override func spec() {
var storage : SEGFileStorage!
beforeEach {
let url = SEGFileStorage.applicationSupportDirectoryURL()
expect(url).toNot(beNil())
expect(url?.lastPathComponent) == "Application Support"
storage = SEGFileStorage(folder: url!, crypto: nil)
}
it("creates folder if none exists") {
let tempDir = NSURL(fileURLWithPath: NSTemporaryDirectory())
let url = tempDir.URLByAppendingPathComponent(NSUUID().UUIDString)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
_ = SEGFileStorage(folder: url, crypto: nil)
var isDir: ObjCBool = false
let exists = NSFileManager.defaultManager().fileExistsAtPath(url.path!, isDirectory: &isDir)
expect(exists) == true
expect(Bool(isDir)) == true
}
it("persists and loads data") {
let dataIn = "segment".dataUsingEncoding(NSUTF8StringEncoding)!
storage.setData(dataIn, forKey: "mydata")
let dataOut = storage.dataForKey("mydata")
expect(dataOut) == dataIn
let strOut = String(data: dataOut!, encoding: NSUTF8StringEncoding)
expect(strOut) == "segment"
}
it("persists and loads string") {
let str = "san francisco"
storage.setString(str, forKey: "city")
expect(storage.stringForKey("city")) == str
storage.removeKey("city")
expect(storage.stringForKey("city")).to(beNil())
}
it("persists and loads array") {
let array = [
"san francisco",
"new york",
"tallinn",
]
storage.setArray(array, forKey: "cities")
expect(storage.arrayForKey("cities") as? Array<String>) == array
storage.removeKey("cities")
expect(storage.arrayForKey("cities")).to(beNil())
}
it("persists and loads dictionary") {
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
storage.setDictionary(dict, forKey: "cityMap")
expect(storage.dictionaryForKey("cityMap") as? Dictionary<String, String>) == dict
storage.removeKey("cityMap")
expect(storage.dictionaryForKey("cityMap")).to(beNil())
}
it("saves file to disk and removes from disk") {
let key = "input.txt"
let url = storage.urlForKey(key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
storage.setString("sloth", forKey: key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == true
storage.removeKey(key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
}
it("should be binary compatible with old SDKs") {
let key = "traits.plist"
let dictIn = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
(dictIn as NSDictionary).writeToURL(storage.urlForKey(key), atomically: true)
let dictOut = storage.dictionaryForKey(key)
expect(dictOut as? [String: String]) == dictIn
}
it("should work with crypto") {
let url = SEGFileStorage.applicationSupportDirectoryURL()
let crypto = SEGAES256Crypto(password: "thetrees")
let s = SEGFileStorage(folder: url!, crypto: crypto)
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
s.setDictionary(dict, forKey: "cityMap")
expect(s.dictionaryForKey("cityMap") as? Dictionary<String, String>) == dict
s.removeKey("cityMap")
expect(s.dictionaryForKey("cityMap")).to(beNil())
}
afterEach {
storage.resetAll()
}
}
}
| mit | 5698080d03fbc544dd9dbb8159836b1e | 30.430894 | 98 | 0.622866 | 4.433486 | false | false | false | false |
developerY/Active-Learning-Swift-2.0_DEMO | ActiveLearningSwift2.playground/Pages/Generics.xcplaygroundpage/Contents.swift | 3 | 10757 | //: [Previous](@previous)
// ------------------------------------------------------------------------------------------------
// Things to know:
//
// * Generics allow flexible, reusable functions and types that can work with any type, subject
// to restrictions that you define.
//
// * Swift's Array and Dictionary are both Generics.
//
// * Generics can be applied to Functions, Structures, Classes and Enumerations.
// ------------------------------------------------------------------------------------------------
// The problem that Generics solve
//
// Consider the following function which can swap two Ints.
func swapTwoInts(inout a: Int, inout b: Int)
{
let tmp = a
a = b
b = tmp
}
// What if we wanted to swap Strings? Or any other type? We would need to write a lot of different
// swap functions. Instead, let's use Generics. Consider the following generic function:
func swapTwoValues<T>(inout a: T, inout b: T)
{
let tmp = a
a = b
b = tmp
}
// The 'swapTwoValues()' function is a generic function in a sense that some or all of the types
// that it works on are generic (i.e., specific only to the calls placed on that function.)
//
// Study the first line of the function and notice the use of <T> and the type for 'a' and 'b' as
// type T. In this case, T is just a placeholder for a type and by studying this function, we can
// see that both 'a' and 'b' are the same type.
//
// If we call this function with two Integers, it will treat the function as one declared to accept
// two Ints, but if we pass in two Strings, it will work on Strings.
//
// If we study the body of the function, we'll see that it is coded in such a way as to work with
// any type passed in: The 'tmp' parameter's type is inferred by the value 'a' and 'a' and 'b' must
// be assignable. If any of this criteria are not met, a compilation error will appear for the
// function call the tries to call swapTwoValues() with a type that doesn't meet this criteria.
//
// Although we're using T as the name for our type placeholder, we can use any name we wish, though
// T is a common placeholder for single type lists. If we were to create a new implementation of
// the Dictionary class, we would want to use two type parameters and name them effectively, such
// as <KeyType, ValueType>.
//
// A type placholder can also be used to define the return type.
//
// Let's call it a few times to see it in action:
var aInt = 3
var bInt = 4
swapTwoValues(&aInt, &bInt)
aInt
bInt
var aDouble = 3.3
var bDouble = 4.4
swapTwoValues(&aDouble, &bDouble)
aDouble
bDouble
var aString = "three"
var bString = "four"
swapTwoValues(&aString, &bString)
aString
bString
// ------------------------------------------------------------------------------------------------
// Generic Types
//
// So far we've seen how to apply Generics to a function, let's see how they can be applied to
// a struct. We'll define a standard 'stack' implementation which works like an array that can
// "push" an element to the end of the array, or "pop" an element off of the end of the array.
//
// As you can see, the type placeholder, once defined for a struct, can be used anywhere in that
// struct to represent the given type. In the code below, the the type placeholder is used as the
// type for a property, the input parameter for a method and the return value for a method.
struct Stack<T>
{
var items = [T]()
mutating func push(item: T)
{
items.append(item)
}
mutating func pop() -> T
{
return items.removeLast()
}
}
// Let's use our new Stack:
var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")
stackOfStrings.push("cuatro")
stackOfStrings.pop()
stackOfStrings.pop()
stackOfStrings.pop()
stackOfStrings.pop()
// ------------------------------------------------------------------------------------------------
// Type constraints
//
// So far, our type parameters are completely Generic - they can represent any given type.
// Sometimes we may want to apply constraints to those types. For example, the Swift Dictionary
// type uses generics and places a constraint on the key's type that it must be hashable (i.e., it
// must conform to the Hashable protocol, defined in the Swift standard library.)
//
// Constraints are defined with the following syntax:
func doSomethingWithKeyValue<KeyType: Hashable, ValueType>(someKey: KeyType, someValue: ValueType)
{
// Our keyType is known to be a Hashable, so we can use the hashValue defined by that protocol
// shown here:
someKey.hashValue
// 'someValue' is an unknown type to us, we'll just drop it here in case it's ever used so we
// can see the value
someValue
}
// Let's see type constraints in action. We'll create a function that finds a given value within
// an array and returns an optional index into the array where the first element was found.
//
// Take notice the constraint "Equatable" on the type T, which is key to making this function
// compile. Without it, we would get an error on the conditional statement used to compare each
// element from the array with the value being searched for. By including the Equatable, we tell
// the generic function that it is guaranteed to receive only values that meet that specific
// criteria.
func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int?
{
for (index, value) in enumerate(array)
{
if value == valueToFind
{
return index
}
}
return nil
}
// Let's try a few different inputs
let doubleIndex = findIndex([3.14159, 0.1, 0.25], 9.3)
let stringIndex = findIndex(["Mike", "Malcolm", "Andrea"], "Andrea")
// ------------------------------------------------------------------------------------------------
// Associated types
//
// Protocols use a different method of defining generic types, called Associated Types, which use
// type inference combined with Type Aliases.
//
// Let's jump right into some code:
protocol Container
{
typealias ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
// In the example above, we declare a Type Alias called ItemType, but because we're declaring
// a protocol, we're only declaring the requirement for the conforming target to provide the
// actual type alias.
//
// With Generics, the type of ItemType can actually be inferred, such that it provides the correct
// types for the append() and the subscript implementations.
//
// Let's see this in action as we turn our Stack into a container:
struct StackContainer<T> : Container
{
// Here we find our original stack implementation, unmodified
var items = [T]()
mutating func push(item: T)
{
items.append(item)
}
mutating func pop() -> T
{
return items.removeLast()
}
// Below, we conform to the protocol
mutating func append(item: T)
{
self.push(item)
}
var count: Int
{
return items.count
}
subscript(i: Int) -> T
{
return items[i]
}
}
// The new StackContainer is now ready to go. You may notice that it does not include the
// typealias that was required as part of the Container protocol. This is because the all of the
// places where an ItemType would be used are using T. This allows Swift to perform a backwards
// inferrence that ItemType must be a type T, and it allows this requirement to be met.
//
// Let's verify our work:
var stringStack = StackContainer<String>()
stringStack.push("Albert")
stringStack.push("Andrew")
stringStack.push("Betty")
stringStack.push("Jacob")
stringStack.pop()
stringStack.count
var doubleStack = StackContainer<Double>()
doubleStack.push(3.14159)
doubleStack.push(42.0)
doubleStack.push(1_000_000)
doubleStack.pop()
doubleStack.count
// We can also extend an existing types to conform to our new generic protocol. As it turns out
// Swift's built-in Array class already supports the requirements of our Container.
//
// Also, since the protocol's type inferrence method of implementing Generics, we can extend
// String without the need to modify String other than to extend it to conform to the protocol:
extension Array: Container {}
// ------------------------------------------------------------------------------------------------
// Where Clauses
//
// We can further extend our constraints on a type by including where clauses as part of a type
// parameter list. Where clauses provide a means for more constraints on associated types and/or
// one or more equality relationships between types and associated types.
//
// Let's take a look at a where clause in action. We'll define a function that works on two
// different containers that that must contain the same type of item.
func allItemsMatch
<C1: Container, C2: Container where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
(someContainer: C1, anotherContainer: C2) -> Bool
{
// Check that both containers contain the same number of items
if someContainer.count != anotherContainer.count
{
return false
}
// Check each pair of items to see if they are equivalent
for i in 0..<someContainer.count
{
if someContainer[i] != anotherContainer[i]
{
return false
}
}
// All items match, so return true
return true
}
// The function's type parameter list places the following restrictions on the types allowed:
//
// * C1 must conform to the Container protocol (C1: Container)
// * C2 must also conform to the Container protocol (C1: Container)
// * The ItemType for C1 must be the same as the ItemType for C2 (C1.ItemType == C2.ItemType)
// * The ItemType for C1 must conform to the Equatable protocol (C1.ItemType: Equatable)
//
// Note that we only need to specify that C1.ItemType conforms to Equatable because the code
// only calls the != operator (part of the Equatable protocol) on someContainer, which is the
// type C1.
//
// Let's test this out by passing the same value for each parameter which should definitely
// return true:
allItemsMatch(doubleStack, doubleStack)
// We can compare stringStack against an array of type String[] because we've extended Swift's
// Array type to conform to our Container protocol:
allItemsMatch(stringStack, ["Alpha", "Beta", "Theta"])
// Finally, if we attempt to call allItemsMatch with a stringStack and a doubleStack, we would get
// a compiler error because they do not store the same ItemType as defined in the function's
// where clause.
//
// The following line of code does not compile:
//
// allItemsMatch(stringStack, doubleStack)
//: [Next](@next)
| apache-2.0 | 28ca6b63cc89a15959347e8f9f428a1e | 35.341216 | 99 | 0.672678 | 4.258511 | false | false | false | false |
lumoslabs/realm-cocoa | examples/ios/swift-2.0/Migration/AppDelegate.swift | 1 | 5364 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import UIKit
import RealmSwift
// Old data models
/* V0
class Person: Object {
dynamic var firstName = ""
dynamic var lastName = ""
dynamic var age = 0
}
*/
/* V1
class Person: Object {
dynamic var fullName = "" // combine firstName and lastName into single field
dynamic var age = 0
}
*/
/* V2 */
class Pet: Object {
dynamic var name = ""
dynamic var type = ""
}
class Person: Object {
dynamic var fullName = ""
dynamic var age = 0
let pets = List<Pet>() // Add pets field
}
func bundlePath(path: String) -> String? {
let resourcePath = NSBundle.mainBundle().resourcePath as NSString?
return resourcePath?.stringByAppendingPathComponent(path)
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = UIViewController()
window?.makeKeyAndVisible()
// copy over old data files for migration
let defaultPath = Realm.defaultPath
let defaultParentPath = (defaultPath as NSString).stringByDeletingLastPathComponent
if let v0Path = bundlePath("default-v0.realm") {
try! NSFileManager.defaultManager().removeItemAtPath(defaultPath)
try! NSFileManager.defaultManager().copyItemAtPath(v0Path, toPath: defaultPath)
}
// define a migration block
// you can define this inline, but we will reuse this to migrate realm files from multiple versions
// to the most current version of our data model
let migrationBlock: MigrationBlock = { migration, oldSchemaVersion in
if oldSchemaVersion < 1 {
migration.enumerate(Person.className()) { oldObject, newObject in
if oldSchemaVersion < 1 {
// combine name fields into a single field
let firstName = oldObject!["firstName"] as! String
let lastName = oldObject!["lastName"] as! String
newObject?["fullName"] = "\(firstName) \(lastName)"
}
}
}
if oldSchemaVersion < 2 {
migration.enumerate(Person.className()) { oldObject, newObject in
// give JP a dog
if newObject?["fullName"] as? String == "JP McDonald" {
let jpsDog = migration.create(Pet.className(), value: ["Jimbo", "dog"])
let dogs = newObject?["pets"] as? List<MigrationObject>
dogs?.append(jpsDog)
}
}
}
print("Migration complete.")
}
setDefaultRealmSchemaVersion(3, migrationBlock: migrationBlock)
// print out all migrated objects in the default realm
// migration is performed implicitly on Realm access
print("Migrated objects in the default Realm: \(try! Realm().objects(Person))")
//
// Migrate a realms at a custom paths
//
if let v1Path = bundlePath("default-v1.realm"), v2Path = bundlePath("default-v2.realm") {
let realmv1Path = (defaultParentPath as NSString).stringByAppendingPathComponent("default-v1.realm")
let realmv2Path = (defaultParentPath as NSString).stringByAppendingPathComponent("default-v2.realm")
setSchemaVersion(3, realmPath: realmv1Path, migrationBlock: migrationBlock)
setSchemaVersion(3, realmPath: realmv2Path, migrationBlock: migrationBlock)
try! NSFileManager.defaultManager().removeItemAtPath(realmv1Path)
try! NSFileManager.defaultManager().copyItemAtPath(v1Path, toPath: realmv1Path)
try! NSFileManager.defaultManager().removeItemAtPath(realmv2Path)
try! NSFileManager.defaultManager().copyItemAtPath(v2Path, toPath: realmv2Path)
// migrate realms at realmv1Path manually, realmv2Path is migrated automatically on access
migrateRealm(realmv1Path)
// print out all migrated objects in the migrated realms
let realmv1 = try! Realm(path: realmv1Path)
print("Migrated objects in the Realm migrated from v1: \(realmv1.objects(Person))")
let realmv2 = try! Realm(path: realmv2Path)
print("Migrated objects in the Realm migrated from v2: \(realmv2.objects(Person))")
}
return true
}
}
| apache-2.0 | 32b660079224b03276d2b004f07f80dd | 39.330827 | 128 | 0.623602 | 5.207767 | false | false | false | false |
devxoul/allkdic | LauncherApplication/AppDelegate.swift | 1 | 1025 | //
// AppDelegate.swift
// LauncherApplication
//
// Created by Jeong on 2017. 1. 27..
// Copyright © 2017년 Allkdic. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
let mainAppIdentifier = "kr.xoul.allkdic"
let runningApps = NSWorkspace.shared().runningApplications
let alreadyRunning = runningApps.filter { $0.bundleIdentifier == mainAppIdentifier }.count > 0
if !alreadyRunning {
let path = Bundle.main.bundlePath as NSString
var components = path.pathComponents
components.removeLast()
components.removeLast()
components.removeLast()
components.append("MacOS")
components.append("Allkdic")
let newPath = NSString.path(withComponents: components)
NSWorkspace.shared().launchApplication(newPath)
}
self.terminate()
}
func terminate() {
NSApp.terminate(nil)
}
}
| mit | dae63387ded05af2692df295502c21b0 | 23.333333 | 98 | 0.686888 | 4.731481 | false | false | false | false |
mercadopago/px-ios | ExampleSwift/ExampleSwift/Controllers/CustomCheckoutWithPostPaymentController.swift | 1 | 10141 | import UIKit
import MercadoPagoSDKV4
enum CustomCheckoutTestCase: String, CaseIterable {
case approved
case rejected
case error
var genericPayment: PXGenericPayment {
switch self {
case .approved:
return PXGenericPayment(
status: "approved",
statusDetail: "Pago aprobado desde procesadora custom!",
paymentId: "1234",
paymentMethodId: nil,
paymentMethodTypeId: nil
)
case .rejected:
return PXGenericPayment(
paymentStatus: .REJECTED,
statusDetail: "cc_amount_rate_limit_exceeded"
)
case .error:
fatalError("genericPayment no debe ser invocado para este caso")
}
}
}
final class CustomCheckoutWithPostPaymentController: UIViewController {
// MARK: - Outlets
@IBOutlet private var localeTextField: UITextField!
@IBOutlet private var publicKeyTextField: UITextField!
@IBOutlet private var preferenceIdTextField: UITextField!
@IBOutlet private var accessTokenTextField: UITextField!
@IBOutlet private var oneTapSwitch: UISwitch!
@IBOutlet private var testCasePicker: UIPickerView!
@IBOutlet private var customProcessorSwitch: UISwitch!
// MARK: - Variables
private var checkout: MercadoPagoCheckout?
// Collector Public Key
private var publicKey: String = "TEST-a463d259-b561-45fe-9dcc-0ce320d1a42f"
// Preference ID
private var preferenceId: String = "737302974-34e65c90-62ad-4b06-9f81-0aa08528ec53"
// Payer private key - Access Token
private var privateKey: String = "TEST-982391008451128-040514-b988271bf377ab11b0ace4f1ef338fe6-737303098"
// MARK: - Actions
@IBAction private func initCheckout(_ sender: Any) {
guard localeTextField.text?.count ?? 0 > 0,
publicKeyTextField.text?.count ?? 0 > 0,
preferenceIdTextField.text?.count ?? 0 > 0 else {
let alert = UIAlertController(
title: "Error",
message: "Complete los campos requeridos para continuar",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
present(alert, animated: true)
return
}
if customProcessorSwitch.isOn {
runMercadoPagoCheckoutWithLifecycleAndCustomProcessor()
} else {
runMercadoPagoCheckoutWithLifecycle()
}
}
@IBAction private func resetData(_ sender: Any) {
localeTextField.text = ""
publicKeyTextField.text = ""
preferenceIdTextField.text = ""
accessTokenTextField.text = ""
oneTapSwitch.setOn(true, animated: true)
}
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
let gradient = CAGradientLayer()
gradient.frame = view.bounds
let col1 = UIColor(red: 34.0 / 255.0, green: 211 / 255.0, blue: 198 / 255.0, alpha: 1)
let col2 = UIColor(red: 145 / 255.0, green: 72.0 / 255.0, blue: 203 / 255.0, alpha: 1)
gradient.colors = [col1.cgColor, col2.cgColor]
view.layer.insertSublayer(gradient, at: 0)
if let path = Bundle.main.path(forResource: "Info", ofType: "plist"),
let infoPlist = NSDictionary(contentsOfFile: path) {
// Initialize values from config
publicKeyTextField.text = infoPlist["PX_COLLECTOR_PUBLIC_KEY"] as? String
accessTokenTextField.text = infoPlist["PX_PAYER_PRIVATE_KEY"] as? String
}
localeTextField.text = "es-AR"
preferenceIdTextField.text = preferenceId
publicKeyTextField.text = publicKey
accessTokenTextField.text = privateKey
self.testCasePicker.delegate = self
self.testCasePicker.dataSource = self
}
// MARK: - Checkout Setup
private func runMercadoPagoCheckoutWithLifecycle() {
guard let publicKey = publicKeyTextField.text,
let preferenceId = preferenceIdTextField.text,
let language = localeTextField.text else {
return
}
let builder = MercadoPagoCheckoutBuilder(publicKey: publicKey, preferenceId: preferenceId).setLanguage(language)
if let privateKey = accessTokenTextField.text {
builder.setPrivateKey(key: privateKey)
}
if oneTapSwitch.isOn {
let advancedConfiguration = PXAdvancedConfiguration()
builder.setAdvancedConfiguration(config: advancedConfiguration)
}
let postPaymentConfig = PXPostPaymentConfiguration()
postPaymentConfig.postPaymentNotificationName = .init("example postpayment")
builder.setPostPaymentConfiguration(config: postPaymentConfig)
suscribeToPostPaymentNotification(postPaymentConfig: postPaymentConfig)
let checkout = MercadoPagoCheckout(builder: builder)
if let myNavigationController = navigationController {
checkout.start(navigationController: myNavigationController, lifeCycleProtocol: self)
}
}
private func runMercadoPagoCheckoutWithLifecycleAndCustomProcessor() {
// Create charge rules
let pxPaymentTypeChargeRules = [
PXPaymentTypeChargeRule.init(
paymentTypeId: PXPaymentTypes.CREDIT_CARD.rawValue,
amountCharge: 10.00
)
]
// Create an instance of your custom payment processor
let row = testCasePicker.selectedRow(inComponent: 0)
let testCase = CustomCheckoutTestCase.allCases[row]
let paymentProcessor: PXPaymentProcessor = CustomPostPaymentProcessor(with: testCase)
// Create a payment configuration instance using the recently created payment processor
let paymentConfiguration = PXPaymentConfiguration(paymentProcessor: paymentProcessor)
// Add charge rules
_ = paymentConfiguration.addChargeRules(charges: pxPaymentTypeChargeRules)
let checkoutPreference = PXCheckoutPreference(
siteId: "MLA",
payerEmail: "[email protected]",
items: [
PXItem(
title: "iPhone 12",
quantity: 1,
unitPrice: 150.0
)
]
)
// Add excluded methods
checkoutPreference.addExcludedPaymentMethod("master")
guard let publicKey = publicKeyTextField.text,
let privateKey = accessTokenTextField.text,
let language = localeTextField.text else {
return
}
let builder = MercadoPagoCheckoutBuilder(
publicKey: publicKey,
checkoutPreference: checkoutPreference,
paymentConfiguration: paymentConfiguration
)
builder.setLanguage(language)
builder.setPrivateKey(key: privateKey)
// Adding a post payment notification and suscribed it
let postPaymentConfig = PXPostPaymentConfiguration()
postPaymentConfig.postPaymentNotificationName = .init("example postpayment")
builder.setPostPaymentConfiguration(config: postPaymentConfig)
suscribeToPostPaymentNotification(postPaymentConfig: postPaymentConfig)
// Instantiate a configuration object
let configuration = PXAdvancedConfiguration()
// Add custom PXDynamicViewController component
configuration.dynamicViewControllersConfiguration = [CustomPXDynamicComponent()]
// Configure the builder object
builder.setAdvancedConfiguration(config: configuration)
// Set the payer private key
builder.setPrivateKey(key: privateKey)
// Create Checkout reference
checkout = MercadoPagoCheckout(builder: builder)
// Start with your navigation controller.
if let myNavigationController = navigationController {
checkout?.start(navigationController: myNavigationController, lifeCycleProtocol: self)
}
}
func suscribeToPostPaymentNotification(postPaymentConfig: PXPostPaymentConfiguration) {
MercadoPagoCheckout.NotificationCenter.SubscribeTo.postPaymentAction(
forName: postPaymentConfig.postPaymentNotificationName ?? .init("")
) { [weak self] _, resultBlock in
let postPayment = PostPaymentViewController(with: resultBlock)
self?.present(
UINavigationController(rootViewController: postPayment),
animated: true,
completion: nil
)
}
}
}
// MARK: Optional Lifecycle protocol implementation example.
extension CustomCheckoutWithPostPaymentController: PXLifeCycleProtocol {
func finishCheckout() -> ((PXResult?) -> Void)? {
return nil
}
func cancelCheckout() -> (() -> Void)? {
return nil
}
func changePaymentMethodTapped() -> (() -> Void)? {
return { () in
print("px - changePaymentMethodTapped")
}
}
}
extension CustomCheckoutWithPostPaymentController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.text = ""
}
func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> Bool {
return string != " "
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.text = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
extension CustomCheckoutWithPostPaymentController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return CustomCheckoutTestCase.allCases.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return CustomCheckoutTestCase.allCases[row].rawValue
}
}
| mit | c2bb5eb74eaa11b7cdfc9bea903f3d8c | 35.876364 | 120 | 0.65743 | 5.391281 | false | true | false | false |
epv44/EVTopTabBar | Example/EVTopTabBar/ViewController.swift | 1 | 2425 | //
// ViewController.swift
// EVTopTabBar
//
// Created by Eric Vennaro on 02/29/2016.
// Copyright (c) 2016 Eric Vennaro. All rights reserved.
//
import UIKit
import EVTopTabBar
class ViewController: UIViewController, EVTabBar {
var pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
var topTabBar: EVPageViewTopTabBar? {
didSet {
topTabBar?.fontColors = (selectedColor: UIColor.gray, unselectedColor: UIColor.lightGray)
topTabBar?.rightButtonText = "Events"
topTabBar?.leftButtonText = "Contacts"
topTabBar?.middleButtonText = "Tasks"
topTabBar?.middleRightButtonText = "Locations"
topTabBar?.labelFont = UIFont(name: "Helvetica", size: 11)!
topTabBar?.indicatorViewColor = UIColor.blue
topTabBar?.backgroundColor = UIColor.white
topTabBar?.delegate = self
}
}
var subviewControllers: [UIViewController] = []
var shadowView = UIImageView(image: #imageLiteral(resourceName: "filter-background-image"))
override func viewDidLoad() {
super.viewDidLoad()
topTabBar = EVPageViewTopTabBar(for: .four, withIndicatorStyle: .textWidth)
let firstVC = FirstViewController(nibName:"FirstViewController", bundle: nil)
let secondVC = SecondViewController(nibName:"SecondViewController", bundle: nil)
let thirdVC = ThirdViewController(nibName: "ThirdViewController", bundle: nil)
let fourthVC = FourthViewController(nibName: "FourthViewController", bundle: nil)
subviewControllers = [firstVC, secondVC, thirdVC, fourthVC]
setupPageView()
setupConstraints()
self.title = "EVTopTabBar"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//MARK: EVTabBarDataSource
extension ViewController: EVTabBarDelegate {
func willSelectViewControllerAtIndex(_ index: Int, direction: UIPageViewController.NavigationDirection) {
if index > subviewControllers.count {
pageController.setViewControllers([subviewControllers[subviewControllers.count - 1]], direction: direction, animated: true, completion: nil)
} else {
pageController.setViewControllers([subviewControllers[index]], direction: direction, animated: true, completion: nil)
}
}
}
| mit | 362d8ed0620641bd4556f55851ee7cb9 | 41.54386 | 152 | 0.695258 | 5.192719 | false | false | false | false |
b0oh/mal | swift/reader.swift | 1 | 7075 | //******************************************************************************
// MAL - reader
//******************************************************************************
import Foundation
let kSymbolWithMeta = MalSymbol(symbol: "with-meta")
let kSymbolDeref = MalSymbol(symbol: "deref")
let token_pattern =
"[[:space:],]*" + // Skip whitespace: a sequence of zero or more commas or [:space:]'s
"(" +
"~@" + // Literal "~@"
"|" +
"[\\[\\]{}()`'~^@]" + // Punctuation: Any one of []{}()`'~^@
"|" +
"\"(?:\\\\.|[^\\\\\"])*\"" + // Quoted string: characters other than \ or ", or any escaped characters
"|" +
";.*" + // Comment: semicolon followed by anything
"|" +
"[^[:space:]\\[\\]{}()`'\",;]*" + // Symbol, keyword, number, nil, true, false: any sequence of chars but [:space:] or []{}()`'",;
")"
let atom_pattern =
"(^;.*$)" + // Comment
"|" +
"(^-?[0-9]+$)" + // Integer
"|" +
"(^-?[0-9][0-9.]*$)" + // Float
"|" +
"(^nil$)" + // nil
"|" +
"(^true$)" + // true
"|" +
"(^false$)" + // false
"|" +
"(^\".*\"$)" + // String
"|" +
"(:.*)" + // Keyword
"|" +
"(^[^\"]*$)" // Symbol
var token_regex: NSRegularExpression = NSRegularExpression(pattern:token_pattern, options:.allZeros, error:nil)!
var atom_regex: NSRegularExpression = NSRegularExpression(pattern:atom_pattern, options:.allZeros, error:nil)!
class Reader {
init(_ tokens: [String]) {
self.tokens = tokens
self.index = 0
}
func next() -> String? {
let token = peek()
increment()
return token
}
func peek() -> String? {
if index < tokens.count {
return tokens[index]
}
return nil
}
private func increment() {
++index
}
private let tokens: [String]
private var index: Int
}
func tokenizer(s: String) -> [String] {
var tokens = [String]()
let range = NSMakeRange(0, s.utf16Count)
let matches = token_regex.matchesInString(s, options:.allZeros, range:range)
for match in matches as [NSTextCheckingResult] {
if match.range.length > 0 {
let token = (s as NSString).substringWithRange(match.rangeAtIndex(1))
tokens.append(token)
}
}
return tokens
}
private func have_match_at(match: NSTextCheckingResult, index:Int) -> Bool {
return Int64(match.rangeAtIndex(index).location) < LLONG_MAX
}
func read_atom(token: String) -> MalVal {
let range = NSMakeRange(0, token.utf16Count)
let matches = atom_regex.matchesInString(token, options:.allZeros, range:range)
for match in matches as [NSTextCheckingResult] {
if have_match_at(match, 1) { // Comment
return MalComment(comment: token)
} else if have_match_at(match, 2) { // Integer
if let value = NSNumberFormatter().numberFromString(token)?.longLongValue {
return MalInteger(value: value)
}
return MalError(message: "invalid integer: \(token)")
} else if have_match_at(match, 3) { // Float
if let value = NSNumberFormatter().numberFromString(token)?.doubleValue {
return MalFloat(value: value)
}
return MalError(message: "invalid float: \(token)")
} else if have_match_at(match, 4) { // nil
return MalNil()
} else if have_match_at(match, 5) { // true
return MalTrue()
} else if have_match_at(match, 6) { // false
return MalFalse()
} else if have_match_at(match, 7) { // String
return MalString(escaped: token)
} else if have_match_at(match, 8) { // Keyword
return MalKeyword(keyword: dropFirst(token))
} else if have_match_at(match, 9) { // Symbol
return MalSymbol(symbol: token)
}
}
return MalError(message: "Unknown token=\(token)")
}
func read_elements(r: Reader, open: String, close: String) -> ([MalVal]?, MalVal?) {
var list = [MalVal]()
while let token = r.peek() {
if token == close {
r.increment() // Consume the closing paren
return (list, nil)
} else {
let item = read_form(r)
if is_error(item) {
return (nil, item)
}
if item.type != .TypeComment {
list.append(item)
}
}
}
return (nil, MalError(message: "ran out of tokens -- possibly unbalanced ()'s"))
}
func read_list(r: Reader) -> MalVal {
let (list, err) = read_elements(r, "(", ")")
return err != nil ? err! : MalList(array: list!)
}
func read_vector(r: Reader) -> MalVal {
let (list, err) = read_elements(r, "[", "]")
return err != nil ? err! : MalVector(array: list!)
}
func read_hashmap(r: Reader) -> MalVal {
let (list, err) = read_elements(r, "{", "}")
return err != nil ? err! : MalHashMap(array: list!)
}
func common_quote(r: Reader, symbol: String) -> MalVal {
let next = read_form(r)
if is_error(next) { return next }
return MalList(objects: MalSymbol(symbol: symbol), next)
}
func read_form(r: Reader) -> MalVal {
if let token = r.next() {
switch token {
case "(":
return read_list(r)
case ")":
return MalError(message: "unexpected \")\"")
case "[":
return read_vector(r)
case "]":
return MalError(message: "unexpected \"]\"")
case "{":
return read_hashmap(r)
case "}":
return MalError(message: "unexpected \"}\"")
case "`":
return common_quote(r, "quasiquote")
case "'":
return common_quote(r, "quote")
case "~":
return common_quote(r, "unquote")
case "~@":
return common_quote(r, "splice-unquote")
case "^":
let meta = read_form(r)
if is_error(meta) { return meta }
let form = read_form(r)
if is_error(form) { return form }
return MalList(objects: kSymbolWithMeta, form, meta)
case "@":
let form = read_form(r)
if is_error(form) { return form }
return MalList(objects: kSymbolDeref, form)
default:
return read_atom(token)
}
}
return MalError(message: "ran out of tokens -- possibly unbalanced ()'s")
}
func read_str(s: String) -> MalVal {
let tokens = tokenizer(s)
let reader = Reader(tokens)
let obj = read_form(reader)
return obj
}
| mpl-2.0 | 07ee577383aedb996a2a4f9c6afe7e1c | 32.851675 | 140 | 0.488198 | 4.226404 | false | false | false | false |
Tonkpils/SpaceRun | SpaceRun/GameViewController.swift | 1 | 2107 | //
// GameViewController.swift
// SpaceRun
//
// Created by Leonardo Correa on 11/29/15.
// Copyright (c) 2015 Leonardo Correa. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
var easyMode : Bool?
override func viewDidLoad() {
super.viewDidLoad()
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
let blackScene = SKScene(size: skView.bounds.size)
blackScene.backgroundColor = UIColor.blackColor()
skView.presentScene(blackScene)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let skView = self.view as! SKView
let openingScene = OpeningScene(size: skView.bounds.size)
openingScene.scaleMode = .AspectFill
let transition = SKTransition.fadeWithDuration(1)
skView.presentScene(openingScene, transition: transition)
openingScene.sceneEndCallback = {
[unowned self] in
let scene : GameScene = GameScene(size: skView.bounds.size)
scene.endGameCallback = {
self.navigationController?.popViewControllerAnimated(true)
}
scene.easyMode = self.easyMode
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | 31ff42ca6ba98e4eff857130d7ef7d82 | 26.363636 | 90 | 0.641196 | 5.202469 | false | false | false | false |
PGSSoft/3DSnakeAR | 3DSnake/common classes/Mushroom.swift | 1 | 1151 | //
// Mushroom.swift
// 3DSnake
//
// Created by Michal Kowalski on 20.07.2017.
// Copyright © 2017 PGS Software. All rights reserved.
//
import SceneKit
final class Mushroom: SCNNode {
var mushroomNode: SCNNode?
// MARK: - Lifecycle
override init() {
super.init()
if let scene = SCNScene(named: "mushroom.scn"), let mushroomNode = scene.rootNode.childNode(withName: "mushroom", recursively: true) {
addChildNode(mushroomNode)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("not implemented")
}
//MARK - Animations
func runAppearAnimation() {
mushroomNode?.position.y = -1
removeAllActions()
removeAllParticleSystems()
scale = SCNVector3(0.1, 0.1, 0.1)
addParticleSystem(SCNParticleSystem(named: "mushroom-appear", inDirectory: nil)!)
let scaleAction = SCNAction.scale(to: 1.0, duration: 1.0)
let removeParticle = SCNAction.run { _ in
self.removeAllParticleSystems()
}
let sequence = SCNAction.sequence([scaleAction, removeParticle])
runAction(sequence)
}
}
| mit | b5458109e13102ad78dc8a95b653707e | 27.04878 | 142 | 0.633043 | 4.121864 | false | false | false | false |
QuiverApps/PiPass-iOS | PiPass-iOS/GetPiPassConfig.swift | 1 | 1162 | //
// GetPiPassConfig.swift
// PiPass-iOS
//
// Created by Jeremy Roberts on 11/22/15.
// Copyright © 2015 Jeremy Roberts. All rights reserved.
//
import Alamofire
import Mantle
public class GetPiPassConfig: NSObject {
public static func doApiCall(rpiAddress:String, success:(PiPassConfig) -> Void, failure:() -> Void) {
let cache = Int(arc4random_uniform(999) + 1)
let address = String(format: Constants.JsonEnpoints.PIPASS_CONFIG, arguments: [rpiAddress,cache])
Alamofire.request(.GET, address)
.responseJSON { response in
var piPassConfig:PiPassConfig = PiPassConfig()
if(response.result.isSuccess) {
if let responseValue = response.result.value {
let JSON = responseValue as! [NSObject : AnyObject]
piPassConfig = PiPassConfig.deserializeObjectFromJSON(JSON) as! PiPassConfig
success(piPassConfig)
}
} else {
failure()
}
}
}
} | mit | c79b373f25988c6e4b0898b397ba63f8 | 32.2 | 105 | 0.546081 | 4.878151 | false | true | false | false |
0xfeedface1993/Xs8-Safari-Block-Extension-Mac | Sex8BlockExtension/Sex8BlockExtension/Webservice/Webservice.swift | 1 | 5962 | //
// Webservice.swift
// S8Blocker
//
// Created by virus1993 on 2017/10/12.
// Copyright © 2017年 ascp. All rights reserved.
//
import AppKit
enum WebserviceError : Error {
case badURL(message: String)
case badSendJson(message: String)
case badResponseJson(message: String)
case emptyResponseData(message: String)
}
enum WebServiceMethod : String {
case post = "POST"
case get = "GET"
}
enum WebserviceBaseURL : String {
case main = "http://14d8856q96.imwork.net"
case aliyun = "http://120.78.89.159/api"
case debug = "http://127.0.0.1"
func url(method: WebserviceMethodPath) -> URL {
return URL(string: self.rawValue + method.rawValue)!
}
}
enum WebserviceMethodPath : String {
case registerDevice = "/api/v1/addDevice"
case findDevice = "/api/v1/findDevice"
case push = "/api/v1/pushAll"
}
class WebserviceCaller<T: Codable, X: Codable> {
var baseURL : WebserviceBaseURL
var way : WebServiceMethod
var method : WebserviceMethodPath
var paras : X?
var rawData : Data?
var execute : ((T?, Error?, ErrorResponse?)->())?
init(url: WebserviceBaseURL, way: WebServiceMethod, method: WebserviceMethodPath) {
self.baseURL = url
self.way = way
self.method = method
}
}
class Webservice {
static let share = Webservice()
var runningTask = [URLSessionDataTask]()
private var session : URLSession = {
let configuration = URLSessionConfiguration.default
return URLSession(configuration: configuration)
}()
func read<P : Codable, X: Codable>(caller : WebserviceCaller<P, X>) throws {
let responseHandler : (Data?, URLResponse?, Error?) -> Swift.Void = { (data, response, err) in
if let e = err {
caller.execute?(nil, e, nil)
return
}
let jsonDecoder = JSONDecoder()
guard let good = data else {
caller.execute?(nil, WebserviceError.badResponseJson(message: "返回数据为空"), nil)
return
}
if let errorResult = try? jsonDecoder.decode(ErrorResponse.self, from: good) {
caller.execute?(nil, nil, errorResult)
return
}
do {
let json = try jsonDecoder.decode(P.self, from: good)
caller.execute?(json, nil, nil)
} catch {
caller.execute?(nil, WebserviceError.badResponseJson(message: "错误的解析对象!请检查返回的JSON字符串是否符合解析的对象类型。\n\(String(data: good, encoding: .utf8) ?? "empty")"), nil)
}
}
func handler(task: URLSessionDataTask) -> ((Data?, URLResponse?, Error?) -> Swift.Void) {
return { (data, response, err) in
if let index = self.runningTask.enumerated().map({ return $0.offset }).first {
self.runningTask.remove(at: index)
}
if let e = err {
caller.execute?(nil, e, nil)
return
}
let jsonDecoder = JSONDecoder()
guard let good = data else {
caller.execute?(nil, WebserviceError.badResponseJson(message: "返回数据为空"), nil)
return
}
if let errorResult = try? jsonDecoder.decode(ErrorResponse.self, from: good) {
caller.execute?(nil, nil, errorResult)
return
}
do {
let json = try jsonDecoder.decode(P.self, from: good)
caller.execute?(json, nil, nil)
} catch {
caller.execute?(nil, WebserviceError.badResponseJson(message: "错误的解析对象!请检查返回的JSON字符串是否符合解析的对象类型。\n\(String(data: good, encoding: .utf8) ?? "empty")"), nil)
}
}
}
switch caller.way {
case .get:
let urlString = caller.baseURL.rawValue.appending("?method=\(caller.method.rawValue)")
if let url = URL(string: urlString) {
var request = URLRequest(url: url)
request.httpMethod = caller.way.rawValue
let task = session.dataTask(with: request, completionHandler: responseHandler)
task.resume()
runningTask.append(task)
return
}
throw WebserviceError.badURL(message: "错误的url:" + urlString)
case .post:
let urlString = caller.baseURL.url(method: caller.method).absoluteString
do {
var data : Data?
if let paras = caller.paras {
let encoder = JSONEncoder()
data = try? encoder.encode(paras)
} else if let raw = caller.rawData {
data = raw
}
if let url = URL(string: urlString) {
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = data
request.httpMethod = caller.way.rawValue
let task = session.dataTask(with: request, completionHandler: responseHandler)
task.resume()
runningTask.append(task)
return
}
throw WebserviceError.badURL(message: "错误的url:" + urlString)
} catch {
caller.execute?(nil, error, nil)
return
}
}
}
func cancelAllTask() {
runningTask.forEach { (task) in
task.cancel()
}
runningTask.removeAll()
}
}
| apache-2.0 | bdd773bf02d4031bf5bc08a3a05d7e41 | 35.496855 | 175 | 0.53817 | 4.691188 | false | false | false | false |
darwin/textyourmom | TextYourMom/MapController.swift | 1 | 10755 | import UIKit
import MapKit
struct DebugLocation {
var description : String = ""
var latitude: Double = 0.0
var longitude: Double = 0.0
init(_ description: String, _ latitude: Double, _ longitude: Double) {
self.description = description
self.latitude = latitude
self.longitude = longitude
}
}
let debugLocations = [
DebugLocation("DONT OVERRIDE", 0.0, 0.0), // #0
DebugLocation("x no-mans-land", 48, 14),
DebugLocation("x surf office Las Palmas",28.1286,-15.4452),
DebugLocation("x surf office Santa Cruz",36.9624,-122.0310),
DebugLocation("SFO-inner-Milbrae-inner",37.6145,-122.3776),
DebugLocation("SFO-outer-Milbrae-outer",37.6231,-122.4166),
DebugLocation("SFO-outer-Milbrae-inner",37.6008,-122.4067),
DebugLocation("SFO-inner-Milbrae-outer",37.6356,-122.3677),
DebugLocation("SFO-outer",37.6547,-122.3687),
DebugLocation("Milbrae-outer",37.5679,-122.3944),
DebugLocation("Ceske Budejovice",48.946381,14.427464),
DebugLocation("Caslav",49.939653,15.381808),
DebugLocation("Hradec Kralove",50.2532,15.845228),
DebugLocation("Horovice",49.848111,13.893506),
DebugLocation("Kbely",50.121367,14.543642),
DebugLocation("Kunovice",49.029444,17.439722),
DebugLocation("Karlovy Vary",50.202978,12.914983),
DebugLocation("Plzen Line",49.675172,13.274617)
]
class AirportOverlay: MKCircle {
var type : AirportPerimeter = .Inner
func setupRenderer(renderer: MKCircleRenderer) {
let innerColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.05)
let outerColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.05)
if type == .Inner {
renderer.fillColor = innerColor
renderer.strokeColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.1)
renderer.lineWidth = 1
} else {
renderer.fillColor = outerColor
}
}
}
class FakeLocationAnnotation : MKPointAnnotation {
}
class CenterLocationAnnotation : MKPointAnnotation {
}
class MapController: BaseViewController {
@IBOutlet weak var locationPicker: UIPickerView!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var centerLabel: UILabel!
var overlaysDefined = false
var manualDragging = false
var fakeLocationAnnotation = FakeLocationAnnotation()
var centerLocationAnnotation = CenterLocationAnnotation()
override func viewDidLoad() {
super.viewDidLoad()
locationPicker.selectRow(overrideLocation, inComponent:0, animated:false)
// last known location
let londonLocation = CLLocationCoordinate2D(latitude: lastLatitude, longitude: lastLongitude)
// this is here just to prevent slow map loading because of extreme zoom-out
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: londonLocation, span: span)
mapView.setRegion(region, animated: true)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
mapController = self
manualDragging = false
mapView.removeAnnotation(centerLocationAnnotation)
defineAirportOverlays(masterController.airportsProvider)
}
override func viewDidDisappear(animated: Bool) {
mapController = nil
super.viewDidDisappear(animated)
}
func defineAirportOverlays(provider:AirportsProvider) {
if overlaysDefined {
return
}
func buildAirportOverlay(airport: Airport, perimeter: AirportPerimeter) -> AirportOverlay {
let center = CLLocationCoordinate2D(latitude:airport.latitude, longitude:airport.longitude)
let radius = CLLocationDistance(perimeter==AirportPerimeter.Inner ? innerAirportPerimeterDistance : outerAirportPerimeterDistance)
var overlay = AirportOverlay(centerCoordinate: center, radius: radius)
overlay.type = perimeter
return overlay
}
let airports = provider.airports
var overlays : [AirportOverlay] = []
var annotations : [MKPointAnnotation] = []
for airport in airports {
overlays.append(buildAirportOverlay(airport, .Outer))
overlays.append(buildAirportOverlay(airport, .Inner))
let annotation = MKPointAnnotation()
annotation.setCoordinate(CLLocationCoordinate2D(latitude:airport.latitude, longitude:airport.longitude))
annotation.title = airport.name
annotations.append(annotation)
}
mapView.addOverlays(overlays)
mapView.addAnnotations(annotations)
overlaysDefined = true
}
func updateLocation(latitude: Double, _ longitude:Double) {
if manualDragging {
return
}
let location = CLLocationCoordinate2D(latitude: latitude, longitude:longitude)
mapView.setCenterCoordinate(location, animated: true)
}
@IBAction func doApplyLocationOverride() {
manualDragging = false
mapView.removeAnnotation(centerLocationAnnotation)
overrideLocation = locationPicker.selectedRowInComponent(0)
let newDebugLocation = debugLocations[overrideLocation]
if overrideLocation > 0 {
log("manual override of location to \(newDebugLocation.description)")
masterController.airportsWatcher.emitFakeUpdateLocation(newDebugLocation.latitude, newDebugLocation.longitude)
fakeLocationAnnotation.setCoordinate(CLLocationCoordinate2D(latitude:newDebugLocation.latitude, longitude:newDebugLocation.longitude))
mapView.addAnnotation(fakeLocationAnnotation)
} else {
log("stopped overriding location")
mapView.removeAnnotation(fakeLocationAnnotation)
}
}
}
// MARK: MKMapViewDelegate
extension MapController : MKMapViewDelegate{
// http://stackoverflow.com/a/26002176/84283
func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view = (mapView.subviews[0] as? UIView)
let recognizers = view!.gestureRecognizers! as [AnyObject]
for recognizer in recognizers {
if recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended {
return true;
}
}
return false
}
func mapView(mapView: MKMapView!, regionWillChangeAnimated animated: Bool) {
if mapViewRegionDidChangeFromUserInteraction() {
manualDragging = true
mapView.addAnnotation(centerLocationAnnotation)
log("started manual dragging")
}
}
func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) {
var center = mapView.centerCoordinate
centerLocationAnnotation.setCoordinate(center)
let fmt = ".4"
centerLabel.text = "\(center.latitude.format(fmt)), \(center.longitude.format(fmt))"
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if let airportOverlay = overlay as? AirportOverlay {
var circleRenderer = MKCircleRenderer(overlay: airportOverlay)
airportOverlay.setupRenderer(circleRenderer)
return circleRenderer
}
return nil
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKUserLocation {
return nil // map view should draw "blue dot" for user location
}
if annotation is FakeLocationAnnotation {
let reuseId = "fake-location"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "Crosshairs")
annotationView.centerOffset = CGPointMake(0, 0)
annotationView.calloutOffset = CGPointMake(0, 0)
}
annotationView.annotation = annotation
return annotationView
}
if annotation is CenterLocationAnnotation {
let reuseId = "center-location"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView.canShowCallout = false
annotationView.image = UIImage(named: "MagentaDot")
annotationView.centerOffset = CGPointMake(0, 0)
annotationView.calloutOffset = CGPointMake(0, 0)
}
annotationView.annotation = annotation
return annotationView
}
let reuseId = "airport"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "DotCircle")
annotationView.centerOffset = CGPointMake(0, 0)
annotationView.calloutOffset = CGPointMake(0, 0)
}
annotationView.annotation = annotation
return annotationView
}
}
extension MapController : UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return debugLocations.count
}
}
extension MapController : UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return debugLocations[row].description
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let text = debugLocations[row].description
var attrString = NSMutableAttributedString(string: text)
var range = NSMakeRange(0, attrString.length)
attrString.beginEditing()
attrString.addAttribute(NSForegroundColorAttributeName, value:UIColor.blueColor(), range:range)
attrString.endEditing()
return attrString
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
doApplyLocationOverride()
}
}
| mit | d32bd4ee6a0d4c2fbf2b258b81d41d8a | 38.686347 | 146 | 0.67206 | 5.198163 | false | false | false | false |
banDedo/BDModules | NavigationDrawerViewController/NavigationDrawerViewController.swift | 1 | 17526 | //
// NavigationDrawerViewController.swift
// Harness
//
// Created by Patrick Hogan on 3/17/15.
// Copyright (c) 2015 bandedo. All rights reserved.
//
import Snap
import UIKit
private let kNavigationDrawerDefaultRevealOffset = CGFloat(50.0)
public class NavigationDrawerViewController: LifecycleViewController, UIGestureRecognizerDelegate {
// MARK:- Enumerated Types
public enum Orientation {
case Default
case PartialRevealLeft
case RevealLeft
}
private enum ViewControllerIndex: Int {
case Left = 0
case Center = 1
static var count: Int {
var max: Int = 0
while let _ = self(rawValue: ++max) {}
return max
}
}
// MARK:- Properties
public var leftDrawerPartialRevealHorizontalOffset = CGFloat(kNavigationDrawerDefaultRevealOffset) {
didSet {
if !isDragging {
switch orientation {
case .PartialRevealLeft:
updateViewConstraints()
break
case .Default, .RevealLeft:
break
}
}
}
}
private(set) public var centerViewController: UIViewController?
private(set) public var leftDrawerViewController: UIViewController?
private(set) public lazy var statusBarBlockerView: UIView = {
let statusBarBlockerView = UIView(frame: CGRectZero)
statusBarBlockerView.backgroundColor = UIColor.blackColor()
return statusBarBlockerView
}()
public var animationDuration = NSTimeInterval(0.25)
public var shortAnimationDuration = NSTimeInterval(0.15)
public var minimumLeftContainerOffset = CGFloat(-kNavigationDrawerDefaultRevealOffset)
private(set) public var orientation = Orientation.Default
// MARK:- View lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
for containerView in containerViews {
view.addSubview(containerView)
}
view.addSubview(statusBarBlockerView)
leftContainerView.snp_makeConstraints() { make in
make.top.and.bottom.equalTo(UIEdgeInsetsZero);
make.width.equalTo(self.view);
}
centerContainerView.snp_makeConstraints() { make in
make.top.and.bottom.equalTo(UIEdgeInsetsZero);
make.width.equalTo(self.view);
}
blockingView.snp_makeConstraints() { make in
make.edges.equalTo(UIEdgeInsetsZero)
}
statusBarBlockerView.snp_makeConstraints() { make in
make.top.equalTo(self.view)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
make.height.equalTo(UIApplication.sharedApplication().statusBarFrame.size.height)
}
}
// MARK:- Layout
public override func updateViewConstraints() {
centerContainerViewHorizontalOffsetConstraint?.uninstall()
leftContainerViewHorizontalOffsetConstraint?.uninstall()
centerContainerView.snp_makeConstraints() { make in
self.centerContainerViewHorizontalOffsetConstraint = {
if self.isDragging {
var currentHorizontalOffset = self.currentHorizontalOffset
if fabs(self.currentPanDelta!.x) > fabs(self.currentPanDelta!.y) {
currentHorizontalOffset -= self.currentPanDelta!.x
currentHorizontalOffset = max(0.0, currentHorizontalOffset)
currentHorizontalOffset = min(self.view.frame.size.width, currentHorizontalOffset)
}
return make.centerX.equalTo(self.view.snp_centerX).with.offset(currentHorizontalOffset)
} else {
switch self.orientation {
case .Default:
return make.left.equalTo(0.0)
case .PartialRevealLeft:
return make.left.equalTo(self.view.snp_right).with.offset(-self.leftDrawerPartialRevealHorizontalOffset)
case .RevealLeft:
return make.left.equalTo(self.view.snp_right)
}
}
}()
}
leftContainerView.snp_makeConstraints() { make in
self.leftContainerViewHorizontalOffsetConstraint = {
if self.isDragging {
var currentLeftContainerOffset = (1.0 - self.normalizedCenterViewOffset) * self.minimumLeftContainerOffset
currentLeftContainerOffset = max(currentLeftContainerOffset, self.minimumLeftContainerOffset)
currentLeftContainerOffset = min(currentLeftContainerOffset, 0.0)
return make.left.equalTo(self.view.snp_left).with.offset(currentLeftContainerOffset)
} else {
switch self.orientation {
case .Default:
return make.left.equalTo(self.minimumLeftContainerOffset)
case .PartialRevealLeft, .RevealLeft:
return make.left.equalTo(0.0)
}
}
}()
}
super.updateViewConstraints()
}
public class func requiresConstraintBasedLayout() -> Bool {
return true
}
// MARK: Status Bar
func updateStatusBarBlockerView() {
statusBarBlockerView.alpha = min(normalizedCenterViewOffset, 1.0)
setNeedsStatusBarAppearanceUpdate()
}
// MARK: Blocking View
func updateBlockingView() {
switch orientation {
case .Default:
blockingView.hidden = true
break
case .PartialRevealLeft, .RevealLeft:
blockingView.hidden = false
break
}
}
// MARK:- Child View Controllers
public func replaceCenterViewController(viewController: UIViewController) {
replaceCenterViewController({ return viewController })
}
public func replaceCenterViewController(
handler: Void -> UIViewController,
animated: Bool = false,
completion: Bool -> Void = { $0 }) {
view.userInteractionEnabled = false
let child = centerViewController
var completionHandler: (Bool -> Void) = { $0 }
let replacementHandler: Void -> Void = { [weak self] in
if let strongSelf = self {
var viewController = handler()
child?.willMoveToParentViewController(nil)
strongSelf.addChildViewController(viewController)
strongSelf.centerContainerView.insertSubview(
viewController.view,
belowSubview:child?.view ?? strongSelf.blockingView
)
viewController.view.snp_makeConstraints() { make in
make.edges.equalTo(strongSelf.centerContainerView)
}
strongSelf.centerContainerView.layoutIfNeeded()
completionHandler = { [weak self] finished in
if let strongSelf = self {
strongSelf.view.userInteractionEnabled = true
strongSelf.blockingView.hidden = true
child?.removeFromParentViewController()
viewController.didMoveToParentViewController(strongSelf)
strongSelf.centerViewController = viewController
completion(finished)
}
}
}
}
if !animated {
replacementHandler()
child?.view.removeFromSuperview()
completionHandler(true)
updateViewConstraints()
view.layoutIfNeeded()
updateStatusBarBlockerView()
} else {
view.layoutIfNeeded()
UIView.animate(
true,
duration: shortAnimationDuration,
animations: {
self.orientation = .RevealLeft
self.updateViewConstraints()
self.view.layoutIfNeeded()
}) { [weak self] finished in
if let strongSelf = self {
let minimumDelay = dispatch_time(DISPATCH_TIME_NOW, Int64(strongSelf.shortAnimationDuration * Double(NSEC_PER_SEC)))
replacementHandler()
child?.view.removeFromSuperview()
dispatch_after(minimumDelay, dispatch_get_main_queue()) { [weak self] in
if let strongSelf = self {
UIView.animate(
true,
duration: strongSelf.animationDuration,
animations: { [weak self] in
strongSelf.orientation = .Default
strongSelf.updateViewConstraints()
strongSelf.view.layoutIfNeeded()
strongSelf.updateStatusBarBlockerView()
},
completion: completionHandler
)
}
}
}
}
}
}
public func replaceLeftViewController(viewController: UIViewController) {
view.userInteractionEnabled = false
let child = leftDrawerViewController
child?.willMoveToParentViewController(nil)
child?.view.removeFromSuperview()
addChildViewController(viewController)
leftContainerView.addSubview(viewController.view)
viewController.view.snp_makeConstraints() { make in
make.edges.equalTo(UIEdgeInsetsZero)
}
child?.removeFromParentViewController()
viewController.didMoveToParentViewController(self)
leftDrawerViewController = viewController
updateViewConstraints()
view.layoutIfNeeded()
updateStatusBarBlockerView()
}
// MARK:- Anchor Drawer
public func anchorDrawer(
orientation: Orientation,
animated: Bool,
completion: Bool -> Void = { finished in }) {
let animations: Void -> Void = {
self.orientation = orientation
self.updateViewConstraints()
self.view.layoutIfNeeded()
self.updateStatusBarBlockerView()
}
let completionHandler: Bool -> Void = { [weak self] finished in
if let strongSelf = self {
strongSelf.updateBlockingView()
completion(finished)
}
}
UIView.animate(
animated,
duration: animationDuration,
animations: animations,
completion: completionHandler
)
}
// MARK:- Action Handlers
public func handlePan(sender: UIPanGestureRecognizer) {
let location = sender.locationInView(view)
switch sender.state {
case UIGestureRecognizerState.Began:
currentPanDelta = CGPointZero
currentTouchPoint = location
isDragging = true
break
case UIGestureRecognizerState.Changed:
currentPanDelta = CGPointMake(
currentTouchPoint!.x - location.x,
currentTouchPoint!.y - location.y
)
currentTouchPoint = location
updateViewConstraints()
view.layoutIfNeeded()
break
case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled:
isDragging = false
let thresholdSpeed = CGFloat(100.0)
let currentVelocity = sender.velocityInView(view)
let orientation: Orientation
if fabs(currentVelocity.x) > thresholdSpeed {
if currentVelocity.x > 0.0 {
orientation = .PartialRevealLeft
} else {
orientation = .Default
}
} else {
if currentHorizontalOffset > leftDrawerPartialRevealHorizontalOffset {
orientation = .PartialRevealLeft
} else {
orientation = .Default
}
}
anchorDrawer(orientation, animated: true)
break
case UIGestureRecognizerState.Failed, UIGestureRecognizerState.Possible:
break
}
updateStatusBarBlockerView()
}
public func handleTap(sender: UITapGestureRecognizer) {
anchorDrawer(.Default, animated: true)
}
// MARK:- Private Properties
private lazy var panGestureRecognizer: UIPanGestureRecognizer = {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
panGestureRecognizer.delegate = self
return panGestureRecognizer
}()
private lazy var blockingView: UIView = {
let blockingView = UIView(frame: CGRectZero)
blockingView.backgroundColor = UIColor.clearColor()
blockingView.hidden = true
blockingView.addGestureRecognizer({
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
tapGestureRecognizer.numberOfTapsRequired = 1
tapGestureRecognizer.numberOfTouchesRequired = 1
tapGestureRecognizer.delegate = self
tapGestureRecognizer.requireGestureRecognizerToFail(self.panGestureRecognizer)
return tapGestureRecognizer
}())
return blockingView
}()
private lazy var containerViews: [ UIView ] = {
var containerViews = [ UIView ]()
for i in 0..<ViewControllerIndex.count {
let view = UIView(frame: CGRectZero)
view.backgroundColor = UIColor.blackColor()
view.opaque = true
let viewControllerIndex = ViewControllerIndex(rawValue: i)!
switch viewControllerIndex {
case .Left:
break
case .Center:
view.addGestureRecognizer(self.panGestureRecognizer)
view.addSubview(self.blockingView)
break
}
containerViews.append(view)
}
return containerViews
}()
private lazy var leftContainerView: UIView = {
return self.containerViews[ViewControllerIndex.Left.rawValue]
}()
private var centerContainerView: UIView {
return self.containerViews[ViewControllerIndex.Center.rawValue]
}
public func gestureRecognizer(
gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer.self) {
// Disable if vertical scrolling is desired.
let velocity = (otherGestureRecognizer as! UIPanGestureRecognizer).velocityInView(view)
if (fabs(velocity.y) > fabs(velocity.x)) {
return false
}
}
// If view is a horizontal scroller, don't allow panning unless at the far left of the scroll view.
if let view = otherGestureRecognizer.view where view.isKindOfClass(UIScrollView.self) {
let scrollView = otherGestureRecognizer.view as! UIScrollView
if (scrollView.contentOffset.x >= 1) {
return false
}
}
return true
}
// MARK:- Panning Properties
private var isDragging = false
private var currentTouchPoint: CGPoint?
private var currentPanDelta: CGPoint?
private var centerContainerViewHorizontalOffsetConstraint: Constraint?
private var leftContainerViewHorizontalOffsetConstraint: Constraint?
private var currentHorizontalOffset: CGFloat {
return CGRectGetMinX(centerContainerView.frame)
}
private var normalizedCenterViewOffset: CGFloat {
var normalizedCenterViewOffset = self.currentHorizontalOffset
normalizedCenterViewOffset /= (view.frame.size.width - self.leftDrawerPartialRevealHorizontalOffset)
return normalizedCenterViewOffset
}
}
| apache-2.0 | 6a79cec81347124aacf5c58fd8e12e7f | 35.974684 | 144 | 0.554148 | 6.864865 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/NCLoyaltyStoreOffersViewController.swift | 2 | 6329 | //
// NCLoyaltyStoreOffersViewController.swift
// Neocom
//
// Created by Artem Shimanski on 12.10.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import EVEAPI
import CoreData
import Futures
class NCLoyaltyStoreCategoryRow: TreeRow {
let categoryID: Int
lazy var category: NCDBInvCategory? = {
return NCDatabase.sharedDatabase?.invCategories[categoryID]
}()
init(categoryID: Int, route: Route) {
self.categoryID = categoryID
super.init(prototype: Prototype.NCDefaultTableViewCell.compact, route: route)
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = category?.categoryName
cell.iconView?.image = category?.icon?.image?.image ?? NCDBEveIcon.defaultCategory.image?.image
cell.accessoryType = .disclosureIndicator
}
}
class NCLoyaltyStoreGroupRow: TreeRow {
let groupID: Int
lazy var group: NCDBInvGroup? = {
return NCDatabase.sharedDatabase?.invGroups[groupID]
}()
init(groupID: Int, route: Route) {
self.groupID = groupID
super.init(prototype: Prototype.NCDefaultTableViewCell.compact, route: route)
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = group?.groupName
cell.iconView?.image = group?.icon?.image?.image ?? NCDBEveIcon.defaultGroup.image?.image
cell.accessoryType = .disclosureIndicator
}
}
class NCLoyaltyStoreOfferRow: TreeRow {
let offer: ESI.Loyalty.Offer
lazy var subtitle: String = {
var components = [String]()
if offer.lpCost > 0 {
components.append(NCUnitFormatter.localizedString(from: offer.lpCost, unit: .custom(NSLocalizedString("LP", comment: ""), false), style: .full))
}
if offer.iskCost > 0 {
components.append(NCUnitFormatter.localizedString(from: offer.lpCost, unit: .isk, style: .full))
}
if !offer.requiredItems.isEmpty {
// offer.requiredItems.flat
components.append(String(format: NSLocalizedString("%d items", comment: ""), offer.requiredItems.count))
}
return components.joined(separator: ", ")
}()
lazy var type: NCDBInvType? = {
return NCDatabase.sharedDatabase?.invTypes[self.offer.typeID]
}()
init(offer: ESI.Loyalty.Offer) {
self.offer = offer
super.init(prototype: Prototype.NCDefaultTableViewCell.default, route: Router.Database.TypeInfo(offer.typeID))
}
override func configure(cell: UITableViewCell) {
super.configure(cell: cell)
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = type?.typeName
cell.iconView?.image = type?.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image
cell.subtitleLabel?.text = subtitle
cell.accessoryType = .disclosureIndicator
}
}
class NCLoyaltyStoreOffersViewController: NCTreeViewController {
var loyaltyPoints: ESI.Loyalty.Point?
enum Filter {
case category(Int)
case group(Int)
}
var filter: Filter?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register([Prototype.NCDefaultTableViewCell.default,
Prototype.NCDefaultTableViewCell.compact,
Prototype.NCHeaderTableViewCell.default])
let label = NCNavigationItemTitleLabel(frame: CGRect(origin: .zero, size: .zero))
let title: String = {
switch filter {
case let .category(categoryID)?:
return NCDatabase.sharedDatabase?.invCategories[categoryID]?.categoryName
case let .group(groupID)?:
return NCDatabase.sharedDatabase?.invGroups[groupID]?.groupName
default:
return nil
}
}() ?? NSLocalizedString("Offers", comment: "")
label.set(title: title, subtitle: NCUnitFormatter.localizedString(from: loyaltyPoints?.loyaltyPoints ?? 0, unit: .custom("LP", false), style: .full))
navigationItem.titleView = label
}
override func load(cachePolicy: URLRequest.CachePolicy) -> Future<[NCCacheRecord]> {
guard let loyaltyPoints = loyaltyPoints, filter == nil && offers == nil else {
return .init([])
}
return dataManager.loyaltyStoreOffers(corporationID: Int64(loyaltyPoints.corporationID)).then(on: .main) { result -> [NCCacheRecord] in
self.offers = result
return [result.cacheRecord(in: NCCache.sharedCache!.viewContext)]
}
}
override func content() -> Future<TreeNode?> {
let loyaltyPoints = self.loyaltyPoints
let offers = self.offers
return DispatchQueue.global(qos: .utility).async { () -> TreeNode? in
guard let loyaltyPoints = loyaltyPoints, let offers = offers, let value = offers.value else {throw NCTreeViewControllerError.noResult}
return try NCDatabase.sharedDatabase!.performTaskAndWait { (managedObjectContext) in
let invTypes = NCDBInvType.invTypes(managedObjectContext: managedObjectContext)
// var map: [Int: [NCLoyaltyStoreOfferRow]] = [:]
let sections: [TreeNode]
switch self.filter {
case let .category(categoryID)?:
let categoryID = Int32(categoryID)
let groups = Set(value.compactMap {invTypes[$0.typeID]?.group}).filter {$0.category?.categoryID == categoryID}
sections = groups.sorted {($0.groupName ?? "") < ($1.groupName ?? "")}.map {NCLoyaltyStoreGroupRow(groupID: Int($0.groupID), route: Router.Character.LoyaltyStoreOffers(loyaltyPoints: loyaltyPoints, filter: .group(Int($0.groupID)), offers: offers))}
case let .group(groupID)?:
let groupID = Int32(groupID)
let types = value.compactMap { i -> (NCDBInvType, ESI.Loyalty.Offer)? in
guard let type = invTypes[i.typeID], type.group?.groupID == groupID else {return nil}
return (type, i)
}
sections = types.sorted {($0.0.typeName ?? "") < ($1.0.typeName ?? "")}.map {NCLoyaltyStoreOfferRow(offer: $0.1)}
default:
let categories = Set(value.compactMap {invTypes[$0.typeID]?.group?.category})
sections = categories.sorted {($0.categoryName ?? "") < ($1.categoryName ?? "")}.map {NCLoyaltyStoreCategoryRow(categoryID: Int($0.categoryID), route: Router.Character.LoyaltyStoreOffers(loyaltyPoints: loyaltyPoints, filter: .category(Int($0.categoryID)), offers: offers))}
}
guard !sections.isEmpty else {throw NCTreeViewControllerError.noResult}
return RootNode(sections)
}
}
}
//MARK: - NCRefreshable
var offers: CachedValue<[ESI.Loyalty.Offer]>?
}
| lgpl-2.1 | b8f1fb68581bf981428f8556debee3dc | 33.769231 | 278 | 0.719027 | 3.987398 | false | false | false | false |
frootloops/swift | test/Sema/diag_get_vs_set_subscripts.swift | 4 | 660 | // RUN: %target-typecheck-verify-swift
enum Key: Int {
case aKey
case anotherKey // expected-note {{did you mean 'anotherKey'?}}
}
class sr6175 {
var dict: [Key: String] = [:]
func what() -> Void {
dict[.notAKey] = "something" // expected-error {{type 'Key' has no member 'notAKey'}}
}
subscript(i: Int) -> Int {
return i*i
}
subscript(j: Double) -> Double {
get { return j*j }
set {}
}
}
let s = sr6175()
let one: Int = 1
// Should choose the settable subscript to find a problem with, not the get-only subscript
s[one] = 2.5 // expected-error {{cannot convert value of type 'Int' to expected argument type 'Double'}}
| apache-2.0 | 8e4eb11337595f24c1152944ec7fe200 | 24.384615 | 104 | 0.630303 | 3.316583 | false | false | false | false |
cplaverty/KeitaiWaniKani | AlliCrab/ViewControllers/WebViewController.swift | 1 | 20275 | //
// WebViewController.swift
// AlliCrab
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
import OnePasswordExtension
import os
import UIKit
import WaniKaniKit
import WebKit
protocol WebViewControllerDelegate: class {
func webViewControllerDidFinish(_ controller: WebViewController)
}
class WebViewController: UIViewController {
class func wrapped(url: URL, configBlock: ((WebViewController) -> Void)? = nil) -> UINavigationController {
let webViewController = self.init(url: url)
configBlock?(webViewController)
let nc = UINavigationController(rootViewController: webViewController)
nc.hidesBarsOnSwipe = true
nc.hidesBarsWhenVerticallyCompact = true
return nc
}
// MARK: - Properties
weak var delegate: WebViewControllerDelegate?
private(set) var webView: WKWebView!
private var url: URL?
private var webViewConfiguration: WKWebViewConfiguration?
private var shouldIncludeDoneButton = false
private var keyValueObservers: [NSKeyValueObservation]?
private lazy var backButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "ArrowLeft"), style: .plain, target: self, action: #selector(backButtonTouched(_:forEvent:)))
private lazy var forwardButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "ArrowRight"), style: .plain, target: self, action: #selector(forwardButtonTouched(_:forEvent:)))
private lazy var shareButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(share(_:)))
private lazy var openInSafariButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "OpenInSafari"), style: .plain, target: self, action: #selector(openInSafari(_:)))
private lazy var doneButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(done(_:)))
private lazy var statusBarView: UIView = {
let view = UIBottomBorderedView(frame: UIApplication.shared.statusBarFrame, color: .lightGray, width: 0.5)
view.autoresizingMask = .flexibleWidth
view.backgroundColor = .globalBarTintColor
return view
}()
private lazy var defaultWebViewConfiguration: WKWebViewConfiguration = {
let config = WKWebViewConfiguration()
registerMessageHandlers(config.userContentController)
config.applicationNameForUserAgent = "Mobile AlliCrab"
let delegate = UIApplication.shared.delegate as! AppDelegate
config.ignoresViewportScaleLimits = true
config.mediaTypesRequiringUserActionForPlayback = [.video]
config.processPool = delegate.webKitProcessPool
return config
}()
// MARK: - Initialisers
required init(url: URL) {
super.init(nibName: nil, bundle: nil)
self.url = url
}
required init(configuration: WKWebViewConfiguration) {
super.init(nibName: nil, bundle: nil)
self.webViewConfiguration = configuration
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
// We nil these references out to unregister KVO on WKWebView
self.navigationItem.titleView = nil
keyValueObservers = nil
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
// MARK: - Actions
@objc func backButtonTouched(_ sender: UIBarButtonItem, forEvent event: UIEvent) {
guard let touch = event.allTouches?.first else { return }
switch touch.tapCount {
case 0: // Long press
self.showBackForwardList(webView.backForwardList.backList, sender: sender)
case 1: // Tap
self.webView.goBack()
default: break
}
}
@objc func forwardButtonTouched(_ sender: UIBarButtonItem, forEvent event: UIEvent) {
guard let touch = event.allTouches?.first else { return }
switch touch.tapCount {
case 0: // Long press
self.showBackForwardList(webView.backForwardList.forwardList, sender: sender)
case 1: // Tap
self.webView.goForward()
default: break
}
}
@objc func share(_ sender: UIBarButtonItem) {
guard let absoluteURL = webView.url?.absoluteURL else {
return
}
var activityItems: [AnyObject] = [absoluteURL as NSURL]
activityItems.reserveCapacity(2)
let onePasswordExtension = OnePasswordExtension.shared()
if onePasswordExtension.isAppExtensionAvailable() {
onePasswordExtension.createExtensionItem(forWebView: webView!) { extensionItem, error -> Void in
if let error = error {
os_log("Failed to create 1Password extension item: %@", type: .error, error as NSError)
} else if let extensionItem = extensionItem {
activityItems.append(extensionItem)
}
self.presentActivityViewController(activityItems, title: self.webView.title, sender: sender) {
activityType, completed, returnedItems, activityError in
if let error = activityError {
os_log("Activity failed: %@", type: .error, error as NSError)
DispatchQueue.main.async {
self.showAlert(title: "Activity failed", message: error.localizedDescription)
}
return
}
guard completed else {
return
}
if onePasswordExtension.isOnePasswordExtensionActivityType(activityType?.rawValue) {
onePasswordExtension.fillReturnedItems(returnedItems, intoWebView: self.webView!) { success, error in
if !success {
let errorDescription = error?.localizedDescription ?? "(No error details)"
os_log("Failed to fill password from password manager: %@", type: .error, errorDescription)
DispatchQueue.main.async {
self.showAlert(title: "Password fill failed", message: errorDescription)
}
}
}
}
}
}
} else {
presentActivityViewController(activityItems, title: webView.title, sender: sender)
}
}
@objc func openInSafari(_ sender: UIBarButtonItem) {
guard let URL = webView.url else {
return
}
UIApplication.shared.open(URL)
}
@objc func done(_ sender: UIBarButtonItem) {
finish()
}
func showBackForwardList(_ backForwardList: [WKBackForwardListItem], sender: UIBarButtonItem) {
let vc = WebViewBackForwardListTableViewController()
vc.backForwardList = backForwardList
vc.delegate = self
vc.modalPresentationStyle = .popover
if let popover = vc.popoverPresentationController {
popover.delegate = vc
popover.permittedArrowDirections = [.up, .down]
popover.barButtonItem = sender
}
present(vc, animated: true, completion: nil)
}
func presentActivityViewController(_ activityItems: [AnyObject], title: String?, sender: UIBarButtonItem, completionHandler: UIActivityViewController.CompletionWithItemsHandler? = nil) {
let avc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
avc.popoverPresentationController?.barButtonItem = sender;
avc.completionWithItemsHandler = completionHandler
if let title = title {
avc.setValue(title, forKey: "subject")
}
navigationController?.present(avc, animated: true, completion: nil)
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
webView = makeWebView()
keyValueObservers = registerObservers(webView)
self.view.addSubview(webView)
self.view.addSubview(statusBarView)
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: view.topAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
statusBarView.topAnchor.constraint(equalTo: view.topAnchor),
statusBarView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
statusBarView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
if let nc = self.navigationController {
shouldIncludeDoneButton = nc.viewControllers[0] == self
let addressBarView = WebAddressBarView(frame: nc.navigationBar.bounds, forWebView: webView)
self.navigationItem.titleView = addressBarView
}
configureToolbars(for: self.traitCollection)
if let url = self.url {
let request = URLRequest(url: url)
self.webView.load(request)
}
}
private func makeWebView() -> WKWebView {
let webView = WKWebView(frame: .zero, configuration: webViewConfiguration ?? defaultWebViewConfiguration)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.navigationDelegate = self
webView.uiDelegate = self
webView.allowsBackForwardNavigationGestures = true
webView.allowsLinkPreview = true
webView.keyboardDisplayDoesNotRequireUserAction()
return webView
}
private func registerObservers(_ webView: WKWebView) -> [NSKeyValueObservation] {
let keyValueObservers = [
webView.observe(\.canGoBack, options: [.initial]) { [weak self] webView, _ in
self?.backButton.isEnabled = webView.canGoBack
},
webView.observe(\.canGoForward, options: [.initial]) { [weak self] webView, _ in
self?.forwardButton.isEnabled = webView.canGoForward
},
webView.observe(\.isLoading, options: [.initial]) { [weak self] webView, _ in
UIApplication.shared.isNetworkActivityIndicatorVisible = webView.isLoading
self?.shareButton.isEnabled = !webView.isLoading && webView.url != nil
},
webView.observe(\.url, options: [.initial]) { [weak self] webView, _ in
let hasURL = webView.url != nil
self?.shareButton.isEnabled = !webView.isLoading && hasURL
self?.openInSafariButton.isEnabled = hasURL
}
]
return keyValueObservers
}
// MARK: - Size class transitions
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
if newCollection.horizontalSizeClass != traitCollection.horizontalSizeClass || newCollection.verticalSizeClass != traitCollection.verticalSizeClass {
configureToolbars(for: newCollection)
}
}
/// Sets the navigation bar and toolbar items based on the given UITraitCollection
func configureToolbars(for traitCollection: UITraitCollection) {
statusBarView.isHidden = traitCollection.verticalSizeClass == .compact
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
addToolbarItemsForCompactWidthRegularHeight()
} else {
addToolbarItemsForAllOtherTraitCollections()
}
}
/// For phone in portrait
func addToolbarItemsForCompactWidthRegularHeight() {
self.navigationController?.setToolbarHidden(false, animated: true)
navigationItem.leftItemsSupplementBackButton = !shouldIncludeDoneButton
navigationItem.leftBarButtonItems = customLeftBarButtonItems
navigationItem.rightBarButtonItems = customRightBarButtonItems
let flexibleSpace = { UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) }
setToolbarItems([backButton, flexibleSpace(), forwardButton, flexibleSpace(), shareButton, flexibleSpace(), openInSafariButton], animated: true)
}
/// For phone in landscape and pad in any orientation
func addToolbarItemsForAllOtherTraitCollections() {
self.navigationController?.setToolbarHidden(true, animated: true)
setToolbarItems(nil, animated: true)
navigationItem.leftItemsSupplementBackButton = !shouldIncludeDoneButton
navigationItem.leftBarButtonItems = customLeftBarButtonItems + [backButton, forwardButton]
navigationItem.rightBarButtonItems = customRightBarButtonItems + [openInSafariButton, shareButton]
}
var customLeftBarButtonItems: [UIBarButtonItem] {
var buttons: [UIBarButtonItem] = []
buttons.reserveCapacity(1)
if shouldIncludeDoneButton {
buttons.append(doneButton)
}
return buttons
}
var customRightBarButtonItems: [UIBarButtonItem] {
var buttons: [UIBarButtonItem] = []
buttons.reserveCapacity(1)
return buttons
}
// MARK: - Implementation
func showBrowserInterface(_ shouldShowBrowserInterface: Bool, animated: Bool) {
guard let nc = self.navigationController else { return }
nc.setNavigationBarHidden(!shouldShowBrowserInterface, animated: animated)
if self.toolbarItems?.isEmpty == false {
nc.setToolbarHidden(!shouldShowBrowserInterface, animated: animated)
}
}
func finish() {
unregisterMessageHandlers(webView.configuration.userContentController)
delegate?.webViewControllerDidFinish(self)
dismiss(animated: true, completion: nil)
}
func registerMessageHandlers(_ userContentController: WKUserContentController) {
}
func unregisterMessageHandlers(_ userContentController: WKUserContentController) {
}
}
// MARK: - WebViewBackForwardListTableViewControllerDelegate
extension WebViewController: WebViewBackForwardListTableViewControllerDelegate {
func webViewBackForwardListTableViewController(_ controller: WebViewBackForwardListTableViewController, didSelectBackForwardListItem item: WKBackForwardListItem) {
controller.dismiss(animated: true, completion: nil)
self.webView.go(to: item)
}
}
// MARK: - WKNavigationDelegate
extension WebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.navigationController?.setNavigationBarHidden(false, animated: true)
if self.toolbarItems?.isEmpty == false {
self.navigationController?.setToolbarHidden(false, animated: true)
}
injectUserScripts(to: webView)
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
injectUserScripts(to: webView)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
os_log("Navigation failed: %@", type: .error, error as NSError)
showErrorDialog(error)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
os_log("Navigation failed: %@", type: .error, error as NSError)
showErrorDialog(error)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let url = webView.url else { return }
switch url {
case WaniKaniURL.lessonSession, WaniKaniURL.reviewSession:
showBrowserInterface(false, animated: true)
default: break
}
}
private func injectUserScripts(to webView: WKWebView) {
webView.configuration.userContentController.removeAllUserScripts()
if let url = webView.url {
_ = injectUserScripts(for: url)
}
}
private func showErrorDialog(_ error: Error) {
switch error {
case let urlError as URLError where urlError.code == .cancelled:
break
case let nsError as NSError where nsError.domain == "WebKitErrorDomain" && nsError.code == 102:
break
default:
showAlert(title: "Failed to load page", message: error.localizedDescription)
}
}
}
// MARK: - WKScriptMessageHandler
extension WebViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
}
}
// MARK: - WKUIDelegate
extension WebViewController: WKUIDelegate {
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
let newVC = type(of: self).init(configuration: configuration)
newVC.url = navigationAction.request.url
self.navigationController?.pushViewController(newVC, animated: true)
return newVC.webView
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
DispatchQueue.main.async {
let host = frame.request.url?.host ?? "web page"
let title = "From \(host):"
os_log("Displaying alert with title %@ and message %@", type: .debug, title, message)
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler() })
self.present(alert, animated: true, completion: nil)
}
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
DispatchQueue.main.async {
let host = frame.request.url?.host ?? "web page"
let title = "From \(host):"
os_log("Displaying alert with title %@ and message %@", type: .debug, title, message)
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler(true) })
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completionHandler(false) })
self.present(alert, animated: true, completion: nil)
}
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
DispatchQueue.main.async {
let host = frame.request.url?.host ?? "web page"
let title = "From \(host):"
os_log("Displaying input panel with title %@ and message %@", type: .debug, title, prompt)
let alert = UIAlertController(title: title, message: prompt, preferredStyle: .alert)
alert.addTextField { $0.text = defaultText }
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler(alert.textFields?.first?.text) })
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completionHandler(nil) })
self.present(alert, animated: true, completion: nil)
}
}
}
// MARK: - WebViewUserScriptSupport
extension WebViewController: WebViewUserScriptSupport {
}
| mit | ad0882e04b5a0c878544ae986bce14c2 | 42.044586 | 201 | 0.651623 | 5.743343 | false | true | false | false |
hughhopkins/PW-OSX | Pods/CryptoSwift/Sources/CryptoSwift/PKCS7.swift | 4 | 1498 | //
// PKCS7.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 28/02/15.
// Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved.
//
// PKCS is a group of public-key cryptography standards devised
// and published by RSA Security Inc, starting in the early 1990s.
//
public struct PKCS7: Padding {
public enum Error: ErrorType {
case InvalidPaddingValue
}
public init() {
}
public func add(bytes: [UInt8] , blockSize:Int) -> [UInt8] {
let padding = UInt8(blockSize - (bytes.count % blockSize))
var withPadding = bytes
if (padding == 0) {
// If the original data is a multiple of N bytes, then an extra block of bytes with value N is added.
for _ in 0..<blockSize {
withPadding.appendContentsOf([UInt8(blockSize)])
}
} else {
// The value of each added byte is the number of bytes that are added
for _ in 0..<padding {
withPadding.appendContentsOf([UInt8(padding)])
}
}
return withPadding
}
public func remove(bytes: [UInt8], blockSize:Int?) -> [UInt8] {
let lastByte = bytes.last!
let padding = Int(lastByte) // last byte
let finalLength = bytes.count - padding
if finalLength < 0 {
return bytes
}
if padding >= 1 {
return Array(bytes[0..<finalLength])
}
return bytes
}
} | mit | 60d2e946c97d5c18f222c80ab18db6d9 | 27.283019 | 113 | 0.570761 | 4.405882 | false | false | false | false |
inkyfox/SwiftySQL | Sources/SQLFunc.swift | 3 | 2010 | //
// SQLFunc.swift
// SwiftySQL
//
// Created by Yongha Yoo (inkyfox) on 2016. 10. 22..
// Copyright © 2016년 Gen X Hippies Company. All rights reserved.
//
import Foundation
public struct SQLFunc: SQLValueType, SQLConditionType, SQLOrderType, SQLAliasable {
let name: String
let args: [SQLExprType]
public init(_ name: String, args: [SQLValueType] = []) {
self.name = name
self.args = args
}
public init(_ name: String, args: SQLAsteriskMark) {
self.name = name
self.args = [args]
}
public init(_ name: String, args: SQLValueType...) {
self.name = name
self.args = args
}
}
extension SQL {
public static func count(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("COUNT", args: [arg])
}
public static func count(_ args: SQLAsteriskMark) -> SQLFunc {
return SQLFunc("COUNT", args: args)
}
}
extension SQL {
public static func avg(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("AVG", args: [arg])
}
public static func max(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("MAX", args: [arg])
}
public static func min(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("MIN", args: [arg])
}
public static func sum(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("SUM", args: [arg])
}
public static func total(_ args: SQLValueType) -> SQLFunc {
return SQLFunc("TOTAL", args: [args])
}
public static func abs(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("ABS", args: [arg])
}
public static func length(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("LENGTH", args: [arg])
}
public static func lower(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("LOWER", args: [arg])
}
public static func upper(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("UPPER", args: [arg])
}
}
| mit | 79cfbc1d389f4f97bb8a7ca5c7578823 | 22.892857 | 83 | 0.581465 | 4.12963 | false | false | false | false |
lvogelzang/Blocky | Blocky/Levels/Level17.swift | 1 | 877 | //
// Level17.swift
// Blocky
//
// Created by Lodewijck Vogelzang on 07-12-18
// Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved.
//
import UIKit
final class Level17: Level {
let levelNumber = 17
var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]
let cameraFollowsBlock = false
let blocky: Blocky
let enemies: [Enemy]
let foods: [Food]
init() {
blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1))
let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0)
let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1)
enemies = [enemy0, enemy1]
foods = []
}
}
| mit | ce1fe8a1ed20d60e6ff6f6d192aaae7b | 24.794118 | 89 | 0.573546 | 2.649547 | false | false | false | false |
Roommate-App/roomy | roomy/Pods/IBAnimatable/Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallZigZag.swift | 2 | 2533 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallZigZag: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 0.7
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize: CGFloat = size.width / 5
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2,
y: (layer.bounds.size.height - circleSize) / 2,
width: circleSize,
height: circleSize)
// Circle 1 animation
let animation = CAKeyframeAnimation(keyPath:"transform")
animation.keyTimes = [0.0, 0.33, 0.66, 1.0]
animation.timingFunctionType = .linear
animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
let circle1 = makeCircleLayer(frame: frame, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
layer.addSublayer(circle1)
// Circle 2 animation
animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))]
let circle2 = makeCircleLayer(frame: frame, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
layer.addSublayer(circle2)
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallZigZag {
func makeCircleLayer(frame: CGRect, size: CGSize, color: UIColor, animation: CAAnimation) -> CALayer {
let circle = ActivityIndicatorShape.circle.makeLayer(size: size, color: color)
circle.frame = frame
circle.add(animation, forKey: "animation")
return circle
}
}
| mit | 0dc44b3593967b0d8093114f3548afbd | 40.52459 | 136 | 0.681011 | 4.58047 | false | false | false | false |
omochi/numsw | Playgrounds/RenderTableViewController.swift | 1 | 3874 | //
// RenderTableViewController.swift
// sandbox
//
// Created by color_box on 2017/03/04.
// Copyright © 2017年 sonson. All rights reserved.
//
// Second Implementation with UITableView
import UIKit
private class RenderTableViewCell: UITableViewCell {
var renderer: Renderer? {
willSet {
self.renderImageView.image = nil
self.renderedImageSize = .zero
}
}
private let renderImageView = UIImageView(frame: .zero)
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
print("RenderTableViewCell init")
self.separatorInset = .zero
self.selectionStyle = .none
renderImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
renderImageView.contentMode = .scaleAspectFit
self.contentView.addSubview(renderImageView)
renderImageView.frame = self.contentView.bounds
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
print("RenderTableViewCell deinit")
}
private var renderedImageSize = CGSize.zero
func updateImageViewIfNeeded() {
print("rendering bounds: \(self.contentView.bounds)")
if renderedImageSize == self.contentView.bounds.size &&
self.renderImageView.image != nil {
// already rendered
return
}
updateImageView()
}
private func updateImageView() {
guard let renderer = self.renderer else { return }
let image = renderer.renderToImage(size: self.contentView.bounds.size)
self.renderImageView.image = image
renderedImageSize = self.contentView.bounds.size
}
}
public class RenderTableViewController: UITableViewController {
private let CellIdentifier = "Cell"
var renderers: [Renderer] = [] {
didSet {
tableView.reloadData()
}
}
public init() {
super.init(style: .plain)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = .zero
tableView.separatorStyle = .none
tableView.register(RenderTableViewCell.self, forCellReuseIdentifier: CellIdentifier)
}
public func append(renderer: Renderer) {
self.renderers.append(renderer)
self.tableView.reloadData()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// will ??
//self.tableView.reloadData()
}
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
for view in tableView.visibleCells {
(view as! RenderTableViewCell).updateImageViewIfNeeded()
}
}
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return renderers.count
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath) as! RenderTableViewCell
cell.renderer = renderers[indexPath.row]
return cell
}
public override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.view.bounds.height * 0.5
}
public override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let cell = cell as! RenderTableViewCell
cell.updateImageViewIfNeeded()
}
}
| mit | 24833f7a387c4c6428260143b1c887bb | 29.968 | 128 | 0.652545 | 5.288251 | false | false | false | false |
apple/swift-package-manager | Sources/PackageGraph/Version+Extensions.swift | 2 | 656 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import struct TSCUtility.Version
extension Version {
func nextPatch() -> Version {
return Version(major, minor, patch + 1)
}
}
| apache-2.0 | fa1327c6d84252d4ddfe2c6b6d2b11fe | 33.526316 | 80 | 0.541159 | 5.206349 | false | false | false | false |
googlesamples/identity-appflip-ios | AppFlip-Sample-iOS/AppDelegate.swift | 1 | 2480 | /*
* Copyright 2019 Google
*
* 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
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity,
restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
print("Handling Universal Link");
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
let incomingURL = userActivity.webpageURL,
let components = NSURLComponents(url: incomingURL, resolvingAgainstBaseURL: true),
let path = components.path,
let params = components.queryItems else {
return false
}
print("path = \(path)")
// Start AppFlipViewController
let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initViewController : AppFlipViewController = mainStoryboard.instantiateViewController(
withIdentifier: "consentPanel") as! AppFlipViewController
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = initViewController
if let clientID = params.first(where: { $0.name == "client_id" } )?.value,
let scope = params.first(where: { $0.name == "scope" } )?.value,
let state = params.first(where: { $0.name == "state" } )?.value,
let redirectUri = params.first(where: { $0.name == "redirect_uri" } )?.value {
initViewController.flipData["clientID"] = clientID
initViewController.flipData["scope"] = scope
initViewController.flipData["state"] = state
initViewController.flipData["redirectUri"] = redirectUri
self.window?.makeKeyAndVisible()
return true
} else {
print("Parameters are missing")
return false
}
}
}
| apache-2.0 | 9092ef3ed647219922d3e50ca24bcf6e | 37.75 | 94 | 0.704839 | 4.760077 | false | false | false | false |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/AnyObserver.swift | 8 | 2199 | //
// AnyObserver.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// A type-erased `ObserverType`.
///
/// Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type.
public struct AnyObserver<Element> : ObserverType {
/// Anonymous event handler type.
public typealias EventHandler = (Event<Element>) -> Void
private let observer: EventHandler
/// Construct an instance whose `on(event)` calls `eventHandler(event)`
///
/// - parameter eventHandler: Event handler that observes sequences events.
public init(eventHandler: @escaping EventHandler) {
self.observer = eventHandler
}
/// Construct an instance whose `on(event)` calls `observer.on(event)`
///
/// - parameter observer: Observer that receives sequence events.
public init<Observer: ObserverType>(_ observer: Observer) where Observer.Element == Element {
self.observer = observer.on
}
/// Send `event` to this observer.
///
/// - parameter event: Event instance.
public func on(_ event: Event<Element>) {
self.observer(event)
}
/// Erases type of observer and returns canonical observer.
///
/// - returns: type erased observer.
public func asObserver() -> AnyObserver<Element> {
self
}
}
extension AnyObserver {
/// Collection of `AnyObserver`s
typealias s = Bag<(Event<Element>) -> Void>
}
extension ObserverType {
/// Erases type of observer and returns canonical observer.
///
/// - returns: type erased observer.
public func asObserver() -> AnyObserver<Element> {
AnyObserver(self)
}
/// Transforms observer of type R to type E using custom transform method.
/// Each event sent to result observer is transformed and sent to `self`.
///
/// - returns: observer that transforms events.
public func mapObserver<Result>(_ transform: @escaping (Result) throws -> Element) -> AnyObserver<Result> {
AnyObserver { e in
self.on(e.map(transform))
}
}
}
| mit | 0c0065cc6b0405e9578666bdcb09243d | 30.855072 | 143 | 0.656051 | 4.617647 | false | false | false | false |
zhiquan911/CHKLineChart | CHKLineChart/Example/Example/Demo/views/SectionHeaderView.swift | 1 | 1733 | //
// SectionHeaderView.swift
// CHKLineChart
//
// Created by Chance on 2017/7/14.
// Copyright © 2017年 atall.io. All rights reserved.
//
import UIKit
import SnapKit
import CHKLineChartKit
class SectionHeaderView: UIView {
@IBOutlet var labelTitle: UILabel!
@IBOutlet var buttonSet: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupUI() {
self.buttonSet = UIButton(type: .custom)
self.buttonSet.setTitle("设置", for: .normal)
self.buttonSet.titleLabel?.font = UIFont.systemFont(ofSize: 10)
self.buttonSet.setTitleColor(UIColor.white, for: .normal)
self.buttonSet.backgroundColor = UIColor.darkGray
self.buttonSet.layer.cornerRadius = 2
self.addSubview(self.buttonSet)
self.buttonSet.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(2)
make.top.bottom.equalToSuperview().offset(2)
make.width.equalTo(30)
}
// self.buttonSet.frame = CGRect(x: 0, y: 1, width: 30, height: 20)
self.labelTitle = UILabel()
self.labelTitle.textColor = UIColor.white
self.labelTitle.font = UIFont.systemFont(ofSize: 10)
self.labelTitle.backgroundColor = UIColor.clear
self.addSubview(self.labelTitle)
self.labelTitle.snp.makeConstraints { (make) in
make.left.equalTo(self.buttonSet.snp.right).offset(8)
make.top.bottom.equalToSuperview().offset(2)
make.right.equalToSuperview()
}
}
}
| mit | 940583b43b732c7685ddb34bc79094a3 | 28.254237 | 74 | 0.625145 | 4.261728 | false | false | false | false |
arvedviehweger/swift | test/ClangImporter/objc_bridging_generics.swift | 1 | 15238 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -verify -swift-version 4 %s
// REQUIRES: objc_interop
import Foundation
import objc_generics
func testNSArrayBridging(_ hive: Hive) {
_ = hive.bees as [Bee]
}
func testNSDictionaryBridging(_ hive: Hive) {
_ = hive.beesByName as [String : Bee] // expected-error{{'[String : Bee]?' is not convertible to '[String : Bee]'; did you mean to use 'as!' to force downcast?}}
var dict1 = hive.anythingToBees
let dict2: [AnyHashable : Bee] = dict1
dict1 = dict2
}
func testNSSetBridging(_ hive: Hive) {
_ = hive.allBees as Set<Bee>
}
public func expectType<T>(_: T.Type, _ x: inout T) {}
func testNSMutableDictionarySubscript(
_ dict: NSMutableDictionary, key: NSCopying, value: Any) {
var oldValue = dict[key]
expectType(Optional<Any>.self, &oldValue)
dict[key] = value
}
class C {}
struct S {}
func f(_ x: GenericClass<NSString>) -> NSString? { return x.thing() }
func f1(_ x: GenericClass<NSString>) -> NSString? { return x.otherThing() }
func f2(_ x: GenericClass<NSString>) -> Int32 { return x.count() }
func f3(_ x: GenericClass<NSString>) -> NSString? { return x.propertyThing }
func f4(_ x: GenericClass<NSString>) -> [NSString] { return x.arrayOfThings() }
func f5(_ x: GenericClass<C>) -> [C] { return x.arrayOfThings() }
func f6(_ x: GenericSubclass<NSString>) -> NSString? { return x.thing() }
func f6(_ x: GenericSubclass<C>) -> C? { return x.thing() }
func g() -> NSString? { return GenericClass<NSString>.classThing() }
func g1() -> NSString? { return GenericClass<NSString>.otherClassThing() }
func h(_ s: NSString?) -> GenericClass<NSString> {
return GenericClass(thing: s)
}
func j(_ x: GenericClass<NSString>?) {
takeGenericClass(x)
}
class Desk {}
class Rock: NSObject, Pettable {
required init(fur: Any) {}
func other() -> Self { return self }
class func adopt() -> Self { fatalError("") }
func pet() {}
func pet(with other: Pettable) {}
class var needingMostPets: Pettable {
get { fatalError("") }
set { }
}
}
class Porcupine: Animal {
}
class Cat: Animal, Pettable {
required init(fur: Any) {}
func other() -> Self { return self }
class func adopt() -> Self { fatalError("") }
func pet() {}
func pet(with other: Pettable) {}
class var needingMostPets: Pettable {
get { fatalError("") }
set { }
}
}
func testImportedTypeParamRequirements() {
let _ = PettableContainer<Desk>() // expected-error{{type 'Desk' does not conform to protocol 'Pettable'}}
let _ = PettableContainer<Rock>()
let _ = PettableContainer<Porcupine>() // expected-error{{type 'Porcupine' does not conform to protocol 'Pettable'}}
let _ = PettableContainer<Cat>()
let _ = AnimalContainer<Desk>() // expected-error{{'AnimalContainer' requires that 'Desk' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Desk]}}
let _ = AnimalContainer<Rock>() // expected-error{{'AnimalContainer' requires that 'Rock' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Rock]}}
let _ = AnimalContainer<Porcupine>()
let _ = AnimalContainer<Cat>()
let _ = PettableAnimalContainer<Desk>() // expected-error{{'PettableAnimalContainer' requires that 'Desk' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Desk]}}
let _ = PettableAnimalContainer<Rock>() // expected-error{{'PettableAnimalContainer' requires that 'Rock' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Rock]}}
let _ = PettableAnimalContainer<Porcupine>() // expected-error{{type 'Porcupine' does not conform to protocol 'Pettable'}}
let _ = PettableAnimalContainer<Cat>()
}
extension GenericClass {
@objc func doesntUseGenericParam() {}
@objc func doesntUseGenericParam2() -> Self {}
// Doesn't use 'T', since ObjC class type params are type-erased
@objc func doesntUseGenericParam3() -> GenericClass<T> {}
// Doesn't use 'T', since its metadata isn't necessary to pass around instance
@objc func doesntUseGenericParam4(_ x: T, _ y: T.Type) -> T {
_ = x
_ = y
return x
}
// Doesn't use 'T', since its metadata isn't necessary to erase to AnyObject
// or to existential metatype
@objc func doesntUseGenericParam5(_ x: T, _ y: T.Type) -> T {
_ = y as AnyObject.Type
_ = y as Any.Type
_ = y as AnyObject
_ = x as AnyObject
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamC(_ x: [(T, T)]?) {} // expected-note{{used here}}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamD(_ x: Int) {
_ = T.self // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamE(_ x: Int) {
_ = x as? T // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamF(_ x: Int) {
_ = x is T // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamG(_ x: T) {
_ = T.self // expected-note{{used here}}
}
@objc func doesntUseGenericParamH(_ x: T) {
_ = x as Any
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamI(_ y: T.Type) {
_ = y as Any // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamJ() -> [(T, T)]? {} // expected-note{{used here}}
@objc static func doesntUseGenericParam() {}
@objc static func doesntUseGenericParam2() -> Self {}
// Doesn't technically use 'T', since it's type-erased at runtime
@objc static func doesntUseGenericParam3() -> GenericClass<T> {}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
static func usesGenericParamC(_ x: [(T, T)]?) {} // expected-note{{used here}}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc static func usesGenericParamD(_ x: Int) {
_ = T.self // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc static func usesGenericParamE(_ x: Int) {
_ = x as? T // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc static func usesGenericParamF(_ x: Int) {
_ = x is T // expected-note{{used here}}
}
@objc func checkThatMethodsAreObjC() {
_ = #selector(GenericClass.doesntUseGenericParam)
_ = #selector(GenericClass.doesntUseGenericParam2)
_ = #selector(GenericClass.doesntUseGenericParam3)
_ = #selector(GenericClass.doesntUseGenericParam4)
_ = #selector(GenericClass.doesntUseGenericParam5)
}
}
func swiftFunction<T: Animal>(x: T) {}
extension AnimalContainer {
@objc func doesntUseGenericParam1(_ x: T, _ y: T.Type) {
_ = #selector(x.another)
_ = #selector(y.create)
}
@objc func doesntUseGenericParam2(_ x: T, _ y: T.Type) {
let a = x.another()
_ = a.another()
_ = x.another().another()
_ = type(of: x).create().another()
_ = type(of: x).init(noise: x).another()
_ = y.create().another()
_ = y.init(noise: x).another()
_ = y.init(noise: x.another()).another()
x.eat(a)
}
@objc func doesntUseGenericParam3(_ x: T, _ y: T.Type) {
let sup: Animal = x
sup.eat(x)
_ = x.buddy
_ = x[0]
x[0] = x
}
@objc func doesntUseGenericParam4(_ x: T, _ y: T.Type) {
_ = type(of: x).apexPredator.another()
type(of: x).apexPredator = x
_ = y.apexPredator.another()
y.apexPredator = x
}
@objc func doesntUseGenericParam5(y: T) {
var x = y
x = y
_ = x
}
@objc func doesntUseGenericParam6(y: T?) {
var x = y
x = y
_ = x
}
// Doesn't use 'T', since dynamic casting to an ObjC generic class doesn't
// check its generic parameters
@objc func doesntUseGenericParam7() {
_ = (self as AnyObject) as! GenericClass<T>
_ = (self as AnyObject) as? GenericClass<T>
_ = (self as AnyObject) as! AnimalContainer<T>
_ = (self as AnyObject) as? AnimalContainer<T>
_ = (self as AnyObject) is AnimalContainer<T>
_ = (self as AnyObject) is AnimalContainer<T>
}
// Dynamic casting to the generic parameter would require its generic params,
// though
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamZ1() {
_ = (self as AnyObject) as! T //expected-note{{here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamZ2() {
_ = (self as AnyObject) as? T //expected-note{{here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamZ3() {
_ = (self as AnyObject) is T //expected-note{{here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamA(_ x: T) {
_ = T(noise: x) // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamB() {
_ = T.create() // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamC() {
_ = T.apexPredator // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamD(_ x: T) {
T.apexPredator = x // expected-note{{used here}}
}
// rdar://problem/27796375 -- allocating init entry points for ObjC
// initializers are generated as true Swift generics, so reify type
// parameters.
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamE(_ x: T) {
_ = GenericClass(thing: x) // expected-note{{used here}}
}
@objc func checkThatMethodsAreObjC() {
_ = #selector(AnimalContainer.doesntUseGenericParam1)
_ = #selector(AnimalContainer.doesntUseGenericParam2)
_ = #selector(AnimalContainer.doesntUseGenericParam3)
_ = #selector(AnimalContainer.doesntUseGenericParam4)
}
// rdar://problem/26283886
@objc func funcWithWrongArgType(x: NSObject) {}
@objc func crashWithInvalidSubscript(x: NSArray) {
_ = funcWithWrongArgType(x: x[12])
// expected-error@-1{{cannot convert value of type 'Any' to expected argument type 'NSObject'}}
}
}
extension PettableContainer {
@objc func doesntUseGenericParam(_ x: T, _ y: T.Type) {
// TODO: rdar://problem/27796375--allocating entry points are emitted as
// true generics.
// _ = type(of: x).init(fur: x).other()
_ = type(of: x).adopt().other()
// _ = y.init(fur: x).other()
_ = y.adopt().other()
x.pet()
x.pet(with: x)
}
// TODO: rdar://problem/27796375--allocating entry points are emitted as
// true generics.
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamZ1(_ x: T, _ y: T.Type) {
_ = type(of: x).init(fur: x).other() // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamZ2(_ x: T, _ y: T.Type) {
_ = y.init(fur: x).other() // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamA(_ x: T) {
_ = T(fur: x) // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamB(_ x: T) {
_ = T.adopt() // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamC(_ x: T) {
_ = T.needingMostPets // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamD(_ x: T) {
T.needingMostPets = x // expected-note{{used here}}
}
@objc func checkThatMethodsAreObjC() {
_ = #selector(PettableContainer.doesntUseGenericParam)
}
}
// expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}}
class SwiftGenericSubclassA<X: AnyObject>: GenericClass<X> {}
// expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}}
class SwiftGenericSubclassB<X: AnyObject>: GenericClass<GenericClass<X>> {}
// expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}}
class SwiftGenericSubclassC<X: NSCopying>: GenericClass<X> {}
class SwiftConcreteSubclassA: GenericClass<AnyObject> {
override init(thing: AnyObject) { }
override func thing() -> AnyObject? { }
override func count() -> Int32 { }
override class func classThing() -> AnyObject? { }
override func arrayOfThings() -> [AnyObject] {}
}
class SwiftConcreteSubclassB: GenericClass<NSString> {
override init(thing: NSString) { }
override func thing() -> NSString? { }
override func count() -> Int32 { }
override class func classThing() -> NSString? { }
override func arrayOfThings() -> [NSString] {}
}
class SwiftConcreteSubclassC<T>: GenericClass<NSString> {
override init(thing: NSString) { }
override func thing() -> NSString? { }
override func count() -> Int32 { }
override class func classThing() -> NSString? { }
override func arrayOfThings() -> [NSString] {}
}
// FIXME: Some generic ObjC APIs rely on covariance. We don't handle this well
// in Swift yet, but ensure we don't emit spurious warnings when
// `as!` is used to force types to line up.
func foo(x: GenericClass<NSMutableString>) {
let x2 = x as! GenericClass<NSString>
takeGenericClass(x2)
takeGenericClass(unsafeBitCast(x, to: GenericClass<NSString>.self))
}
// Test type-erased bounds
func getContainerForPanda() -> AnimalContainer<Animal> {
return Panda.getContainer()
}
func getContainerForFungiblePanda() -> FungibleAnimalContainer<Animal & Fungible> {
return Panda.getFungibleContainer()
}
| apache-2.0 | 9830d2e1493b9fd114d7214532206900 | 38.476684 | 204 | 0.681323 | 3.905177 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Views/HabiticaAlertController.swift | 1 | 16880 | //
// BaseAlertController.swift
// Habitica
//
// Created by Phillip on 23.10.17.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
import PopupDialog
@objc
class HabiticaAlertController: UIViewController, Themeable {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var titleLabelTopMargin: NSLayoutConstraint!
@IBOutlet weak var titleLabelBottomMargin: NSLayoutConstraint!
@IBOutlet weak var titleLabelBackground: UIView!
@IBOutlet weak var buttonStackView: UIStackView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var alertStackView: UIStackView!
@IBOutlet weak var bottomOffsetConstraint: NSLayoutConstraint!
@IBOutlet var centerConstraint: NSLayoutConstraint!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var scrollviewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var alertBackgroundView: UIView!
@IBOutlet weak var buttonContainerView: UIView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var containerViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var buttonUpperSpacing: NSLayoutConstraint!
@IBOutlet weak var buttonLowerSpacing: NSLayoutConstraint!
private var buttonHandlers = [Int: ((UIButton) -> Swift.Void)]()
private var buttons = [UIButton]()
private var shouldCloseOnButtonTap = [Int: Bool]()
var dismissOnBackgroundTap = true
var contentView: UIView? {
didSet {
configureContentView()
}
}
override var title: String? {
didSet {
configureTitleView()
}
}
var message: String? {
didSet {
if message == nil || self.view == nil {
return
}
attributedMessage = nil
configureMessageView()
}
}
var attributedMessage: NSAttributedString? {
didSet {
if attributedMessage == nil || self.view == nil {
return
}
message = nil
configureMessageView()
}
}
var messageFont = CustomFontMetrics.scaledSystemFont(ofSize: 17)
var messageColor: UIColor?
var messageView: UILabel?
var arrangeMessageLast = false
var closeAction: (() -> Void)? {
didSet {
configureCloseButton()
}
}
var contentViewInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30) {
didSet {
if containerView != nil {
containerView.layoutMargins = contentViewInsets
}
}
}
var containerViewSpacing: CGFloat = 8
var closeTitle: String?
convenience init(title newTitle: String?, message newMessage: String? = nil) {
self.init()
title = newTitle
message = newMessage
}
convenience init(title newTitle: String?, attributedMessage newMessage: NSAttributedString) {
self.init()
title = newTitle
attributedMessage = newMessage
}
init() {
super.init(nibName: "HabiticaAlertController", bundle: Bundle.main)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
ThemeService.shared.addThemeable(themable: self, applyImmediately: true)
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backgroundTapped)))
alertBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(alertTapped)))
}
func applyTheme(theme: Theme) {
view.backgroundColor = theme.dimmBackgroundColor.withAlphaComponent(0.7)
buttonContainerView.backgroundColor = theme.contentBackgroundColor
alertBackgroundView.backgroundColor = theme.contentBackgroundColor
closeButton.backgroundColor = theme.contentBackgroundColor
titleLabel.textColor = theme.primaryTextColor
titleLabelBackground.backgroundColor = theme.contentBackgroundColor
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configureTitleView()
configureContentView()
configureMessageView()
configureCloseButton()
configureButtons()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
super.viewWillDisappear(animated)
}
override func viewWillLayoutSubviews() {
var maximumSize = view.frame.size
if #available(iOS 11.0, *) {
let guide = view.safeAreaLayoutGuide
maximumSize = guide.layoutFrame.size
}
maximumSize.width = min(300, maximumSize.width - 24)
maximumSize.width -= contentViewInsets.left + contentViewInsets.right
maximumSize.height -= contentViewInsets.top + contentViewInsets.bottom
let maximumHeight = maximumSize.height - (32 + 140) - buttonUpperSpacing.constant - buttonLowerSpacing.constant
var contentHeight = contentView?.systemLayoutSizeFitting(maximumSize).height ?? 0
if contentHeight == 0 {
contentHeight = contentView?.intrinsicContentSize.height ?? 0
}
var height = contentHeight + contentViewInsets.top + contentViewInsets.bottom
if let messageView = messageView {
if height > 0 {
height += containerViewSpacing
}
height += messageView.sizeThatFits(maximumSize).height
}
scrollviewHeightConstraint.constant = min(height, maximumHeight)
if arrangeMessageLast {
if let contentView = contentView {
contentView.pin.top(contentViewInsets.top).left(contentViewInsets.left).width(maximumSize.width).height(contentHeight)
messageView?.pin.top(contentHeight + containerViewSpacing).left(contentViewInsets.left).width(maximumSize.width).sizeToFit(.width)
} else {
messageView?.pin.top(contentViewInsets.top).left(contentViewInsets.left).width(maximumSize.width).height(height)
}
} else {
if let messageView = messageView {
messageView.pin.top(contentViewInsets.top).left(contentViewInsets.left).width(maximumSize.width).sizeToFit(.width)
contentView?.pin.below(of: messageView).marginTop(containerViewSpacing).left(contentViewInsets.left).width(maximumSize.width).height(contentHeight)
} else {
contentView?.pin.top(contentViewInsets.top).left(contentViewInsets.left).width(maximumSize.width).height(contentHeight)
}
}
containerViewHeightConstraint.constant = height
contentView?.updateConstraints()
super.viewWillLayoutSubviews()
}
@objc
func keyboardWillShow(notification: NSNotification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.bottomOffsetConstraint.constant = keyboardHeight + 8
if centerConstraint.isActive {
centerConstraint.isActive = false
}
}
}
@objc
func keyboardWillHide(notification: NSNotification) {
self.bottomOffsetConstraint.constant = 16
if !centerConstraint.isActive {
centerConstraint.isActive = true
}
}
@objc
@discardableResult
func addAction(title: String, style: UIAlertAction.Style = .default, isMainAction: Bool = false, closeOnTap: Bool = true, identifier: String? = nil, handler: ((UIButton) -> Swift.Void)? = nil) -> UIButton {
let button = UIButton()
if let identifier = identifier {
button.accessibilityIdentifier = identifier
}
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.setTitle(title, for: .normal)
button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 24, bottom: 8, right: 24)
var color = isMainAction ? ThemeService.shared.theme.fixedTintColor : ThemeService.shared.theme.tintColor
if style == .destructive {
color = ThemeService.shared.theme.errorColor
}
if isMainAction {
button.setTitleColor(UIColor.white, for: .normal)
button.titleLabel?.font = CustomFontMetrics.scaledSystemFont(ofSize: 17, ofWeight: .semibold)
button.backgroundColor = color
button.cornerRadius = 8
button.layer.shadowColor = ThemeService.shared.theme.buttonShadowColor.cgColor
button.layer.shadowRadius = 2
button.layer.shadowOffset = CGSize(width: 1, height: 1)
button.layer.shadowOpacity = 0.5
button.layer.masksToBounds = false
} else {
button.setTitleColor(color, for: .normal)
button.titleLabel?.font = CustomFontMetrics.scaledSystemFont(ofSize: 17)
}
button.addWidthConstraint(width: 150, relatedBy: NSLayoutConstraint.Relation.greaterThanOrEqual)
button.addHeightConstraint(height: 38)
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
button.tag = buttons.count
if let action = handler {
buttonHandlers[button.tag] = action
}
shouldCloseOnButtonTap[button.tag] = closeOnTap
buttons.append(button)
if buttonStackView != nil {
buttonStackView.addArrangedSubview(button)
if buttonStackView.arrangedSubviews.count > 2 {
buttonStackView.axis = .vertical
}
}
return button
}
@objc
func setCloseAction(title: String, handler: @escaping (() -> Void)) {
closeAction = handler
closeTitle = title
}
private func configureTitleView() {
if titleLabel != nil {
titleLabel.text = title
}
if title == nil && titleLabelTopMargin != nil && titleLabelBottomMargin != nil {
titleLabelTopMargin.constant = 0
titleLabelBottomMargin.constant = 0
} else if titleLabelTopMargin != nil && titleLabelBottomMargin != nil {
titleLabelTopMargin.constant = 12
titleLabelBottomMargin.constant = 12
}
}
private func configureMessageView() {
if (message == nil && attributedMessage == nil) || containerView == nil {
return
}
let label = UILabel()
label.textColor = messageColor ?? ThemeService.shared.theme.secondaryTextColor
label.font = messageFont
if message != nil {
label.text = message
} else {
label.attributedText = attributedMessage
}
label.numberOfLines = 0
label.textAlignment = .center
containerView.addSubview(label)
messageView = label
}
private func configureContentView() {
if containerView == nil {
return
}
containerView.layoutMargins = contentViewInsets
if contentView == nil && message == nil {
containerView.superview?.isHidden = true
alertStackView.spacing = 0
} else {
containerView.superview?.isHidden = false
alertStackView.spacing = containerViewSpacing
}
if let view = contentView {
if let oldView = containerView.subviews.first {
oldView.removeFromSuperview()
}
containerView.addSubview(view)
}
}
private func configureCloseButton() {
if closeButton != nil {
closeButton.isHidden = closeAction == nil
closeButton.setTitle(closeTitle, for: .normal)
closeButton.tintColor = ThemeService.shared.theme.fixedTintColor
}
}
private func configureButtons() {
buttonStackView.arrangedSubviews.forEach { (view) in
view.removeFromSuperview()
}
for button in buttons {
buttonStackView.addArrangedSubview(button)
}
if buttons.count > 1 {
buttonStackView.axis = .vertical
} else {
buttonStackView.axis = .horizontal
}
}
@objc
func show() {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
modalTransitionStyle = .crossDissolve
modalPresentationStyle = .overCurrentContext
topController.present(self, animated: true) {
}
}
}
@objc
func enqueue() {
HabiticaAlertController.addToQueue(alert: self)
}
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
super.dismiss(animated: flag, completion: completion)
HabiticaAlertController.showNextInQueue(currentAlert: self)
}
@objc
func buttonTapped(_ button: UIButton) {
if shouldCloseOnButtonTap[button.tag] != false {
dismiss(animated: true, completion: {[weak self] in
self?.buttonHandlers[button.tag]?(button)
})
} else {
buttonHandlers[button.tag]?(button)
}
}
@IBAction func closeTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
if let action = closeAction {
action()
}
}
@objc
func backgroundTapped() {
if dismissOnBackgroundTap {
dismiss(animated: true, completion: nil)
}
}
@objc
func alertTapped() {
// if the alert is tapped, it should not be dismissed
}
private static var alertQueue = [HabiticaAlertController]()
private static func showNextInQueue(currentAlert: HabiticaAlertController) {
if alertQueue.first == currentAlert {
alertQueue.removeFirst()
}
if !alertQueue.isEmpty {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
alertQueue[0].show()
}
}
}
private static func addToQueue(alert: HabiticaAlertController) {
if alertQueue.isEmpty {
alert.show()
}
alertQueue.append(alert)
}
}
extension HabiticaAlertController {
@objc
public static func alert(title: String? = nil,
message: String? = nil) -> HabiticaAlertController {
let alertController = HabiticaAlertController(
title: title,
message: message
)
return alertController
}
@objc
public static func alert(title: String? = nil,
attributedMessage: NSAttributedString) -> HabiticaAlertController {
let alertController = HabiticaAlertController(
title: title,
attributedMessage: attributedMessage
)
return alertController
}
@objc
public static func genericError(message: String?, title: String = L10n.Errors.error) -> HabiticaAlertController {
let alertController = HabiticaAlertController(
title: title,
message: message
)
alertController.addOkAction()
return alertController
}
@objc
func addCancelAction(handler: ((UIButton) -> Void)? = nil) {
addAction(title: L10n.cancel, identifier: "Cancel", handler: handler)
}
@objc
func addCloseAction(handler: ((UIButton) -> Void)? = nil) {
addAction(title: L10n.close, identifier: "Close", handler: handler)
}
@objc
func addShareAction(handler: ((UIButton) -> Void)? = nil) {
addAction(title: L10n.share, closeOnTap: false, handler: handler)
}
@objc
func addOkAction(handler: ((UIButton) -> Void)? = nil) {
addAction(title: L10n.ok, handler: handler)
}
}
| gpl-3.0 | 3233ab528f5e311355259f93d572c88c | 34.912766 | 210 | 0.629421 | 5.587223 | false | false | false | false |
twobitlabs/Nimble | Tests/NimbleTests/Matchers/MatchErrorTest.swift | 11 | 3159 | import Foundation
import XCTest
import Nimble
final class MatchErrorTest: XCTestCase, XCTestCaseProvider {
func testMatchErrorPositive() {
expect(NimbleError.laugh).to(matchError(NimbleError.laugh))
expect(NimbleError.laugh).to(matchError(NimbleError.self))
expect(EquatableError.parameterized(x: 1)).to(matchError(EquatableError.parameterized(x: 1)))
expect(NimbleError.laugh as Error).to(matchError(NimbleError.laugh))
}
func testMatchErrorNegative() {
expect(NimbleError.laugh).toNot(matchError(NimbleError.cry))
expect(NimbleError.laugh as Error).toNot(matchError(NimbleError.cry))
expect(NimbleError.laugh).toNot(matchError(EquatableError.self))
expect(EquatableError.parameterized(x: 1)).toNot(matchError(EquatableError.parameterized(x: 2)))
}
func testMatchNSErrorPositive() {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let error1 = NSError(domain: "err", code: 0, userInfo: nil)
let error2 = NSError(domain: "err", code: 0, userInfo: nil)
expect(error1).to(matchError(error2))
#endif
}
func testMatchNSErrorNegative() {
let error1 = NSError(domain: "err", code: 0, userInfo: nil)
let error2 = NSError(domain: "err", code: 1, userInfo: nil)
expect(error1).toNot(matchError(error2))
}
func testMatchPositiveMessage() {
failsWithErrorMessage("expected to match error <parameterized(x: 2)>, got <parameterized(x: 1)>") {
expect(EquatableError.parameterized(x: 1)).to(matchError(EquatableError.parameterized(x: 2)))
}
failsWithErrorMessage("expected to match error <cry>, got <laugh>") {
expect(NimbleError.laugh).to(matchError(NimbleError.cry))
}
failsWithErrorMessage("expected to match error <code=1>, got <code=0>") {
expect(CustomDebugStringConvertibleError.a).to(matchError(CustomDebugStringConvertibleError.b))
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
failsWithErrorMessage("expected to match error <Error Domain=err Code=1 \"(null)\">, got <Error Domain=err Code=0 \"(null)\">") {
let error1 = NSError(domain: "err", code: 0, userInfo: nil)
let error2 = NSError(domain: "err", code: 1, userInfo: nil)
expect(error1).to(matchError(error2))
}
#endif
}
func testMatchNegativeMessage() {
failsWithErrorMessage("expected to not match error <laugh>, got <laugh>") {
expect(NimbleError.laugh).toNot(matchError(NimbleError.laugh))
}
failsWithErrorMessage("expected to match error from type <EquatableError>, got <laugh>") {
expect(NimbleError.laugh).to(matchError(EquatableError.self))
}
}
func testDoesNotMatchNils() {
failsWithErrorMessageForNil("expected to match error <laugh>, got no error") {
expect(nil as Error?).to(matchError(NimbleError.laugh))
}
failsWithErrorMessageForNil("expected to not match error <laugh>, got no error") {
expect(nil as Error?).toNot(matchError(NimbleError.laugh))
}
}
}
| apache-2.0 | 720f1300531a4e03c427187f096e2690 | 40.565789 | 137 | 0.662551 | 4.369295 | false | true | false | false |
onevcat/Kingfisher | Sources/General/ImageSource/AVAssetImageDataProvider.swift | 2 | 5185 | //
// AVAssetImageDataProvider.swift
// Kingfisher
//
// Created by onevcat on 2020/08/09.
//
// Copyright (c) 2020 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(watchOS)
import Foundation
import AVKit
#if canImport(MobileCoreServices)
import MobileCoreServices
#else
import CoreServices
#endif
/// A data provider to provide thumbnail data from a given AVKit asset.
public struct AVAssetImageDataProvider: ImageDataProvider {
/// The possible error might be caused by the `AVAssetImageDataProvider`.
/// - userCancelled: The data provider process is cancelled.
/// - invalidImage: The retrieved image is invalid.
public enum AVAssetImageDataProviderError: Error {
case userCancelled
case invalidImage(_ image: CGImage?)
}
/// The asset image generator bound to `self`.
public let assetImageGenerator: AVAssetImageGenerator
/// The time at which the image should be generate in the asset.
public let time: CMTime
private var internalKey: String {
return (assetImageGenerator.asset as? AVURLAsset)?.url.absoluteString ?? UUID().uuidString
}
/// The cache key used by `self`.
public var cacheKey: String {
return "\(internalKey)_\(time.seconds)"
}
/// Creates an asset image data provider.
/// - Parameters:
/// - assetImageGenerator: The asset image generator controls data providing behaviors.
/// - time: At which time in the asset the image should be generated.
public init(assetImageGenerator: AVAssetImageGenerator, time: CMTime) {
self.assetImageGenerator = assetImageGenerator
self.time = time
}
/// Creates an asset image data provider.
/// - Parameters:
/// - assetURL: The URL of asset for providing image data.
/// - time: At which time in the asset the image should be generated.
///
/// This method uses `assetURL` to create an `AVAssetImageGenerator` object and calls
/// the `init(assetImageGenerator:time:)` initializer.
///
public init(assetURL: URL, time: CMTime) {
let asset = AVAsset(url: assetURL)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
self.init(assetImageGenerator: generator, time: time)
}
/// Creates an asset image data provider.
///
/// - Parameters:
/// - assetURL: The URL of asset for providing image data.
/// - seconds: At which time in seconds in the asset the image should be generated.
///
/// This method uses `assetURL` to create an `AVAssetImageGenerator` object, uses `seconds` to create a `CMTime`,
/// and calls the `init(assetImageGenerator:time:)` initializer.
///
public init(assetURL: URL, seconds: TimeInterval) {
let time = CMTime(seconds: seconds, preferredTimescale: 600)
self.init(assetURL: assetURL, time: time)
}
public func data(handler: @escaping (Result<Data, Error>) -> Void) {
assetImageGenerator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)]) {
(requestedTime, image, imageTime, result, error) in
if let error = error {
handler(.failure(error))
return
}
if result == .cancelled {
handler(.failure(AVAssetImageDataProviderError.userCancelled))
return
}
guard let cgImage = image, let data = cgImage.jpegData else {
handler(.failure(AVAssetImageDataProviderError.invalidImage(image)))
return
}
handler(.success(data))
}
}
}
extension CGImage {
var jpegData: Data? {
guard let mutableData = CFDataCreateMutable(nil, 0),
let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, nil)
else {
return nil
}
CGImageDestinationAddImage(destination, self, nil)
guard CGImageDestinationFinalize(destination) else { return nil }
return mutableData as Data
}
}
#endif
| mit | ca77e12b8c0a866ad7529eeaec29972a | 36.572464 | 117 | 0.67541 | 4.886899 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Noise Operations.xcplaygroundpage/Contents.swift | 2 | 503 | //: ## Noise Operations
//:
import XCPlayground
import AudioKit
let generator = AKOperationGenerator() { _ in
let white = AKOperation.whiteNoise()
let pink = AKOperation.pinkNoise()
let lfo = AKOperation.sineWave(frequency: 0.3)
let balance = lfo.scale(minimum: 0, maximum: 1)
let noise = mixer(white, pink, balance: balance)
return noise.pan(lfo)
}
AudioKit.output = generator
AudioKit.start()
generator.start()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
| mit | 8007f8c0f9fe6f879bf4e579b45e08d6 | 22.952381 | 60 | 0.725646 | 4.157025 | false | false | false | false |
apple/swift-format | Tests/SwiftFormatRulesTests/OneVariableDeclarationPerLineTests.swift | 1 | 5945 | import SwiftFormatRules
final class OneVariableDeclarationPerLineTests: LintOrFormatRuleTestCase {
func testMultipleVariableBindings() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
var a = 0, b = 2, (c, d) = (0, "h")
let e = 0, f = 2, (g, h) = (0, "h")
var x: Int { return 3 }
let a, b, c: Int
var j: Int, k: String, l: Float
""",
expected:
"""
var a = 0
var b = 2
var (c, d) = (0, "h")
let e = 0
let f = 2
let (g, h) = (0, "h")
var x: Int { return 3 }
let a: Int
let b: Int
let c: Int
var j: Int
var k: String
var l: Float
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 1, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 2, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 4, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 5, column: 1)
}
func testNestedVariableBindings() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
var x: Int = {
let y = 5, z = 10
return z
}()
func foo() {
let x = 4, y = 10
}
var x: Int {
let y = 5, z = 10
return z
}
var a: String = "foo" {
didSet {
let b, c: Bool
}
}
let
a: Int = {
let p = 10, q = 20
return p * q
}(),
b: Int = {
var s: Int, t: Double
return 20
}()
""",
expected:
"""
var x: Int = {
let y = 5
let z = 10
return z
}()
func foo() {
let x = 4
let y = 10
}
var x: Int {
let y = 5
let z = 10
return z
}
var a: String = "foo" {
didSet {
let b: Bool
let c: Bool
}
}
let
a: Int = {
let p = 10
let q = 20
return p * q
}()
let
b: Int = {
var s: Int
var t: Double
return 20
}()
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 2, column: 3)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 7, column: 3)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 11, column: 3)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 17, column: 5)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 21, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 23, column: 5)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 27, column: 5)
}
func testMixedInitializedAndTypedBindings() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
var a = 5, b: String
let c: Int, d = "d", e = "e", f: Double
""",
expected:
"""
var a = 5
var b: String
let c: Int
let d = "d"
let e = "e"
let f: Double
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 1, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 2, column: 1)
}
func testCommentPrecedingDeclIsNotRepeated() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
// Comment
let a, b, c: Int
""",
expected:
"""
// Comment
let a: Int
let b: Int
let c: Int
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 2, column: 1)
}
func testCommentsPrecedingBindingsAreKept() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
let /* a */ a, /* b */ b, /* c */ c: Int
""",
expected:
"""
let /* a */ a: Int
let /* b */ b: Int
let /* c */ c: Int
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 1, column: 1)
}
func testInvalidBindingsAreNotDestroyed() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
let a, b, c = 5
let d, e
let f, g, h: Int = 5
let a: Int, b, c = 5, d, e: Int
""",
expected:
"""
let a, b, c = 5
let d, e
let f, g, h: Int = 5
let a: Int
let b, c = 5
let d: Int
let e: Int
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 1, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 2, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 3, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 4, column: 1)
}
func testMultipleBindingsWithAccessorsAreCorrected() {
// Swift parses multiple bindings with accessors but forbids them at a later
// stage. That means that if the individual bindings would be correct in
// isolation then we can correct them, which is kind of nice.
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
var x: Int { return 10 }, y = "foo" { didSet { print("changed") } }
""",
expected:
"""
var x: Int { return 10 }
var y = "foo" { didSet { print("changed") } }
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 1, column: 1)
}
}
| apache-2.0 | 3d7a824ebedbc2efe0d199a207848a38 | 24.625 | 80 | 0.523129 | 4.61927 | false | false | false | false |
huang1988519/WechatArticles | WechatArticles/WechatArticles/Library/Timepiece/NSTimeInterval+Timepiece.swift | 6 | 1614 | //
// NSTimeInterval+Timepiece.swift
// Timepiece
//
// Created by Mattijs on 10/05/15.
// Copyright (c) 2015 Naoto Kaneko. All rights reserved.
//
import Foundation
/**
This extension is deprecated in 0.4.1 and will be obsoleted in 0.5.0.
The conversion of Duration into NSTimeInterval is performed under incorrect assumption that 1 month is always equal to 30 days.
Therefore, The comparison between Duration and NSTimeInterval is also incorrect.
*/
public func < (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs < rhs.interval
}
public func < (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval < rhs
}
public func > (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs > rhs.interval
}
public func > (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval > rhs
}
public func == (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs == rhs.interval
}
public func == (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval == rhs
}
public func >= (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs >= rhs.interval
}
public func >= (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval >= rhs
}
public func <= (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs <= rhs.interval
}
public func <= (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval <= rhs
}
public func != (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs != rhs.interval
}
public func != (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval != rhs
} | apache-2.0 | 71c4997a9df7dafd22f93c4d92bee747 | 24.234375 | 131 | 0.67658 | 3.788732 | false | false | false | false |
songzhw/2iOS | iOS_Swift/iOS_Swift/biz/basiclesson/BillCaculatorViewController.swift | 1 | 1323 | import UIKit
class BillCaculatorViewController: UIViewController {
@IBOutlet weak var tfTotal: UITextField!
@IBOutlet weak var lblSplit: UILabel!
weak var btnPrevSelected : UIButton? //让上一个selected的变为不可选. 是动态的. 所以不用IBOutlet
var percentage : Float = 0
var headcount : Int = 2
@IBAction func tipPressed(_ sender: UIButton) {
guard btnPrevSelected !== sender else {return}
btnPrevSelected?.isSelected = false
sender.isSelected = true
btnPrevSelected = sender
percentage = Float(sender.currentTitle!.dropLast())!/100 //去除"%"后再参与运算
}
@IBAction func splitPressed(_ sender: UIStepper) {
headcount = Int(sender.value)
lblSplit.text = String(headcount)
}
@IBAction func calculatePressed(_ sender: UIButton) {
self.performSegue(withIdentifier: "BillResult", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "BillResult" {
guard tfTotal.text != nil else {return}
let vc2 = segue.destination as! BillResultViewController
vc2.total = Float(tfTotal.text!)!
vc2.headcount = headcount
vc2.tipPercentage = percentage
print("totoal = \(vc2.total), head = \(headcount)")
}
}
}
| apache-2.0 | c69f6e49c802cad31f0caf120ec3e3d3 | 26.042553 | 79 | 0.674272 | 4.1 | false | false | false | false |
vamsirajendra/firefox-ios | Client/Frontend/Home/BookmarksPanel.swift | 2 | 14566 | /* 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 Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
let BookmarkStatusChangedNotification = "BookmarkStatusChangedNotification"
struct BookmarksPanelUX {
private static let BookmarkFolderHeaderViewChevronInset: CGFloat = 10
private static let BookmarkFolderChevronSize: CGFloat = 20
private static let BookmarkFolderChevronLineWidth: CGFloat = 4.0
private static let BookmarkFolderTextColor = UIColor(red: 92/255, green: 92/255, blue: 92/255, alpha: 1.0)
private static let BookmarkFolderTextFont = UIFont.systemFontOfSize(UIConstants.DefaultMediumFontSize, weight: UIFontWeightMedium)
}
class BookmarksPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
var source: BookmarksModel?
var parentFolders = [BookmarkFolder]()
var bookmarkFolder = BookmarkRoots.MobileFolderGUID
private let BookmarkFolderCellIdentifier = "BookmarkFolderIdentifier"
private let BookmarkFolderHeaderViewIdentifier = "BookmarkFolderHeaderIdentifier"
private lazy var defaultIcon: UIImage = {
return UIImage(named: "defaultFavicon")!
}()
init() {
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil)
self.tableView.registerClass(BookmarkFolderTableViewCell.self, forCellReuseIdentifier: BookmarkFolderCellIdentifier)
self.tableView.registerClass(BookmarkFolderTableViewHeader.self, forHeaderFooterViewReuseIdentifier: BookmarkFolderHeaderViewIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// if we've not already set a source for this panel fetch a new model
// otherwise just use the existing source to select a folder
guard let source = self.source else {
// Get all the bookmarks split by folders
profile.bookmarks.modelForFolder(bookmarkFolder).upon(onModelFetched)
return
}
source.selectFolder(bookmarkFolder).upon(onModelFetched)
}
func notificationReceived(notification: NSNotification) {
switch notification.name {
case NotificationFirefoxAccountChanged:
self.reloadData()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
private func onModelFetched(result: Maybe<BookmarksModel>) {
guard let model = result.successValue else {
self.onModelFailure(result.failureValue)
return
}
self.onNewModel(model)
}
private func onNewModel(model: BookmarksModel) {
self.source = model
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
private func onModelFailure(e: Any) {
log.error("Error: failed to get data: \(e)")
}
override func reloadData() {
self.source?.reloadData().upon(onModelFetched)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return source?.current.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let source = source, bookmark = source.current[indexPath.row] else { return super.tableView(tableView, cellForRowAtIndexPath: indexPath) }
let cell: UITableViewCell
if let _ = bookmark as? BookmarkFolder {
cell = tableView.dequeueReusableCellWithIdentifier(BookmarkFolderCellIdentifier, forIndexPath: indexPath)
} else {
cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
if let url = bookmark.favicon?.url.asURL where url.scheme == "asset" {
cell.imageView?.image = UIImage(named: url.host!)
} else {
cell.imageView?.setIcon(bookmark.favicon, withPlaceholder: self.defaultIcon)
}
}
switch (bookmark) {
case let item as BookmarkItem:
if item.title.isEmpty {
cell.textLabel?.text = item.url
} else {
cell.textLabel?.text = item.title
}
default:
// Bookmark folders don't have a good fallback if there's no title. :(
cell.textLabel?.text = bookmark.title
}
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? BookmarkFolderTableViewCell {
cell.textLabel?.font = BookmarksPanelUX.BookmarkFolderTextFont
}
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// Don't show a header for the root
if source == nil || parentFolders.isEmpty {
return nil
}
guard let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(BookmarkFolderHeaderViewIdentifier) as? BookmarkFolderTableViewHeader else { return nil }
// register as delegate to ensure we get notified when the user interacts with this header
if header.delegate == nil {
header.delegate = self
}
if parentFolders.count == 1 {
header.textLabel?.text = NSLocalizedString("Bookmarks", comment: "Panel accessibility label")
} else if let parentFolder = parentFolders.last {
header.textLabel?.text = parentFolder.title
}
return header
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Don't show a header for the root. If there's no root (i.e. source == nil), we'll also show no header.
if source == nil || parentFolders.isEmpty {
return 0
}
return SiteTableViewControllerUX.RowHeight
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? BookmarkFolderTableViewHeader {
// for some reason specifying the font in header view init is being ignored, so setting it here
header.textLabel?.font = BookmarksPanelUX.BookmarkFolderTextFont
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let source = source {
let bookmark = source.current[indexPath.row]
switch (bookmark) {
case let item as BookmarkItem:
homePanelDelegate?.homePanel(self, didSelectURL: NSURL(string: item.url)!, visitType: VisitType.Bookmark)
break
case let folder as BookmarkFolder:
let nextController = BookmarksPanel()
nextController.parentFolders = parentFolders + [source.current]
nextController.bookmarkFolder = folder.guid
nextController.source = source
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.navigationController?.pushViewController(nextController, animated: true)
break
default:
// Weird.
break // Just here until there's another executable statement (compiler requires one).
}
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if source == nil {
return .None
}
if source!.current.itemIsEditableAtIndex(indexPath.row) ?? false {
return .Delete
}
return .None
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
if source == nil {
return [AnyObject]()
}
let title = NSLocalizedString("Delete", tableName: "BookmarkPanel", comment: "Action button for deleting bookmarks in the bookmarks panel.")
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: title, handler: { (action, indexPath) in
if let bookmark = self.source?.current[indexPath.row] {
// Why the dispatches? Because we call success and failure on the DB
// queue, and so calling anything else that calls through to the DB will
// deadlock. This problem will go away when the bookmarks API switches to
// Deferred instead of using callbacks.
// TODO: it's now time for this.
self.profile.bookmarks.remove(bookmark).uponQueue(dispatch_get_main_queue()) { res in
if let err = res.failureValue {
self.onModelFailure(err)
return
}
dispatch_async(dispatch_get_main_queue()) {
self.source?.reloadData().upon {
guard let model = $0.successValue else {
self.onModelFailure($0.failureValue)
return
}
dispatch_async(dispatch_get_main_queue()) {
tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.source = model
tableView.endUpdates()
NSNotificationCenter.defaultCenter().postNotificationName(BookmarkStatusChangedNotification, object: bookmark, userInfo:["added":false])
}
}
}
}
}
})
return [delete]
}
}
private protocol BookmarkFolderTableViewHeaderDelegate {
func didSelectHeader()
}
extension BookmarksPanel: BookmarkFolderTableViewHeaderDelegate {
private func didSelectHeader() {
self.navigationController?.popViewControllerAnimated(true)
}
}
class BookmarkFolderTableViewCell: TwoLineTableViewCell {
private let ImageMargin: CGFloat = 12
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = SiteTableViewControllerUX.HeaderBackgroundColor
textLabel?.backgroundColor = UIColor.clearColor()
textLabel?.tintColor = BookmarksPanelUX.BookmarkFolderTextColor
textLabel?.font = BookmarksPanelUX.BookmarkFolderTextFont
imageView?.image = UIImage(named: "bookmarkFolder")
let chevron = ChevronView(direction: .Right)
chevron.tintColor = BookmarksPanelUX.BookmarkFolderTextColor
chevron.frame = CGRectMake(0, 0, BookmarksPanelUX.BookmarkFolderChevronSize, BookmarksPanelUX.BookmarkFolderChevronSize)
chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth
accessoryView = chevron
separatorInset = UIEdgeInsetsZero
}
override func layoutSubviews() {
super.layoutSubviews()
// doing this here as TwoLineTableViewCell changes the imageView frame in it's layoutSubviews and we have to make sure it is right
if let imageSize = imageView?.image?.size {
imageView?.frame = CGRectMake(ImageMargin, (frame.height - imageSize.width) / 2, imageSize.width, imageSize.height)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private class BookmarkFolderTableViewHeader : UITableViewHeaderFooterView {
var delegate: BookmarkFolderTableViewHeaderDelegate?
lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = UIConstants.HighlightBlue
return label
}()
lazy var chevron: ChevronView = {
let chevron = ChevronView(direction: .Left)
chevron.tintColor = UIConstants.HighlightBlue
chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth
return chevron
}()
override var textLabel: UILabel? {
return titleLabel
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
userInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "viewWasTapped:")
tapGestureRecognizer.numberOfTapsRequired = 1
addGestureRecognizer(tapGestureRecognizer)
contentView.addSubview(chevron)
contentView.addSubview(titleLabel)
chevron.snp_makeConstraints { make in
make.left.equalTo(contentView).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.centerY.equalTo(contentView)
make.size.equalTo(BookmarksPanelUX.BookmarkFolderChevronSize)
}
titleLabel.snp_makeConstraints { make in
make.left.equalTo(chevron.snp_right).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.right.equalTo(contentView).offset(-BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.centerY.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func viewWasTapped(gestureRecognizer: UITapGestureRecognizer) {
delegate?.didSelectHeader()
}
}
| mpl-2.0 | 2386e5cb7e56ca9c09e01a8cacba7406 | 39.573816 | 172 | 0.65852 | 5.935615 | false | false | false | false |
ObjectAlchemist/OOUIKit | Sources/_UIKitDelegate/UITableViewDelegate/ConfiguringRowsForTheTableView/UITableViewDelegateConfigurationPrinting.swift | 1 | 2423 | //
// UITableViewDelegateConfigurationPrinting.swift
// OOUIKit
//
// Created by Karsten Litsche on 04.11.17.
//
import UIKit
public final class UITableViewDelegateConfigurationPrinting: NSObject, UITableViewDelegate {
// MARK: - init
convenience override init() {
fatalError("Not supported!")
}
public init(_ decorated: UITableViewDelegate, filterKey: String = "") {
self.decorated = decorated
// add space if exist to separate following log
self.filterKey = filterKey.count == 0 ? "" : "\(filterKey) "
}
// MARK: - protocol: UITableViewDelegate
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
printUI("\(filterKey)table heightForRowAt (\(indexPath.section)-\(indexPath.row)) called")
return decorated.tableView?(tableView, heightForRowAt: indexPath) ?? UITableView.automaticDimension
}
public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
printUI("\(filterKey)table estimatedHeightForRowAt (\(indexPath.section)-\(indexPath.row)) called")
return decorated.tableView?(tableView, estimatedHeightForRowAt: indexPath) ?? UITableView.automaticDimension
}
public func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
printUI("\(filterKey)table indentationLevelForRowAt (\(indexPath.section)-\(indexPath.row)) called")
return decorated.tableView?(tableView, indentationLevelForRowAt: indexPath) ?? 1
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
printUI("\(filterKey)table willDisplayCellForRowAt (\(indexPath.section)-\(indexPath.row)) called")
decorated.tableView?(tableView, willDisplay: cell, forRowAt: indexPath)
}
public func tableView(_ tableView: UITableView, shouldSpringLoadRowAt indexPath: IndexPath, with context: UISpringLoadedInteractionContext) -> Bool {
printUI("\(filterKey)table shouldSpringLoadRowAt (\(indexPath.section)-\(indexPath.row)) called")
return decorated.tableView?(tableView, shouldSpringLoadRowAt: indexPath, with: context) ?? true
}
// MARK: - private
private let decorated: UITableViewDelegate
private let filterKey: String
}
| mit | d05862ced1105c71b9c6aceb6a6e2039 | 42.267857 | 153 | 0.708213 | 5.674473 | false | false | false | false |
martinomamic/CarBooking | CarBooking/Services/Booking/BookingService.swift | 1 | 1951 | //
// BookingService.swift
// CarBooking
//
// Created by Martino Mamic on 29/07/2017.
// Copyright © 2017 Martino Mamic. All rights reserved.
//
import UIKit
import Foundation
class BookingService: BookingsStoreProtocol {
private let service = WebService()
func createBooking(newBooking: Booking, completionHandler: @escaping (() throws -> Booking?) -> Void) {
var json = RequestDictionary()
json["carId"] = "\(newBooking.car.id)"
json["startDate"] = newBooking.startDate.fullDateFormat()
json["endDate"] = newBooking.endDate.fullDateFormat()
json["isExpired"] = "\(false)"
json["duration"] = "\(newBooking.duration)"
service.create(params: json, resource: BookingResources.newBooking) { (createdBooking, error, response) in
if let booking = createdBooking {
completionHandler { return booking }
} else {
print(error ?? "no error")
print(response ?? "no response")
}
}
}
func fetchBookings(completionHandler: @escaping (() throws -> [Booking]) -> Void) {
service.get(resource: BookingResources.allBookings) { (bookingsArray, error, response) in
if let bookings = bookingsArray {
print(bookings)
for b in bookings {
print(b)
}
completionHandler { return bookings }
}
}
}
func fetchBooking(id: String, completionHandler: @escaping (() throws -> Booking?) -> Void) {
service.get(resource: BookingResources.fetchBooking(id)) { (fetchedBooking, error, response) in
if let booking = fetchedBooking {
print(booking)
completionHandler { return booking }
} else {
print(error ?? "no error")
print(response ?? "no response")
}
}
}
}
| mit | 2921f39f178d3f2b93287ded1bb6152a | 35.111111 | 114 | 0.573846 | 4.767726 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/InsertLinkViewController.swift | 3 | 3701 | import UIKit
protocol InsertLinkViewControllerDelegate: AnyObject {
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didTapCloseButton button: UIBarButtonItem)
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didInsertLinkFor page: String, withLabel label: String?)
}
class InsertLinkViewController: UIViewController {
weak var delegate: InsertLinkViewControllerDelegate?
private var theme = Theme.standard
private let dataStore: MWKDataStore
typealias Link = SectionEditorWebViewMessagingController.Link
private let link: Link
private let siteURL: URL?
init(link: Link, siteURL: URL?, dataStore: MWKDataStore) {
self.link = link
self.siteURL = siteURL
self.dataStore = dataStore
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var closeButton: UIBarButtonItem = {
let closeButton = UIBarButtonItem.wmf_buttonType(.X, target: self, action: #selector(delegateCloseButtonTap(_:)))
closeButton.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
return closeButton
}()
private lazy var searchViewController: SearchViewController = {
let searchViewController = SearchViewController()
searchViewController.dataStore = dataStore
searchViewController.siteURL = siteURL
searchViewController.searchTerm = link.page
searchViewController.areRecentSearchesEnabled = false
searchViewController.shouldBecomeFirstResponder = true
searchViewController.dataStore = SessionSingleton.sharedInstance()?.dataStore
searchViewController.shouldShowCancelButton = false
searchViewController.delegate = self
searchViewController.delegatesSelection = true
searchViewController.showLanguageBar = false
searchViewController.search()
return searchViewController
}()
override func viewDidLoad() {
super.viewDidLoad()
title = CommonStrings.insertLinkTitle
navigationItem.leftBarButtonItem = closeButton
let navigationController = WMFThemeableNavigationController(rootViewController: searchViewController)
navigationController.isNavigationBarHidden = true
wmf_add(childController: navigationController, andConstrainToEdgesOfContainerView: view)
apply(theme: theme)
}
@objc private func delegateCloseButtonTap(_ sender: UIBarButtonItem) {
delegate?.insertLinkViewController(self, didTapCloseButton: sender)
}
override func accessibilityPerformEscape() -> Bool {
delegate?.insertLinkViewController(self, didTapCloseButton: closeButton)
return true
}
}
extension InsertLinkViewController: ArticleCollectionViewControllerDelegate {
func articleCollectionViewController(_ articleCollectionViewController: ArticleCollectionViewController, didSelectArticleWith articleURL: URL, at indexPath: IndexPath) {
guard let title = articleURL.wmf_title else {
return
}
delegate?.insertLinkViewController(self, didInsertLinkFor: title, withLabel: nil)
}
}
extension InsertLinkViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.inputAccessoryBackground
view.layer.shadowColor = theme.colors.shadow.cgColor
closeButton.tintColor = theme.colors.primaryText
searchViewController.apply(theme: theme)
}
}
| mit | 59a5504ecf4661e2e5a08da89b0b5076 | 40.58427 | 173 | 0.737909 | 6.283531 | false | false | false | false |
chrisjmendez/swift-exercises | Authentication/BasicDropBox/BasicDropBox/DropboxUtil.swift | 1 | 1637 | //
// DropboxUtil.swift
// BasicDropBox
//
// Created by Chris on 1/16/16.
// Copyright © 2016 Chris Mendez. All rights reserved.
//
// https://www.dropbox.com/developers/documentation/swift#tutorial
import UIKit
import SwiftyDropbox
protocol DropboxUtilDelegate {
func didAuthenticate(success:Bool)
}
class DropboxUtil {
let DROPBOX_FOLDER_PATH = "SwiftHero"
var client:DropboxClient?
var delegate:DropboxUtilDelegate? = nil
internal init(){
//super.init()
if let cli = Dropbox.authorizedClient {
client = cli
print("A")
delegate?.didAuthenticate(true)
print("B")
} else {
delegate?.didAuthenticate(false)
}
}
func getUserAccount(){
print("getUserAccount")
//A. Get the current user's account info
client?.users.getCurrentAccount().response({ (response, error) -> Void in
print("*** Get current account ***")
if error != nil {
print("Error:", error!)
}
if let account = response {
print("Hello \(account.name.givenName)!")
}
})
}
func listFolder(){
client?.files.listFolder(path: "./").response( { (response, error) -> Void in
print("*** List folder ***")
if let result = response {
print("Folder contents:")
for entry in result.entries {
print(entry.name)
}
} else {
print(error!)
}
})
}
} | mit | f3b3ad73e6c6788aa7ef9ad68c5b9dd6 | 24.578125 | 85 | 0.520782 | 4.728324 | false | false | false | false |
TieShanWang/KKAutoScrollView | KKAutoScrollView/KKAutoScrollView/KKAutoCollectionViewCell.swift | 1 | 1556 | //
// KKAutoCollectionViewCell.swift
// KKAutoScrollController
//
// Created by KING on 2017/1/4.
// Copyright © 2017年 KING. All rights reserved.
//
import UIKit
import Security
let KKAutoCollectionViewCellReuseID = "KKAutoCollectionViewCellReuseID"
class KKAutoCollectionViewCell: UICollectionViewCell {
var imageView: UIImageView!
var titleLabel: UILabel!
var downloadURL: String?
var model: KKAutoScrollViewModel?
override init(frame: CGRect) {
super.init(frame: frame)
self.imageView = UIImageView()
self.titleLabel = UILabel.init()
self.contentView.addSubview(self.titleLabel)
self.contentView.addSubview(self.imageView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func reloadData() {
if let m = self.model {
self.showData(m)
}
}
func showData(_ data: KKAutoScrollViewModel) {
self.model = data
let url = data.url
self.downloadURL = url
data.downModel { [weak self] (img) in
DispatchQueue.main.async {
self?.imageView.image = img
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.imageView.frame = self.contentView.bounds
}
}
| mit | 656d50ea77bcaa7dee3e853da2de1af4 | 19.986486 | 71 | 0.576304 | 4.838006 | false | false | false | false |
davedufresne/SwiftParsec | Sources/SwiftParsec/TokenParser.swift | 1 | 42546 | //==============================================================================
// TokenParser.swift
// SwiftParsec
//
// Created by David Dufresne on 2015-10-05.
// Copyright © 2015 David Dufresne. All rights reserved.
//
// A helper module to parse lexical elements (tokens). See the initializer for
// the `TokenParser` structure for a description of how to use it.
// Operator implementations for the `Message` type.
//==============================================================================
import func Foundation.pow
//==============================================================================
/// Types implementing this protocol hold lexical parsers.
public protocol TokenParser {
/// The state supplied by the user.
associatedtype UserState
/// Language definition parameterizing the lexer.
var languageDefinition: LanguageDefinition<UserState> { get }
/// This lexeme parser parses a legal identifier. Returns the identifier
/// string. This parser will fail on identifiers that are reserved words.
/// Legal identifier (start) characters and reserved words are defined in
/// the `LanguageDefinition` that is passed to the initializer of this token
/// parser. An `identifier` is treated as a single token using
/// `GenericParser.attempt`.
var identifier: GenericParser<String, UserState, String> { get }
/// The lexeme parser `reservedName(name)` parses `symbol(name)`, but it
/// also checks that the `name` is not a prefix of a valid identifier. A
/// _reserved_ word is treated as a single token using
/// `GenericParser.attempt`.
///
/// - parameter name: The reserved name to parse.
/// - returns: A parser returning nothing.
func reservedName(_ name: String) -> GenericParser<String, UserState, ()>
/// This lexeme parser parses a legal operator and returns the name of the
/// operator. This parser will fail on any operators that are reserved
/// operators. Legal operator (start) characters and reserved operators are
/// defined in the `LanguageDefinition` that is passed to the initializer of
/// this token parser. An 'operator' is treated as a single token using
/// `GenericParser.attempt`.
var legalOperator: GenericParser<String, UserState, String> { get }
/// The lexeme parser `reservedOperator(name)` parses `symbol(name)`, but it
/// also checks that the `name` is not a prefix of a valid operator. A
/// 'reservedOperator' is treated as a single token using
/// `GenericParser.attempt`.
///
/// - parameter name: The operator name.
/// - returns: A parser returning nothing.
func reservedOperator(
_ name: String
) -> GenericParser<String, UserState, ()>
/// This lexeme parser parses a single literal character and returns the
/// literal character value. This parser deals correctly with escape
/// sequences.
var characterLiteral: GenericParser<String, UserState, Character> { get }
/// This lexeme parser parses a literal string and returns the literal
/// string value. This parser deals correctly with escape sequences and
/// gaps.
var stringLiteral: GenericParser<String, UserState, String> { get }
/// This lexeme parser parses a natural number (a positive whole number) and
/// returns the value of the number. The number can be specified in
/// 'decimal', 'hexadecimal' or 'octal'.
var natural: GenericParser<String, UserState, Int> { get }
/// This lexeme parser parses an integer (a whole number). This parser is
/// like `natural` except that it can be prefixed with sign (i.e. "-" or
/// "+"). It returns the value of the number. The number can be specified in
/// 'decimal', 'hexadecimal' or 'octal'.
var integer: GenericParser<String, UserState, Int> { get }
/// This lexeme parser parses an integer (a whole number). It is like
/// `integer` except that it can parse bigger numbers. Returns the value of
/// the number as a `Double`.
var integerAsFloat: GenericParser<String, UserState, Double> { get }
/// This lexeme parser parses a floating point value and returns the value
/// of the number.
var float: GenericParser<String, UserState, Double> { get }
/// This lexeme parser parses either `integer` or a `float` and returns the
/// value of the number. This parser deals with any overlap in the grammar
/// rules for integers and floats.
var number: GenericParser<String, UserState, Either<Int, Double>> { get }
/// Parses a positive whole number in the decimal system. Returns the value
/// of the number.
static var decimal: GenericParser<String, UserState, Int> { get }
/// Parses a positive whole number in the hexadecimal system. The number
/// should be prefixed with "x" or "X". Returns the value of the number.
static var hexadecimal: GenericParser<String, UserState, Int> { get }
/// Parses a positive whole number in the octal system. The number should be
/// prefixed with "o" or "O". Returns the value of the number.
static var octal: GenericParser<String, UserState, Int> { get }
/// Lexeme parser `symbol(str)` parses `str` and skips trailing white space.
///
/// - parameter name: The name of the symbol to parse.
/// - returns: `name`.
func symbol(_ name: String) -> GenericParser<String, UserState, String>
/// `lexeme(parser)` first applies `parser` and than the `whiteSpace`
/// parser, returning the value of `parser`. Every lexical token (lexeme) is
/// defined using `lexeme`, this way every parse starts at a point without
/// white space. Parsers that use `lexeme` are called _lexeme_ parsers in
/// this document.
///
/// The only point where the 'whiteSpace' parser should be called explicitly
/// is the start of the main parser in order to skip any leading white
/// space.
///
/// let mainParser = sum <^> whiteSpace *> lexeme(digit) <* eof
///
/// - parameter parser: The parser to transform in a 'lexeme'.
/// - returns: The value of `parser`.
func lexeme<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result>
/// Parses any white space. White space consists of _zero_ or more
/// occurrences of a 'space', a line comment or a block (multiline) comment.
/// Block comments may be nested. How comments are started and ended is
/// defined in the `LanguageDefinition` that is passed to the initializer of
/// this token parser.
var whiteSpace: GenericParser<String, UserState, ()> { get }
/// Lexeme parser `parentheses(parser)` parses `parser` enclosed in
/// parentheses, returning the value of `parser`.
///
/// - parameter parser: The parser applied between the parentheses.
/// - returns: The value of `parser`.
func parentheses<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result>
/// Lexeme parser `braces(parser)` parses `parser` enclosed in braces "{"
/// and "}", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the braces.
/// - returns: The value of `parser`.
func braces<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result>
/// Lexeme parser `angles(parser)` parses `parser` enclosed in angle
/// brackets "<" and ">", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the angles.
/// - returns: The value of `parser`.
func angles<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result>
/// Lexeme parser `brackets(parser)` parses `parser` enclosed in brackets
/// "[" and "]", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the brackets.
/// - returns: The value of `parser`.
func brackets<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result>
/// Lexeme parser `semicolon` parses the character ";" and skips any
/// trailing white space. Returns the string ";".
var semicolon: GenericParser<String, UserState, String> { get }
/// Lexeme parser `comma` parses the character "," and skips any trailing
/// white space. Returns the string ",".
var comma: GenericParser<String, UserState, String> { get }
/// Lexeme parser `colon` parses the character ":" and skips any trailing
/// white space. Returns the string ":".
var colon: GenericParser<String, UserState, String> { get }
/// Lexeme parser `dot` parses the character "." and skips any trailing
/// white space. Returns the string ".".
var dot: GenericParser<String, UserState, String> { get }
/// Lexeme parser `semicolonSeperated(parser)` parses _zero_ or more
/// occurrences of `parser` separated by `semicolon`. Returns an array of
/// values returned by `parser`.
///
/// - parameter parser: The parser applied between semicolons.
/// - returns: An array of values returned by `parser`.
func semicolonSeparated<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]>
/// Lexeme parser `semicolonSeperated1(parser)` parses _one_ or more
/// occurrences of `parser` separated by `semicolon`. Returns an array of
/// values returned by `parser`.
///
/// - parameter parser: The parser applied between semicolons.
/// - returns: An array of values returned by `parser`.
func semicolonSeparated1<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]>
/// Lexeme parser `commaSeparated(parser)` parses _zero_ or more occurrences
/// of `parser` separated by `comma`. Returns an array of values returned by
/// `parser`.
///
/// - parameter parser: The parser applied between commas.
/// - returns: An array of values returned by `parser`.
func commaSeparated<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]>
/// Lexeme parser `commaSeparated1(parser)` parses _one_ or more occurrences
/// of `parser` separated by `comma`. Returns an array of values returned by
/// `parser`.
///
/// - parameter parser: The parser applied between commas.
/// - returns: An array of values returned by `parser`.
func commaSeparated1<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]>
}
// Default implementation of the methods of the `TokenParser` parser type.
extension TokenParser {
// Type aliases used internally to simplify the code.
typealias StrParser = GenericParser<String, UserState, String>
typealias CharacterParser = GenericParser<String, UserState, Character>
typealias IntParser = GenericParser<String, UserState, Int>
typealias DoubleParser = GenericParser<String, UserState, Double>
typealias IntDoubleParser =
GenericParser<String, UserState, Either<Int, Double>>
typealias VoidParser = GenericParser<String, UserState, ()>
//
// Identifiers & Reserved words
//
/// This lexeme parser parses a legal identifier. Returns the identifier
/// string. This parser will fail on identifiers that are reserved words.
/// Legal identifier (start) characters and reserved words are defined in
/// the `LanguageDefinition` that is passed to the initializer of this token
/// parser. An `identifier` is treated as a single token using
/// `GenericParser.attempt`.
public var identifier: GenericParser<String, UserState, String> {
let langDef = languageDefinition
let ident: StrParser = langDef.identifierStart >>- { char in
langDef.identifierLetter(char).many >>- { chars in
let cs = chars.prepending(char)
return GenericParser(result: String(cs))
}
} <?> LocalizedString("identifier")
let identCheck: StrParser = ident >>- { name in
let reservedNames: Set<String>
let n: String
if langDef.isCaseSensitive {
reservedNames = langDef.reservedNames
n = name
} else {
reservedNames = langDef.reservedNames.map { $0.lowercased() }
n = name.lowercased()
}
guard !reservedNames.contains(n) else {
let reservedWordMsg = LocalizedString("reserved word ")
return GenericParser.unexpected(reservedWordMsg + name)
}
return GenericParser(result: name)
}
return lexeme(identCheck.attempt)
}
/// The lexeme parser `reservedName(name)` parses `symbol(name)`, but it
/// also checks that the `name` is not a prefix of a valid identifier. A
/// _reserved_ word is treated as a single token using
/// `GenericParser.attempt`.
///
/// - parameter name: The reserved name to parse.
/// - returns: A parser returning nothing.
public func reservedName(
_ name: String
) -> GenericParser<String, UserState, ()> {
let lastChar = name.last!
let reserved = caseString(name) *>
languageDefinition.identifierLetter(lastChar).noOccurence <?>
LocalizedString("end of ") + name
return lexeme(reserved.attempt)
}
//
// Operators & reserved operators
//
/// This lexeme parser parses a legal operator and returns the name of the
/// operator. This parser will fail on any operators that are reserved
/// operators. Legal operator (start) characters and reserved operators are
/// defined in the `LanguageDefinition` that is passed to the initializer of
/// this token parser. An 'operator' is treated as a single token using
/// `GenericParser.attempt`.
public var legalOperator: GenericParser<String, UserState, String> {
let langDef = languageDefinition
let op: StrParser = langDef.operatorStart >>- { char in
langDef.operatorLetter.many >>- { chars in
let cs = chars.prepending(char)
return GenericParser(result: String(cs))
}
} <?> LocalizedString("operator")
let opCheck: StrParser = op >>- { name in
guard !langDef.reservedOperators.contains(name) else {
let reservedOperatorMsg = LocalizedString("reserved operator ")
return GenericParser.unexpected(reservedOperatorMsg + name)
}
return GenericParser(result: name)
}
return lexeme(opCheck.attempt)
}
/// The lexeme parser `reservedOperator(name)` parses `symbol(name)`, but it
/// also checks that the `name` is not a prefix of a valid operator. A
/// 'reservedOperator' is treated as a single token using
/// `GenericParser.attempt`.
///
/// - parameter name: The operator name.
/// - returns: A parser returning nothing.
public func reservedOperator(
_ name: String
) -> GenericParser<String, UserState, ()> {
let op = VoidParser.string(name) *>
languageDefinition.operatorLetter.noOccurence <?>
LocalizedString("end of ") + name
return lexeme(op.attempt)
}
//
// Characters & Strings
//
/// This lexeme parser parses a single literal character and returns the
/// literal character value. This parser deals correctly with escape
/// sequences.
public var characterLiteral: GenericParser<String, UserState, Character> {
let characterLetter = CharacterParser.satisfy { char in
char != "'" && char != "\\" && char != substituteCharacter
}
let defaultCharEscape = GenericParser.character("\\") *>
GenericTokenParser<UserState>.escapeCode
let characterEscape =
languageDefinition.characterEscape ?? defaultCharEscape
let character = characterLetter <|> characterEscape <?>
LocalizedString("literal character")
let quote = CharacterParser.character("'")
let endOfCharMsg = LocalizedString("end of character")
return lexeme(character.between(quote, quote <?> endOfCharMsg)) <?>
LocalizedString("character")
}
/// This lexeme parser parses a literal string and returns the literal
/// string value. This parser deals correctly with escape sequences and
/// gaps.
public var stringLiteral: GenericParser<String, UserState, String> {
let stringLetter = CharacterParser.satisfy { char in
char != "\"" && char != "\\" && char != substituteCharacter
}
let escapeGap: GenericParser<String, UserState, Character?> =
GenericParser.space.many1 *> GenericParser.character("\\") *>
GenericParser(result: nil) <?>
LocalizedString("end of string gap")
let escapeEmpty: GenericParser<String, UserState, Character?> =
GenericParser.character("&") *> GenericParser(result: nil)
let characterEscape: GenericParser<String, UserState, Character?> =
GenericParser.character("\\") *>
(escapeGap <|> escapeEmpty <|>
GenericTokenParser.escapeCode.map { $0 })
let stringEscape =
languageDefinition.characterEscape?.map { $0 } ?? characterEscape
let stringChar = stringLetter.map { $0 } <|> stringEscape
let doubleQuote = CharacterParser.character("\"")
let endOfStringMsg = LocalizedString("end of string")
let string = stringChar.many.between(
doubleQuote, doubleQuote <?> endOfStringMsg
)
let literalString = string.map({ str in
str.reduce("") { (acc, char) in
guard let c = char else { return acc }
return acc.appending(c)
}
}) <?> LocalizedString("literal string")
return lexeme(literalString)
}
//
// Numbers
//
/// This lexeme parser parses a natural number (a positive whole number) and
/// returns the value of the number. The number can be specified in
/// 'decimal', 'hexadecimal' or 'octal'.
public var natural: GenericParser<String, UserState, Int> {
return lexeme(GenericTokenParser.naturalNumber) <?>
LocalizedString("natural")
}
/// This lexeme parser parses an integer (a whole number). This parser is
/// like `natural` except that it can be prefixed with sign (i.e. "-" or
/// "+"). It returns the value of the number. The number can be specified in
/// 'decimal', 'hexadecimal' or 'octal'.
public var integer: GenericParser<String, UserState, Int> {
let int = lexeme(GenericTokenParser.sign()) >>- { f in
GenericTokenParser.naturalNumber >>- {
GenericParser(result: f($0))
}
}
return lexeme(int) <?> LocalizedString("integer")
}
/// This lexeme parser parses an integer (a whole number). It is like
/// `integer` except that it can parse bigger numbers. Returns the value of
/// the number as a `Double`.
public var integerAsFloat: GenericParser<String, UserState, Double> {
let hexaPrefix = CharacterParser.oneOf(hexadecimalPrefixes)
let hexa = hexaPrefix *> GenericTokenParser.doubleWithBase(
16,
parser: GenericParser.hexadecimalDigit
)
let octPrefix = CharacterParser.oneOf(octalPrefixes)
let oct = octPrefix *> GenericTokenParser.doubleWithBase(
8,
parser: GenericParser.octalDigit
)
let decDigit = CharacterParser.decimalDigit
let dec = GenericTokenParser.doubleWithBase(10, parser: decDigit)
let zeroNumber = (GenericParser.character("0") *>
(hexa <|> oct <|> dec <|> GenericParser(result: 0))) <?> ""
let nat = zeroNumber <|> dec
let double = lexeme(GenericTokenParser.sign()) >>- { sign in
nat >>- { GenericParser(result: sign($0)) }
}
return lexeme(double) <?> LocalizedString("integer")
}
/// This lexeme parser parses a floating point value and returns the value
/// of the number.
public var float: GenericParser<String, UserState, Double> {
let intPart = GenericTokenParser<UserState>.doubleIntegerPart
let expPart = GenericTokenParser<UserState>.fractionalExponent
let f = intPart >>- { expPart($0) }
let double = lexeme(GenericTokenParser.sign()) >>- { sign in
f >>- { GenericParser(result: sign($0)) }
}
return lexeme(double) <?> LocalizedString("float")
}
/// This lexeme parser parses either `integer` or a `float` and returns the
/// value of the number. This parser deals with any overlap in the grammar
/// rules for integers and floats.
public var number: GenericParser<String, UserState, Either<Int, Double>> {
let intDouble = float.map({ Either.right($0) }).attempt <|>
integer.map({ Either.left($0) })
return lexeme(intDouble) <?> LocalizedString("number")
}
/// Parses a positive whole number in the decimal system. Returns the value
/// of the number.
public static var decimal: GenericParser<String, UserState, Int> {
return numberWithBase(10, parser: GenericParser.decimalDigit)
}
/// Parses a positive whole number in the hexadecimal system. The number
/// should be prefixed with "x" or "X". Returns the value of the number.
public static var hexadecimal: GenericParser<String, UserState, Int> {
return GenericParser.oneOf(hexadecimalPrefixes) *>
numberWithBase(16, parser: GenericParser.hexadecimalDigit)
}
/// Parses a positive whole number in the octal system. The number should be
/// prefixed with "o" or "O". Returns the value of the number.
public static var octal: GenericParser<String, UserState, Int> {
return GenericParser.oneOf(octalPrefixes) *>
numberWithBase(8, parser: GenericParser.octalDigit)
}
//
// White space & symbols
//
/// Lexeme parser `symbol(str)` parses `str` and skips trailing white space.
///
/// - parameter name: The name of the symbol to parse.
/// - returns: `name`.
public func symbol(
_ name: String
) -> GenericParser<String, UserState, String> {
return lexeme(StrParser.string(name))
}
/// `lexeme(parser)` first applies `parser` and than the `whiteSpace`
/// parser, returning the value of `parser`. Every lexical token (lexeme) is
/// defined using `lexeme`, this way every parse starts at a point without
/// white space. Parsers that use `lexeme` are called _lexeme_ parsers in
/// this document.
///
/// The only point where the 'whiteSpace' parser should be called explicitly
/// is the start of the main parser in order to skip any leading white
/// space.
///
/// let mainParser = sum <^> whiteSpace *> lexeme(digit) <* eof
///
/// - parameter parser: The parser to transform in a 'lexeme'.
/// - returns: The value of `parser`.
public func lexeme<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result> {
return parser <* whiteSpace
}
/// Parses any white space. White space consists of _zero_ or more
/// occurrences of a 'space', a line comment or a block (multiline) comment.
/// Block comments may be nested. How comments are started and ended is
/// defined in the `LanguageDefinition` that is passed to the initializer of
/// this token parser.
public var whiteSpace: GenericParser<String, UserState, ()> {
let simpleSpace = CharacterParser.satisfy({ $0.isSpace }).skipMany1
let commentLineEmpty = languageDefinition.commentLine.isEmpty
let commentStartEmpty = languageDefinition.commentStart.isEmpty
if commentLineEmpty && commentStartEmpty {
return (simpleSpace <?> "").skipMany
}
if commentLineEmpty {
return (simpleSpace <|> multiLineComment <?> "").skipMany
}
if commentStartEmpty {
return (simpleSpace <|> oneLineComment <?> "").skipMany
}
return (
simpleSpace <|> oneLineComment <|> multiLineComment <?> ""
).skipMany
}
//
// Bracketing
//
/// Lexeme parser `parentheses(parser)` parses `parser` enclosed in
/// parentheses, returning the value of `parser`.
///
/// - parameter parser: The parser applied between the parentheses.
/// - returns: The value of `parser`.
public func parentheses<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result> {
return parser.between(symbol("("), symbol(")"))
}
/// Lexeme parser `braces(parser)` parses `parser` enclosed in braces "{"
/// and "}", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the braces.
/// - returns: The value of `parser`.
public func braces<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result> {
return parser.between(symbol("{"), symbol("}"))
}
/// Lexeme parser `angles(parser)` parses `parser` enclosed in angle
/// brackets "<" and ">", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the angles.
/// - returns: The value of `parser`.
public func angles<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result> {
return parser.between(symbol("<"), symbol(">"))
}
/// Lexeme parser `brackets(parser)` parses `parser` enclosed in brackets
/// "[" and "]", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the brackets.
/// - returns: The value of `parser`.
public func brackets<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result> {
return parser.between(symbol("["), symbol("]"))
}
/// Lexeme parser `semicolon` parses the character ";" and skips any
/// trailing white space. Returns the string ";".
public var semicolon: GenericParser<String, UserState, String> {
return symbol(";")
}
/// Lexeme parser `comma` parses the character "," and skips any trailing
/// white space. Returns the string ",".
public var comma: GenericParser<String, UserState, String> {
return symbol(",")
}
/// Lexeme parser `colon` parses the character ":" and skips any trailing
/// white space. Returns the string ":".
public var colon: GenericParser<String, UserState, String> {
return symbol(":")
}
/// Lexeme parser `dot` parses the character "." and skips any trailing
/// white space. Returns the string ".".
public var dot: GenericParser<String, UserState, String> {
return symbol(".")
}
/// Lexeme parser `semicolonSeperated(parser)` parses _zero_ or more
/// occurrences of `parser` separated by `semicolon`. Returns an array of
/// values returned by `parser`.
///
/// - parameter parser: The parser applied between semicolons.
/// - returns: An array of values returned by `parser`.
public func semicolonSeparated<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]> {
return parser.separatedBy(semicolon)
}
/// Lexeme parser `semicolonSeperated1(parser)` parses _one_ or more
/// occurrences of `parser` separated by `semicolon`. Returns an array of
/// values returned by `parser`.
///
/// - parameter parser: The parser applied between semicolons.
/// - returns: An array of values returned by `parser`.
public func semicolonSeparated1<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]> {
return parser.separatedBy1(semicolon)
}
/// Lexeme parser `commaSeparated(parser)` parses _zero_ or more occurrences
/// of `parser` separated by `comma`. Returns an array of values returned by
/// `parser`.
///
/// - parameter parser: The parser applied between commas.
/// - returns: An array of values returned by `parser`.
public func commaSeparated<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]> {
return parser.separatedBy(comma)
}
/// Lexeme parser `commaSeparated1(parser)` parses _one_ or more occurrences
/// of `parser` separated by `comma`. Returns an array of values returned by
/// `parser`.
///
/// - parameter parser: The parser applied between commas.
/// - returns: An array of values returned by `parser`.
public func commaSeparated1<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]> {
return parser.separatedBy1(comma)
}
//
// Private methods. They sould be in a separate private extension but it
// causes problems with the internal typealiases.
//
private var oneLineComment: VoidParser {
let commentStart = StrParser.string(languageDefinition.commentLine)
return commentStart.attempt *>
GenericParser.satisfy({ $0 != "\n"}).skipMany *>
GenericParser(result: ())
}
private var multiLineComment: VoidParser {
return GenericParser {
let commentStart =
StrParser.string(self.languageDefinition.commentStart)
return commentStart.attempt *> self.inComment
}
}
private var inComment: VoidParser {
return languageDefinition.allowNestedComments ?
inNestedComment : inNonNestedComment
}
private var inNestedComment: VoidParser {
return GenericParser {
let langDef = self.languageDefinition
let startEnd = (
langDef.commentStart + langDef.commentEnd
).removingDuplicates()
let commentEnd = StrParser.string(langDef.commentEnd)
return commentEnd.attempt *> GenericParser(result: ()) <|>
self.multiLineComment *> self.inNestedComment <|>
GenericParser.noneOf(String(startEnd)).skipMany1 *>
self.inNestedComment <|>
GenericParser.oneOf(String(startEnd)) *>
self.inNestedComment <?>
LocalizedString("end of comment")
}
}
private var inNonNestedComment: VoidParser {
return GenericParser {
let langDef = self.languageDefinition
let startEnd = (
langDef.commentStart + langDef.commentEnd
).removingDuplicates()
let commentEnd = StrParser.string(langDef.commentEnd)
return commentEnd.attempt *> GenericParser(result: ()) <|>
GenericParser.noneOf(String(startEnd)).skipMany1 *>
self.inNonNestedComment <|>
GenericParser.oneOf(String(startEnd)) *>
self.inNonNestedComment <?>
LocalizedString("end of comment")
}
}
private static var escapeCode: CharacterParser {
return charEscape <|> charNumber <|> charAscii <|> charControl <?>
LocalizedString("escape code")
}
private static var charEscape: CharacterParser {
let parsers = escapeMap.map { escCode in
CharacterParser.character(escCode.esc) *>
GenericParser(result: escCode.code)
}
return GenericParser.choice(parsers)
}
private static var charNumber: CharacterParser {
let octalDigit = CharacterParser.octalDigit
let hexaDigit = CharacterParser.hexadecimalDigit
let num = decimal <|>
GenericParser.character("o") *>
numberWithBase(8, parser: octalDigit) <|>
GenericParser.character("x") *>
numberWithBase(16, parser: hexaDigit)
return num >>- { characterFromInt($0) }
}
private static var charAscii: CharacterParser {
let parsers = asciiCodesMap.map { control in
StrParser.string(control.esc) *> GenericParser(result: control.code)
}
return GenericParser.choice(parsers)
}
private static var charControl: CharacterParser {
let upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let ctrlCodes: CharacterParser =
GenericParser.oneOf(upper).flatMap { char in
let charA: Character = "A"
let value = char.unicodeScalar.value -
charA.unicodeScalar.value + 1
let unicode = UnicodeScalar.fromUInt32(value)!
return GenericParser(result: Character(unicode))
}
return GenericParser.character("^") *> (ctrlCodes <|>
GenericParser.character("@") *> GenericParser(result: "\0") <|>
GenericParser.character("[") *>
GenericParser(result: "\u{001B}") <|>
GenericParser.character("]") *>
GenericParser(result: "\u{001C}") <|>
GenericParser.character("\\") *>
GenericParser(result: "\u{001D}") <|>
GenericParser.character("^") *>
GenericParser(result: "\u{001E}") <|>
GenericParser.character("_") *> GenericParser(result: "\u{001F}"))
}
static func characterFromInt(_ v: Int) -> CharacterParser {
guard let us = UnicodeScalar.fromInt(v) else {
let outsideMsg = LocalizedString(
"value outside of Unicode codespace"
)
return GenericParser.fail(outsideMsg)
}
return GenericParser(result: Character(us))
}
private static func numberWithBase(
_ base: Int,
parser: CharacterParser
) -> IntParser {
return parser.many1 >>- { digits in
return integerWithDigits(String(digits), base: base)
}
}
static func integerWithDigits(_ digits: String, base: Int) -> IntParser {
guard let integer = Int(digits, radix: base) else {
let overflowMsg = LocalizedString("Int overflow")
return GenericParser.fail(overflowMsg)
}
return GenericParser(result: integer)
}
private static func doubleWithBase(
_ base: Int,
parser: CharacterParser
) -> DoubleParser {
let baseDouble = Double(base)
return parser.many1 >>- { digits in
let double = digits.reduce(0.0) { acc, d in
baseDouble * acc + Double(Int(String(d), radix: base)!)
}
return GenericParser(result: double)
}
}
private static var doubleIntegerPart: DoubleParser {
return GenericParser.decimalDigit.many1 >>- { digits in
GenericParser(result: Double(String(digits))!)
}
}
private static var naturalNumber: IntParser {
let zeroNumber = GenericParser.character("0") *>
(hexadecimal <|> octal <|> decimal <|> GenericParser(result: 0))
<?> ""
return zeroNumber <|> decimal
}
private static func sign<Number: SignedNumeric>()
-> GenericParser<String, UserState, (Number) -> Number> {
return GenericParser.character("-") *> GenericParser(result: -) <|>
GenericParser.character("+") *> GenericParser(result: { $0 }) <|>
GenericParser(result: { $0 })
}
private static func fractionalExponent(_ number: Double) -> DoubleParser {
let fractionMsg = LocalizedString("fraction")
let fract = CharacterParser.character(".") *>
(GenericParser.decimalDigit.many1 <?> fractionMsg).map { digits in
digits.reduceRight(0) { frac, digit in
(frac + Double(String(digit))!) / 10
}
}
let exponentMsg = LocalizedString("exponent")
let expo = GenericParser.oneOf("eE") *> sign() >>- { sign in
(self.decimal <?> exponentMsg) >>- { exp in
GenericParser(result: power(sign(exp)))
}
}
let fraction = (fract <?> fractionMsg) >>- { frac in
(expo <?> exponentMsg).otherwise(1) >>- { exp in
return GenericParser(result: (number + frac) * exp)
}
}
let exponent = expo >>- { exp in
GenericParser(result: number * exp)
}
return fraction <|> exponent
}
private func caseString(_ name: String) -> StrParser {
if languageDefinition.isCaseSensitive {
return StrParser.string(name)
}
func walk(_ string: String) -> VoidParser {
let unit = VoidParser(result: ())
guard !string.isEmpty else { return unit }
var str = string
let c = str.remove(at: str.startIndex)
let charParser: VoidParser
if c.isAlpha {
charParser = (GenericParser.character(c.lowercase) <|>
GenericParser.character(c.uppercase)) *> unit
} else {
charParser = GenericParser.character(c) *> unit
}
return (charParser <?> name) >>- { _ in walk(str) }
}
return walk(name) *> GenericParser(result: name)
}
}
private let hexadecimalPrefixes = "xX"
private let octalPrefixes = "oO"
private let substituteCharacter: Character = "\u{001A}"
private let escapeMap: [(esc: Character, code: Character)] = [
("a", "\u{0007}"), ("b", "\u{0008}"), ("f", "\u{000C}"), ("n", "\n"),
("r", "\r"), ("t", "\t"), ("v", "\u{000B}"), ("\\", "\\"), ("\"", "\""),
("'", "'")
]
private let asciiCodesMap: [(esc: String, code:Character)] = [
("NUL", "\u{0000}"), ("SOH", "\u{0001}"), ("STX", "\u{0002}"),
("ETX", "\u{0003}"), ("EOT", "\u{0004}"), ("ENQ", "\u{0005}"),
("ACK", "\u{0006}"), ("BEL", "\u{0007}"), ("BS", "\u{0008}"),
("HT", "\u{0009}"), ("LF", "\u{000A}"), ("VT", "\u{000B}"),
("FF", "\u{000C}"), ("CR", "\u{000D}"), ("SO", "\u{000E}"),
("SI", "\u{000F}"), ("DLE", "\u{0010}"), ("DC1", "\u{0011}"),
("DC2", "\u{0012}"), ("DC3", "\u{0013}"), ("DC4", "\u{0014}"),
("NAK", "\u{0015}"), ("SYN", "\u{0016}"), ("ETB", "\u{0017}"),
("CAN", "\u{0018}"), ("EM", "\u{0019}"), ("SUB", "\u{001A}"),
("ESC", "\u{001B}"), ("FS", "\u{001C}"), ("GS", "\u{001D}"),
("RS", "\u{001E}"), ("US", "\u{001F}"), ("SP", "\u{0020}"),
("DEL", "\u{007F}")
]
private func power(_ exp: Int) -> Double {
if exp < 0 {
return 1.0 / power(-exp)
}
return pow(10.0, Double(exp))
}
| bsd-2-clause | 933a822fb970401a7e50138b26429faa | 35.177721 | 80 | 0.574639 | 5.18968 | false | false | false | false |
Brightify/Cuckoo | Source/CuckooFunctions.swift | 2 | 1683 | //
// CuckooFunctions.swift
// Cuckoo
//
// Created by Tadeas Kriz on 13/01/16.
// Copyright © 2016 Brightify. All rights reserved.
//
/// Starts the stubbing for the given mock. Can be used multiple times.
public func stub<M: Mock>(_ mock: M, block: (M.Stubbing) -> Void) {
block(mock.getStubbingProxy())
}
/// Used in stubbing. Currently only returns passed function but this may change in the future so it is not recommended to omit it.
// TODO: Uncomment the `: BaseStubFunctionTrait` before the next major release to improve API.
public func when<F/*: BaseStubFunctionTrait*/>(_ function: F) -> F {
return function
}
/// Creates object used for verification of calls.
public func verify<M: Mock>(_ mock: M, _ callMatcher: CallMatcher = times(1), file: StaticString = #file, line: UInt = #line) -> M.Verification {
return mock.getVerificationProxy(callMatcher, sourceLocation: (file, line))
}
/// Clears all invocations and stubs of mocks.
public func reset(_ mocks: HasMockManager...) {
mocks.forEach { mock in
mock.cuckoo_manager.reset()
}
}
/// Clears all stubs of mocks.
public func clearStubs<M: Mock>(_ mocks: M...) {
mocks.forEach { mock in
mock.cuckoo_manager.clearStubs()
}
}
/// Clears all invocations of mocks.
public func clearInvocations<M: Mock>(_ mocks: M...) {
mocks.forEach { mock in
mock.cuckoo_manager.clearInvocations()
}
}
/// Checks if there are no more uverified calls.
public func verifyNoMoreInteractions<M: Mock>(_ mocks: M..., file: StaticString = #file, line: UInt = #line) {
mocks.forEach { mock in
mock.cuckoo_manager.verifyNoMoreInteractions((file, line))
}
}
| mit | 559d5fdcd83ffd96b8775d2a9087ed5a | 31.980392 | 145 | 0.684899 | 3.814059 | false | false | false | false |
luinily/hOme | hOme/UI/SequencesViewController.swift | 1 | 3269 | //
// SequencesViewController.swift
// hOme
//
// Created by Coldefy Yoann on 2016/02/07.
// Copyright © 2016年 YoannColdefy. All rights reserved.
//
import Foundation
import UIKit
class SequencesViewController: UITableViewController, ApplicationUser {
@IBOutlet weak var sequencesTable: UITableView!
private let _sectionSequences = 0
private let _sectionNewSequence = 1
override func viewDidLoad() {
sequencesTable.delegate = self
sequencesTable.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let cell = sender as? SequenceCell,
let sequenceVC = segue.destination as? SequenceViewController {
if let sequence = cell.sequence {
sequenceVC.setSequence(sequence)
}
} else if let viewController = segue.destination as? UINavigationController {
if let newSequenceVC = viewController.visibleViewController as? NewSequenceViewController {
newSequenceVC.setOnDone(reloadData)
}
}
}
override func viewWillAppear(_ animated: Bool) {
reloadData()
}
private func ShowSequence(_ sequence: Sequence) {
performSegue(withIdentifier: "ShowSequenceSegue", sender: self)
}
private func reloadData() {
sequencesTable.reloadData()
}
//MARK: Table Data Source
//MARK: Sections
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == _sectionSequences {
return "Sequences"
}
return ""
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == _sectionSequences {
if let application = application {
return application.getSequenceCount()
}
} else if section == _sectionNewSequence {
return 1
}
return 0
}
//MARK: Cells
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = nil
if (indexPath as NSIndexPath).section == _sectionSequences {
cell = tableView.dequeueReusableCell(withIdentifier: "SequenceCell")
if let cell = cell as? SequenceCell,
let application = application {
cell.setSequence(application.getSequences()[(indexPath as NSIndexPath).row])
}
} else if (indexPath as NSIndexPath).section == _sectionNewSequence {
cell = tableView.dequeueReusableCell(withIdentifier: "NewSequenceCell")
}
if let cell = cell {
return cell
} else {
return UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "Cell")
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return (indexPath as NSIndexPath).section == _sectionSequences
}
// MARK: Table Delegate
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .destructive, title: "Delete") {
action, indexPath in
if let cell = tableView.cellForRow(at: indexPath) as? SequenceCell,
let application = self.application {
if let sequence = cell.sequence {
application.deleteSequence(sequence)
tableView.reloadData()
}
}
}
return [delete]
}
}
| mit | abc6edd8d5c135abe99fc8b22cb2c0c0 | 27.649123 | 121 | 0.72872 | 4.176471 | false | false | false | false |
angmu/SwiftPlayCode | 02-TableView演练/02-TableView演练/ViewController.swift | 1 | 2821 | //
// ViewController.swift
// 02-TableView演练
//
// Created by 穆良 on 2017/6/21.
// Copyright © 2017年 穆良. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private lazy var tableView: UITableView = {
// 实例化 指定样式
let tb = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
tb.dataSource = self
// 注册可重用cell [UITableViewCell class]
// 注册一个类
// tb.register(UITableViewCell.self , forCellReuseIdentifier: "CELL")
return tb
}()
// 纯代码创建视图层次结构 - 和 storyboard/xib 等价
override func loadView() {
// 在访问 view 时,如果view == nil, 会自动调用 loadView方法
// view没有创建 又来到这个方法 死循环
// print(view)
// view 就是tableView; tableViewController也是这么做的
view = tableView;
}
override func viewDidLoad() {
view.backgroundColor = UIColor.magenta
}
}
/// 将一组相关的代码放在一起, 便于阅读和维护
/// 遵守协议的写法 类似其他语言中 多继承
extension ViewController: UITableViewDataSource {
// 不实现直接报错
// UITableViewController 需要override已经遵守了协议,实现了方法
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 33;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 方式一: 必须注册可重用cell
// iOS6.0 出现indexPath 代替原始方法——>iOS7.0以后下面代码很少出现——>Swift中注册机制优势明显
// let cell = tableView.dequeueReusableCe÷ll(withIdentifier: "CELL", for: indexPath)
// cell.textLabel?.text = "hello \(indexPath.row)"
// return cell
// 方式二
// 最原始的方法,也可利用注册机制 不用判断了
// 不要求注册可重用的cell, 返回值有可能为空——可选的
var cell = tableView.dequeueReusableCell(withIdentifier: "CELL")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "CELL")
}
// cell? 可选更安全
cell?.textLabel?.text = "hello \(indexPath.row)"
return cell!
}
}
/*
### 思考问题
1. 创建tableView,frame参数怎么填?
- 注册cell怎么填写class类型?
- 怎样让view == tableView?
- 为什么会死循环
- 注册机制是怎样的
- 原始创建时,cell为什么要转来转去
- extension怎么用
- 为什么不用写override了?
- OC中没有多几继承, OC中用协议替代多线程
*/
| mit | 93362f4f03f6be444b4ddc0795014bbc | 24.147727 | 100 | 0.615906 | 3.657851 | false | false | false | false |
stripe/stripe-ios | Stripe/STPPaymentMethodParams+BasicUI.swift | 1 | 1584 | //
// STPPaymentMethodParams+BasicUI.swift
// StripeiOS
//
// Created by David Estes on 6/30/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripePaymentsUI
import UIKit
extension STPPaymentMethodParams: STPPaymentOption {
// MARK: - STPPaymentOption
@objc public var image: UIImage {
if type == .card && card != nil {
let brand = STPCardValidator.brand(forNumber: card?.number ?? "")
return STPImageLibrary.cardBrandImage(for: brand)
} else {
return STPImageLibrary.cardBrandImage(for: .unknown)
}
}
@objc public var templateImage: UIImage {
if type == .card && card != nil {
let brand = STPCardValidator.brand(forNumber: card?.number ?? "")
return STPImageLibrary.templatedBrandImage(for: brand)
} else if type == .FPX {
return STPImageLibrary.bankIcon()
} else {
return STPImageLibrary.templatedBrandImage(for: .unknown)
}
}
@objc public var isReusable: Bool {
switch type {
case .card, .link, .USBankAccount:
return true
case .alipay, .AUBECSDebit, .bacsDebit, .SEPADebit, .iDEAL, .FPX, .cardPresent, .giropay,
.grabPay, .EPS, .przelewy24, .bancontact, .netBanking, .OXXO, .payPal, .sofort, .UPI,
.afterpayClearpay, .blik, .weChatPay, .boleto, .klarna, .linkInstantDebit, .affirm,
.unknown:
return false
@unknown default:
return false
}
}
}
| mit | 81372b3355da6d167afb48f2c236425c | 31.979167 | 97 | 0.603917 | 4.007595 | false | false | false | false |
SweetzpotAS/TCXZpot-Swift | TCXZpot-SwiftTests/LapTest.swift | 1 | 3482 | //
// LapTest.swift
// TCXZpot
//
// Created by Tomás Ruiz López on 24/5/17.
// Copyright 2017 SweetZpot AS
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TCXZpot
class LapTest: XCTestCase {
func testSerializesCorrectly() {
let lap = Lap(startTime: TCXDate(day: 1, month: 1, year: 2017, hour: 0, minute: 0, second: 0)!,
totalTime: 125,
distance: 67,
maximumSpeed: 23,
calories: 200,
averageHeartRate: HeartRate(bpm: 92),
maximumHeartRate: HeartRate(bpm: 120),
intensity: Intensity.active,
cadence: Cadence(value: 10),
triggerMethod: TriggerMethod.manual,
tracks: Track(with: []),
notes: Notes(text: "Some notes"))
let serializer = MockSerializer()
lap.serialize(to: serializer)
XCTAssertTrue(serializer.hasPrinted("<Lap StartTime=\"2017-01-01T00:00:00.000Z\">"))
XCTAssertTrue(serializer.hasPrinted("<TotalTimeSeconds>125.0</TotalTimeSeconds>"))
XCTAssertTrue(serializer.hasPrinted("<DistanceMeters>67.0</DistanceMeters>"))
XCTAssertTrue(serializer.hasPrinted("<MaximumSpeed>23.0</MaximumSpeed>"))
XCTAssertTrue(serializer.hasPrinted("<Calories>200</Calories>"))
XCTAssertTrue(serializer.hasPrinted("<AverageHeartRateBpm>"))
XCTAssertTrue(serializer.hasPrinted("<MaximumHeartRateBpm>"))
XCTAssertTrue(serializer.hasPrinted("<Intensity>Active</Intensity>"))
XCTAssertTrue(serializer.hasPrinted("<Cadence>10</Cadence>"))
XCTAssertTrue(serializer.hasPrinted("<TriggerMethod>Manual</TriggerMethod>"))
XCTAssertTrue(serializer.hasPrinted("<Track>"))
XCTAssertTrue(serializer.hasPrinted("<Notes>Some notes</Notes>"))
XCTAssertTrue(serializer.hasPrinted("</Lap>"))
}
func testSerializesShortVersionCorrectly() {
let lap = Lap(startTime: TCXDate(day: 1, month: 1, year: 2017, hour: 0, minute: 0, second: 0)!,
totalTime: 125,
distance: 67,
calories: 200,
intensity: Intensity.active,
triggerMethod: TriggerMethod.manual,
tracks: nil)
let serializer = MockSerializer()
lap.serialize(to: serializer)
XCTAssertTrue(serializer.hasPrinted("<Lap StartTime=\"2017-01-01T00:00:00.000Z\">"))
XCTAssertTrue(serializer.hasPrinted("<TotalTimeSeconds>125.0</TotalTimeSeconds>"))
XCTAssertTrue(serializer.hasPrinted("<DistanceMeters>67.0</DistanceMeters>"))
XCTAssertTrue(serializer.hasPrinted("<Calories>200</Calories>"))
XCTAssertTrue(serializer.hasPrinted("<Intensity>Active</Intensity>"))
XCTAssertTrue(serializer.hasPrinted("<TriggerMethod>Manual</TriggerMethod>"))
XCTAssertTrue(serializer.hasPrinted("</Lap>"))
}
}
| apache-2.0 | d5ac8f3ecbeec6be70db0e497b62095b | 44.194805 | 103 | 0.653448 | 4.754098 | false | true | false | false |
brave/browser-ios | Storage/Cursor.swift | 28 | 2957 | /* 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
/**
* Status results for a Cursor
*/
public enum CursorStatus {
case success
case failure
case closed
}
public protocol TypedCursor: Sequence {
associatedtype T
var count: Int { get }
var status: CursorStatus { get }
var statusMessage: String { get }
subscript(index: Int) -> T? { get }
func asArray() -> [T]
}
/**
* Provides a generic method of returning some data and status information about a request.
*/
open class Cursor<T>: TypedCursor {
open var count: Int {
get { return 0 }
}
// Extra status information
open var status: CursorStatus
public var statusMessage: String
init(err: NSError) {
self.status = .failure
self.statusMessage = err.description
}
public init(status: CursorStatus = .success, msg: String = "") {
self.statusMessage = msg
self.status = status
}
// Collection iteration and access functions
open subscript(index: Int) -> T? {
get { return nil }
}
open func asArray() -> [T] {
var acc = [T]()
acc.reserveCapacity(self.count)
for row in self {
// Shouldn't ever be nil -- that's to allow the generator or subscript to be
// out of range.
if let row = row {
acc.append(row)
}
}
return acc
}
open func makeIterator() -> AnyIterator<T?> {
var nextIndex = 0
return AnyIterator() {
if nextIndex >= self.count || self.status != CursorStatus.success {
return nil
}
defer { nextIndex += 1 }
return self[nextIndex]
}
}
open func close() {
status = .closed
statusMessage = "Closed"
}
deinit {
if status != CursorStatus.closed {
close()
}
}
}
/*
* A cursor implementation that wraps an array.
*/
open class ArrayCursor<T> : Cursor<T> {
fileprivate var data: [T]
open override var count: Int {
if status != .success {
return 0
}
return data.count
}
public init(data: [T], status: CursorStatus, statusMessage: String) {
self.data = data
super.init(status: status, msg: statusMessage)
}
public convenience init(data: [T]) {
self.init(data: data, status: CursorStatus.success, statusMessage: "Success")
}
open override subscript(index: Int) -> T? {
get {
if index >= data.count || index < 0 || status != .success {
return nil
}
return data[index]
}
}
override open func close() {
data = [T]()
super.close()
}
}
| mpl-2.0 | 86d030b1f03d07dd36b09fdab5adaa06 | 22.846774 | 91 | 0.558336 | 4.361357 | false | false | false | false |
manavgabhawala/swift | test/SourceKit/NameTranslation/basic.swift | 5 | 4483 | import Foo
var derivedObj = FooClassDerived()
func foo1(_ a : FooClassDerived) {
_ = a.fooProperty1
_ = a.fooInstanceFunc0()
fooFunc3(1,1,1,nil)
}
func foo2 (_ a : FooClassDerived) {
a.fooBaseInstanceFuncOverridden()
a.fooInstanceFunc0()
a.fooInstanceFunc1(2)
a.fooInstanceFunc2(2, withB: 2)
_ = a.fooProperty1
_ = FooClassBase(float: 2.3)
_ = FooClassBase()
}
// REQUIRES: objc_interop
// RUN: %sourcekitd-test -req=translate -objc-name FooClassDerived2 -pos=5:30 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK1 %s
// RUN: %sourcekitd-test -req=translate -objc-selector FooClassDerived2 -pos=3:23 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK11 %s
// RUN: %sourcekitd-test -req=translate -objc-name fooProperty2 -pos=6:16 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK2 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc1 -pos=7:16 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK3 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooFunc3:d:d:d: -pos=8:4 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooBaseInstanceFuncOverridden1 -pos=12:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK4 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc01 -pos=13:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK5 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc11: -pos=14:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK6 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc2:withBB: -pos=15:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK7 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc21:withBB: -pos=15:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK8 %s
// RUN: %sourcekitd-test -req=translate -objc-name fooProperty11 -pos=16:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK9 %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc21:withBB:withC: -pos=15:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc21: -pos=15:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s
// RUN: %sourcekitd-test -req=translate -objc-selector fooInstanceFunc21: -pos=17:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK10 %s
// RUN: %sourcekitd-test -req=translate -objc-selector initWithfloat2: -pos=17:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK12 %s
// RUN: %sourcekitd-test -req=translate -objc-selector initWithfloat2:D: -pos=17:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s
// RUN: %sourcekitd-test -req=translate -objc-selector init: -pos=17:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK13 %s
// RUN: %sourcekitd-test -req=translate -objc-selector iit: -pos=17:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK13 %s
// RUN: %sourcekitd-test -req=translate -objc-selector init: -pos=18:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s
// RUN: %sourcekitd-test -req=translate -objc-selector NAME -pos=18:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK14 %s
// CHECK1: FooClassDerived2
// CHECK-NONE: <empty name translation info>
// CHECK2: fooProperty2
// CHECK3: fooInstanceFunc1
// CHECK4: fooBaseInstanceFuncOverridden1
// CHECK5: fooInstanceFunc01
// CHECK6: fooInstanceFunc11(_:)
// CHECK7: fooInstanceFunc2(_:withBB:)
// CHECK8: fooInstanceFunc21(_:withBB:)
// CHECK9: fooProperty11
// CHECK10: init(nstanceFunc21:)
// CHECK11: init(lassDerived2:)
// CHECK12: init(float2:)
// CHECK13: init(_:)
// CHECK14: init
| apache-2.0 | 614f738dfdfaeefa68708a365624c569 | 74.983051 | 198 | 0.691947 | 2.882958 | false | true | false | false |
material-components/material-components-ios | components/Buttons/examples/supplemental/ButtonsTypicalUseSupplemental.swift | 2 | 2057 | // Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import MaterialComponents.MaterialButtons
class ButtonsTypicalUseSupplemental: NSObject {
static let floatingButtonPlusDimension = CGFloat(24)
static func plusShapePath() -> UIBezierPath {
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 19, y: 13))
bezierPath.addLine(to: CGPoint(x: 13, y: 13))
bezierPath.addLine(to: CGPoint(x: 13, y: 19))
bezierPath.addLine(to: CGPoint(x: 11, y: 19))
bezierPath.addLine(to: CGPoint(x: 11, y: 13))
bezierPath.addLine(to: CGPoint(x: 5, y: 13))
bezierPath.addLine(to: CGPoint(x: 5, y: 11))
bezierPath.addLine(to: CGPoint(x: 11, y: 11))
bezierPath.addLine(to: CGPoint(x: 11, y: 5))
bezierPath.addLine(to: CGPoint(x: 13, y: 5))
bezierPath.addLine(to: CGPoint(x: 13, y: 11))
bezierPath.addLine(to: CGPoint(x: 19, y: 11))
bezierPath.addLine(to: CGPoint(x: 19, y: 13))
bezierPath.close()
return bezierPath
}
static func createPlusShapeLayer(_ floatingButton: MDCFloatingButton) -> CAShapeLayer {
let plusShape = CAShapeLayer()
plusShape.path = ButtonsTypicalUseSupplemental.plusShapePath().cgPath
plusShape.fillColor = UIColor.white.cgColor
plusShape.position =
CGPoint(
x: (floatingButton.frame.size.width - floatingButtonPlusDimension) / 2,
y: (floatingButton.frame.size.height - floatingButtonPlusDimension) / 2)
return plusShape
}
}
| apache-2.0 | 6d3bb3dc68add05909fc817becdd3368 | 38.557692 | 89 | 0.716091 | 3.895833 | false | false | false | false |
tuffz/pi-weather-app | Carthage/Checkouts/realm-cocoa/RealmSwift/Tests/ObjectCreationTests.swift | 1 | 53645 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm.Private
import RealmSwift
import Foundation
#if swift(>=3.0)
class ObjectCreationTests: TestCase {
// MARK: Init tests
func testInitWithDefaults() {
// test all properties are defaults
let object = SwiftObject()
XCTAssertNil(object.realm)
// test defaults values
verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false,
boolObjectListValues: [])
// test realm properties are nil for standalone
XCTAssertNil(object.realm)
XCTAssertNil(object.objectCol!.realm)
XCTAssertNil(object.arrayCol.realm)
}
func testInitWithOptionalWithoutDefaults() {
let object = SwiftOptionalObject()
for prop in object.objectSchema.properties {
let value = object[prop.name]
if let value = value as? RLMOptionalBase {
XCTAssertNil(value.underlyingValue)
} else {
XCTAssertNil(value)
}
}
}
func testInitWithOptionalDefaults() {
let object = SwiftOptionalDefaultValuesObject()
verifySwiftOptionalObjectWithDictionaryLiteral(object, dictionary:
SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true)
}
func testInitWithDictionary() {
// dictionary with all values specified
let baselineValues: [String: Any] =
["boolCol": true,
"intCol": 1,
"floatCol": 1.1 as Float,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 2),
"objectCol": SwiftBoolObject(value: [true]),
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()]
]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[props[propNum].name] = validValue
let object = SwiftObject(value: values)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[props[propNum].name] = invalidValue
assertThrows(SwiftObject(value: values), "Invalid property value")
}
}
}
func testInitWithDefaultsAndDictionary() {
// test with dictionary with mix of default and one specified value
let object = SwiftObject(value: ["intCol": 200])
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(object, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testInitWithArray() {
// array with all values specified
let baselineValues: [Any] = [true, 1, 1.1 as Float, 11.1, "b", "b".data(using: String.Encoding.utf8)!,
Date(timeIntervalSince1970: 2), ["boolCol": true], [[true], [false]]]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[propNum] = validValue
let object = SwiftObject(value: values)
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[propNum] = invalidValue
assertThrows(SwiftObject(value: values), "Invalid property value")
}
}
}
func testInitWithKVCObject() {
// test with kvc object
let objectWithInt = SwiftObject(value: ["intCol": 200])
let objectWithKVCObject = SwiftObject(value: objectWithInt)
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testGenericInit() {
func createObject<T: Object>() -> T {
return T()
}
let obj1: SwiftBoolObject = createObject()
let obj2 = SwiftBoolObject()
XCTAssertEqual(obj1.boolCol, obj2.boolCol,
"object created via generic initializer should equal object created by calling initializer directly")
}
// MARK: Creation tests
func testCreateWithDefaults() {
let realm = try! Realm()
assertThrows(realm.create(SwiftObject.self), "Must be in write transaction")
var object: SwiftObject!
let objects = realm.objects(SwiftObject.self)
XCTAssertEqual(0, objects.count)
try! realm.write {
// test create with all defaults
object = realm.create(SwiftObject.self)
return
}
verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false,
boolObjectListValues: [])
// test realm properties are populated correctly
XCTAssertEqual(object.realm!, realm)
XCTAssertEqual(object.objectCol!.realm!, realm)
XCTAssertEqual(object.arrayCol.realm!, realm)
}
func testCreateWithOptionalWithoutDefaults() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalObject.self)
for prop in object.objectSchema.properties {
XCTAssertNil(object[prop.name])
}
}
}
func testCreateWithOptionalDefaults() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalDefaultValuesObject.self)
self.verifySwiftOptionalObjectWithDictionaryLiteral(object,
dictionary: SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true)
}
}
func testCreateWithOptionalIgnoredProperties() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalIgnoredPropertiesObject.self)
let properties = object.objectSchema.properties
XCTAssertEqual(properties.count, 1)
XCTAssertEqual(properties[0].name, "id")
}
}
func testCreateWithDictionary() {
// dictionary with all values specified
let baselineValues: [String: Any] = [
"boolCol": true,
"intCol": 1,
"floatCol": 1.1 as Float,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 2),
"objectCol": SwiftBoolObject(value: [true]),
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()]
]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[props[propNum].name] = validValue
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: values)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
try! Realm().commitWrite()
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[props[propNum].name] = invalidValue
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftObject.self, value: values), "Invalid property value")
try! Realm().cancelWrite()
}
}
}
func testCreateWithDefaultsAndDictionary() {
// test with dictionary with mix of default and one specified value
let realm = try! Realm()
realm.beginWrite()
let objectWithInt = realm.create(SwiftObject.self, value: ["intCol": 200])
try! realm.commitWrite()
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(objectWithInt, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testCreateWithArray() {
// array with all values specified
let baselineValues: [Any] = [true, 1, 1.1 as Float, 11.1, "b", "b".data(using: String.Encoding.utf8)!,
Date(timeIntervalSince1970: 2), ["boolCol": true], [[true], [false]]]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[propNum] = validValue
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: values)
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
try! Realm().commitWrite()
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid array literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[propNum] = invalidValue
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftObject.self, value: values),
"Invalid property value '\(invalidValue)' for property number \(propNum)")
try! Realm().cancelWrite()
}
}
}
func testCreateWithKVCObject() {
// test with kvc object
try! Realm().beginWrite()
let objectWithInt = try! Realm().create(SwiftObject.self, value: ["intCol": 200])
let objectWithKVCObject = try! Realm().create(SwiftObject.self, value: objectWithInt)
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
try! Realm().commitWrite()
verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
XCTAssertEqual(try! Realm().objects(SwiftObject.self).count, 2, "Object should have been copied")
}
func testCreateWithNestedObjects() {
let standalone = SwiftPrimaryStringObject(value: ["p0", 11])
try! Realm().beginWrite()
let objectWithNestedObjects = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p1", ["p1", 11],
[standalone]])
try! Realm().commitWrite()
let stringObjects = try! Realm().objects(SwiftPrimaryStringObject.self)
XCTAssertEqual(stringObjects.count, 2)
let persistedObject = stringObjects.first!
// standalone object should be copied into the realm, not added directly
XCTAssertNotEqual(standalone, persistedObject)
XCTAssertEqual(objectWithNestedObjects.object!, persistedObject)
XCTAssertEqual(objectWithNestedObjects.objects.first!, stringObjects.last!)
let standalone1 = SwiftPrimaryStringObject(value: ["p3", 11])
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p3", ["p3", 11], [standalone1]]),
"Should throw with duplicate primary key")
try! Realm().commitWrite()
}
func testUpdateWithNestedObjects() {
let standalone = SwiftPrimaryStringObject(value: ["primary", 11])
try! Realm().beginWrite()
let object = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["otherPrimary", ["primary", 12],
[["primary", 12]]], update: true)
try! Realm().commitWrite()
let stringObjects = try! Realm().objects(SwiftPrimaryStringObject.self)
XCTAssertEqual(stringObjects.count, 1)
let persistedObject = object.object!
XCTAssertEqual(persistedObject.intCol, 12)
XCTAssertNil(standalone.realm) // the standalone object should be copied, rather than added, to the realm
XCTAssertEqual(object.object!, persistedObject)
XCTAssertEqual(object.objects.first!, persistedObject)
}
func testCreateWithObjectsFromAnotherRealm() {
let values: [String: Any] = [
"boolCol": true,
"intCol": 1,
"floatCol": 1.1 as Float,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 2),
"objectCol": SwiftBoolObject(value: [true]),
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()],
]
realmWithTestPath().beginWrite()
let otherRealmObject = realmWithTestPath().create(SwiftObject.self, value: values)
try! realmWithTestPath().commitWrite()
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: otherRealmObject)
try! Realm().commitWrite()
XCTAssertNotEqual(otherRealmObject, object)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
func testCreateWithDeeplyNestedObjectsFromAnotherRealm() {
let values: [String: Any] = [
"boolCol": true,
"intCol": 1,
"floatCol": 1.1 as Float,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 2),
"objectCol": SwiftBoolObject(value: [true]),
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()],
]
let realmA = realmWithTestPath()
let realmB = try! Realm()
var realmAObject: SwiftListOfSwiftObject!
try! realmA.write {
let array = [SwiftObject(value: values), SwiftObject(value: values)]
realmAObject = realmA.create(SwiftListOfSwiftObject.self, value: ["array": array])
}
var realmBObject: SwiftListOfSwiftObject!
try! realmB.write {
realmBObject = realmB.create(SwiftListOfSwiftObject.self, value: realmAObject)
}
XCTAssertNotEqual(realmAObject, realmBObject)
XCTAssertEqual(realmBObject.array.count, 2)
for swiftObject in realmBObject.array {
verifySwiftObjectWithDictionaryLiteral(swiftObject, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
func testUpdateWithObjectsFromAnotherRealm() {
realmWithTestPath().beginWrite()
let otherRealmObject = realmWithTestPath().create(SwiftLinkToPrimaryStringObject.self,
value: ["primary", NSNull(), [["2", 2], ["4", 4]]])
try! realmWithTestPath().commitWrite()
try! Realm().beginWrite()
try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["primary", ["10", 10], [["11", 11]]])
let object = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: otherRealmObject, update: true)
try! Realm().commitWrite()
XCTAssertNotEqual(otherRealmObject, object) // the object from the other realm should be copied into this realm
XCTAssertEqual(try! Realm().objects(SwiftLinkToPrimaryStringObject.self).count, 1)
XCTAssertEqual(try! Realm().objects(SwiftPrimaryStringObject.self).count, 4)
}
func testCreateWithNSNullLinks() {
let values: [String: Any] = [
"boolCol": true,
"intCol": 1,
"floatCol": 1.1,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 2),
"objectCol": NSNull(),
"arrayCol": NSNull(),
]
realmWithTestPath().beginWrite()
let object = realmWithTestPath().create(SwiftObject.self, value: values)
try! realmWithTestPath().commitWrite()
XCTAssert(object.objectCol == nil) // XCTAssertNil caused a NULL deref inside _swift_getClass
XCTAssertEqual(object.arrayCol.count, 0)
}
// test null object
// test null list
// MARK: Add tests
func testAddWithExisingNestedObjects() {
try! Realm().beginWrite()
let existingObject = try! Realm().create(SwiftBoolObject.self)
try! Realm().commitWrite()
try! Realm().beginWrite()
let object = SwiftObject(value: ["objectCol" : existingObject])
try! Realm().add(object)
try! Realm().commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertEqual(object.objectCol, existingObject)
}
func testAddAndUpdateWithExisingNestedObjects() {
try! Realm().beginWrite()
let existingObject = try! Realm().create(SwiftPrimaryStringObject.self, value: ["primary", 1])
try! Realm().commitWrite()
try! Realm().beginWrite()
let object = SwiftLinkToPrimaryStringObject(value: ["primary", ["primary", 2], []])
try! Realm().add(object, update: true)
try! Realm().commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertEqual(object.object!, existingObject) // the existing object should be updated
XCTAssertEqual(existingObject.intCol, 2)
}
// MARK: Private utilities
private func verifySwiftObjectWithArrayLiteral(_ object: SwiftObject, array: [Any], boolObjectValue: Bool,
boolObjectListValues: [Bool]) {
XCTAssertEqual(object.boolCol, (array[0] as! Bool))
XCTAssertEqual(object.intCol, (array[1] as! Int))
XCTAssertEqual(object.floatCol, (array[2] as! Float))
XCTAssertEqual(object.doubleCol, (array[3] as! Double))
XCTAssertEqual(object.stringCol, (array[4] as! String))
XCTAssertEqual(object.binaryCol, (array[5] as! Data))
XCTAssertEqual(object.dateCol, (array[6] as! Date))
XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue)
XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count)
for i in 0..<boolObjectListValues.count {
XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i])
}
}
private func verifySwiftObjectWithDictionaryLiteral(_ object: SwiftObject, dictionary: [String: Any],
boolObjectValue: Bool, boolObjectListValues: [Bool]) {
XCTAssertEqual(object.boolCol, (dictionary["boolCol"] as! Bool))
XCTAssertEqual(object.intCol, (dictionary["intCol"] as! Int))
XCTAssertEqual(object.floatCol, (dictionary["floatCol"] as! Float))
XCTAssertEqual(object.doubleCol, (dictionary["doubleCol"] as! Double))
XCTAssertEqual(object.stringCol, (dictionary["stringCol"] as! String))
XCTAssertEqual(object.binaryCol, (dictionary["binaryCol"] as! Data))
XCTAssertEqual(object.dateCol, (dictionary["dateCol"] as! Date))
XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue)
XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count)
for i in 0..<boolObjectListValues.count {
XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i])
}
}
private func verifySwiftOptionalObjectWithDictionaryLiteral(_ object: SwiftOptionalDefaultValuesObject,
dictionary: [String: Any],
boolObjectValue: Bool?) {
XCTAssertEqual(object.optBoolCol.value, (dictionary["optBoolCol"] as! Bool?))
XCTAssertEqual(object.optIntCol.value, (dictionary["optIntCol"] as! Int?))
XCTAssertEqual(object.optInt8Col.value,
((dictionary["optInt8Col"] as! NSNumber?)?.int8Value).map({Int8($0)}))
XCTAssertEqual(object.optInt16Col.value,
((dictionary["optInt16Col"] as! NSNumber?)?.int16Value).map({Int16($0)}))
XCTAssertEqual(object.optInt32Col.value,
((dictionary["optInt32Col"] as! NSNumber?)?.int32Value).map({Int32($0)}))
XCTAssertEqual(object.optInt64Col.value, (dictionary["optInt64Col"] as! NSNumber?)?.int64Value)
XCTAssertEqual(object.optFloatCol.value, (dictionary["optFloatCol"] as! Float?))
XCTAssertEqual(object.optDoubleCol.value, (dictionary["optDoubleCol"] as! Double?))
XCTAssertEqual(object.optStringCol, (dictionary["optStringCol"] as! String?))
XCTAssertEqual(object.optNSStringCol, (dictionary["optNSStringCol"] as! NSString))
XCTAssertEqual(object.optBinaryCol, (dictionary["optBinaryCol"] as! Data?))
XCTAssertEqual(object.optDateCol, (dictionary["optDateCol"] as! Date?))
XCTAssertEqual(object.optObjectCol?.boolCol, boolObjectValue)
}
private func defaultSwiftObjectValuesWithReplacements(_ replace: [String: Any]) -> [String: Any] {
var valueDict = SwiftObject.defaultValues()
for (key, value) in replace {
valueDict[key] = value
}
return valueDict
}
// return an array of valid values that can be used to initialize each type
// swiftlint:disable:next cyclomatic_complexity
private func validValuesForSwiftObjectType(_ type: PropertyType) -> [Any] {
try! Realm().beginWrite()
let persistedObject = try! Realm().create(SwiftBoolObject.self, value: [true])
try! Realm().commitWrite()
switch type {
case .bool: return [true, NSNumber(value: 0 as Int), NSNumber(value: 1 as Int)]
case .int: return [NSNumber(value: 1 as Int)]
case .float: return [NSNumber(value: 1 as Int), NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)]
case .double: return [NSNumber(value: 1 as Int), NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)]
case .string: return ["b"]
case .data: return ["b".data(using: String.Encoding.utf8, allowLossyConversion: false)!]
case .date: return [Date(timeIntervalSince1970: 2)]
case .object: return [[true], ["boolCol": true], SwiftBoolObject(value: [true]), persistedObject]
case .array: return [
[[true], [false]],
[["boolCol": true], ["boolCol": false]],
[SwiftBoolObject(value: [true]), SwiftBoolObject(value: [false])],
[persistedObject, [false]]
]
case .any: XCTFail("not supported")
case .linkingObjects: XCTFail("not supported")
}
return []
}
// swiftlint:disable:next cyclomatic_complexity
private func invalidValuesForSwiftObjectType(_ type: PropertyType) -> [Any] {
try! Realm().beginWrite()
let persistedObject = try! Realm().create(SwiftIntObject.self)
try! Realm().commitWrite()
switch type {
case .bool: return ["invalid", NSNumber(value: 2 as Int), NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)]
case .int: return ["invalid", NSNumber(value: 1.1 as Float), NSNumber(value: 11.1 as Double)]
case .float: return ["invalid", true, false]
case .double: return ["invalid", true, false]
case .string: return [0x197A71D, true, false]
case .data: return ["invalid"]
case .date: return ["invalid"]
case .object: return ["invalid", ["a"], ["boolCol": "a"], SwiftIntObject()]
case .array: return ["invalid", [["a"]], [["boolCol" : "a"]], [[SwiftIntObject()]], [[persistedObject]]]
case .any: XCTFail("not supported")
case .linkingObjects: XCTFail("not supported")
}
return []
}
}
#else
class ObjectCreationTests: TestCase {
// MARK: Init tests
func testInitWithDefaults() {
// test all properties are defaults
let object = SwiftObject()
XCTAssertNil(object.realm)
// test defaults values
verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false,
boolObjectListValues: [])
// ensure realm properties are nil for unmanaged object
XCTAssertNil(object.realm)
XCTAssertNil(object.objectCol!.realm)
XCTAssertNil(object.arrayCol.realm)
}
func testInitWithOptionalWithoutDefaults() {
let object = SwiftOptionalObject()
for prop in object.objectSchema.properties {
let value = object[prop.name]
if let value = value as? RLMOptionalBase {
XCTAssertNil(value.underlyingValue)
} else {
XCTAssertNil(value)
}
}
}
func testInitWithOptionalDefaults() {
let object = SwiftOptionalDefaultValuesObject()
verifySwiftOptionalObjectWithDictionaryLiteral(object, dictionary:
SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true)
}
func testInitWithDictionary() {
// dictionary with all values specified
let baselineValues =
["boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": SwiftBoolObject(value: [true]) as AnyObject,
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject
]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[props[propNum].name] = validValue
let object = SwiftObject(value: values)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[props[propNum].name] = invalidValue
assertThrows(SwiftObject(value: values), "Invalid property value")
}
}
}
func testInitWithDefaultsAndDictionary() {
// test with dictionary with mix of default and one specified value
let object = SwiftObject(value: ["intCol": 200])
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(object, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testInitWithArray() {
// array with all values specified
let baselineValues = [true, 1, 1.1, 11.1, "b", "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
NSDate(timeIntervalSince1970: 2) as NSDate, ["boolCol": true], [[true], [false]]] as [AnyObject]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[propNum] = validValue
let object = SwiftObject(value: values)
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[propNum] = invalidValue
assertThrows(SwiftObject(value: values), "Invalid property value")
}
}
}
func testInitWithKVCObject() {
// test with kvc object
let objectWithInt = SwiftObject(value: ["intCol": 200])
let objectWithKVCObject = SwiftObject(value: objectWithInt)
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testGenericInit() {
func createObject<T: Object>() -> T {
return T()
}
let obj1: SwiftBoolObject = createObject()
let obj2 = SwiftBoolObject()
XCTAssertEqual(obj1.boolCol, obj2.boolCol,
"object created via generic initializer should equal object created by calling initializer directly")
}
// MARK: Creation tests
func testCreateWithDefaults() {
let realm = try! Realm()
assertThrows(realm.create(SwiftObject), "Must be in write transaction")
var object: SwiftObject!
let objects = realm.objects(SwiftObject.self)
XCTAssertEqual(0, objects.count)
try! realm.write {
// test create with all defaults
object = realm.create(SwiftObject)
return
}
verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false,
boolObjectListValues: [])
// test realm properties are populated correctly
XCTAssertEqual(object.realm!, realm)
XCTAssertEqual(object.objectCol!.realm!, realm)
XCTAssertEqual(object.arrayCol.realm!, realm)
}
func testCreateWithOptionalWithoutDefaults() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalObject)
for prop in object.objectSchema.properties {
XCTAssertNil(object[prop.name])
}
}
}
func testCreateWithOptionalDefaults() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalDefaultValuesObject)
self.verifySwiftOptionalObjectWithDictionaryLiteral(object,
dictionary: SwiftOptionalDefaultValuesObject.defaultValues(), boolObjectValue: true)
}
}
func testCreateWithOptionalIgnoredProperties() {
let realm = try! Realm()
try! realm.write {
let object = realm.create(SwiftOptionalIgnoredPropertiesObject)
let properties = object.objectSchema.properties
XCTAssertEqual(properties.count, 1)
XCTAssertEqual(properties[0].name, "id")
}
}
func testCreateWithDictionary() {
// dictionary with all values specified
let baselineValues: [String: AnyObject] = [
"boolCol": true,
"intCol": 1,
"floatCol": 1.1,
"doubleCol": 11.1,
"stringCol": "b",
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)!,
"dateCol": NSDate(timeIntervalSince1970: 2),
"objectCol": SwiftBoolObject(value: [true]),
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()]
]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[props[propNum].name] = validValue
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: values)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
try! Realm().commitWrite()
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid dictionary literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[props[propNum].name] = invalidValue
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftObject.self, value: values), "Invalid property value")
try! Realm().cancelWrite()
}
}
}
func testCreateWithDefaultsAndDictionary() {
// test with dictionary with mix of default and one specified value
let realm = try! Realm()
realm.beginWrite()
let objectWithInt = realm.create(SwiftObject.self, value: ["intCol": 200])
try! realm.commitWrite()
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
verifySwiftObjectWithDictionaryLiteral(objectWithInt, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
}
func testCreateWithArray() {
// array with all values specified
let baselineValues = [true, 1, 1.1, 11.1, "b", "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
NSDate(timeIntervalSince1970: 2) as NSDate, ["boolCol": true], [[true], [false]]] as [AnyObject]
// test with valid dictionary literals
let props = try! Realm().schema["SwiftObject"]!.properties
for propNum in 0..<props.count {
for validValue in validValuesForSwiftObjectType(props[propNum].type) {
// update dict with valid value and init
var values = baselineValues
values[propNum] = validValue
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: values)
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
try! Realm().commitWrite()
verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
// test with invalid array literals
for propNum in 0..<props.count {
for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) {
// update dict with invalid value and init
var values = baselineValues
values[propNum] = invalidValue
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftObject.self, value: values),
"Invalid property value '\(invalidValue)' for property number \(propNum)")
try! Realm().cancelWrite()
}
}
}
func testCreateWithKVCObject() {
// test with kvc object
try! Realm().beginWrite()
let objectWithInt = try! Realm().create(SwiftObject.self, value: ["intCol": 200])
let objectWithKVCObject = try! Realm().create(SwiftObject.self, value: objectWithInt)
let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200])
try! Realm().commitWrite()
verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false,
boolObjectListValues: [])
XCTAssertEqual(try! Realm().objects(SwiftObject.self).count, 2, "Object should have been copied")
}
func testCreateWithNestedObjects() {
let unmanaged = SwiftPrimaryStringObject(value: ["p0", 11])
try! Realm().beginWrite()
let objectWithNestedObjects = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p1", ["p1", 11],
[unmanaged]])
try! Realm().commitWrite()
let stringObjects = try! Realm().objects(SwiftPrimaryStringObject.self)
XCTAssertEqual(stringObjects.count, 2)
let managedObject = stringObjects.first!
// unmanaged object should be copied into the Realm, not added directly
XCTAssertNotEqual(unmanaged, managedObject)
XCTAssertEqual(objectWithNestedObjects.object!, managedObject)
XCTAssertEqual(objectWithNestedObjects.objects.first!, stringObjects.last!)
let unmanaged1 = SwiftPrimaryStringObject(value: ["p3", 11])
try! Realm().beginWrite()
assertThrows(try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p3", ["p3", 11], [unmanaged1]]),
"Should throw with duplicate primary key")
try! Realm().commitWrite()
}
func testUpdateWithNestedObjects() {
let unmanaged = SwiftPrimaryStringObject(value: ["primary", 11])
try! Realm().beginWrite()
let object = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["otherPrimary", ["primary", 12],
[["primary", 12]]], update: true)
try! Realm().commitWrite()
let stringObjects = try! Realm().objects(SwiftPrimaryStringObject.self)
XCTAssertEqual(stringObjects.count, 1)
let managedObject = object.object!
XCTAssertEqual(managedObject.intCol, 12)
XCTAssertNil(unmanaged.realm) // the unmanaged object should be copied, rather than added, to the realm
XCTAssertEqual(object.object!, managedObject)
XCTAssertEqual(object.objects.first!, managedObject)
}
func testCreateWithObjectsFromAnotherRealm() {
let values = [
"boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": SwiftBoolObject(value: [true]) as AnyObject,
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject,
]
realmWithTestPath().beginWrite()
let otherRealmObject = realmWithTestPath().create(SwiftObject.self, value: values)
try! realmWithTestPath().commitWrite()
try! Realm().beginWrite()
let object = try! Realm().create(SwiftObject.self, value: otherRealmObject)
try! Realm().commitWrite()
XCTAssertNotEqual(otherRealmObject, object)
verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
func testCreateWithDeeplyNestedObjectsFromAnotherRealm() {
let values = [
"boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": SwiftBoolObject(value: [true]) as AnyObject,
"arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject,
]
let realmA = realmWithTestPath()
let realmB = try! Realm()
var realmAObject: SwiftListOfSwiftObject!
try! realmA.write {
let array = [SwiftObject(value: values), SwiftObject(value: values)]
realmAObject = realmA.create(SwiftListOfSwiftObject.self, value: ["array": array])
}
var realmBObject: SwiftListOfSwiftObject!
try! realmB.write {
realmBObject = realmB.create(SwiftListOfSwiftObject.self, value: realmAObject)
}
XCTAssertNotEqual(realmAObject, realmBObject)
XCTAssertEqual(realmBObject.array.count, 2)
for swiftObject in realmBObject.array {
verifySwiftObjectWithDictionaryLiteral(swiftObject, dictionary: values, boolObjectValue: true,
boolObjectListValues: [true, false])
}
}
func testUpdateWithObjectsFromAnotherRealm() {
realmWithTestPath().beginWrite()
let otherRealmObject = realmWithTestPath().create(SwiftLinkToPrimaryStringObject.self,
value: ["primary", NSNull(), [["2", 2], ["4", 4]]])
try! realmWithTestPath().commitWrite()
try! Realm().beginWrite()
try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["primary", ["10", 10], [["11", 11]]])
let object = try! Realm().create(SwiftLinkToPrimaryStringObject.self, value: otherRealmObject, update: true)
try! Realm().commitWrite()
XCTAssertNotEqual(otherRealmObject, object) // the object from the other realm should be copied into this realm
XCTAssertEqual(try! Realm().objects(SwiftLinkToPrimaryStringObject.self).count, 1)
XCTAssertEqual(try! Realm().objects(SwiftPrimaryStringObject.self).count, 4)
}
func testCreateWithNSNullLinks() {
let values = [
"boolCol": true as NSNumber,
"intCol": 1 as NSNumber,
"floatCol": 1.1 as NSNumber,
"doubleCol": 11.1 as NSNumber,
"stringCol": "b" as NSString,
"binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 2) as NSDate,
"objectCol": NSNull(),
"arrayCol": NSNull(),
]
realmWithTestPath().beginWrite()
let object = realmWithTestPath().create(SwiftObject.self, value: values)
try! realmWithTestPath().commitWrite()
XCTAssert(object.objectCol == nil) // XCTAssertNil caused a NULL deref inside _swift_getClass
XCTAssertEqual(object.arrayCol.count, 0)
}
// test null object
// test null list
// MARK: Add tests
func testAddWithExisingNestedObjects() {
try! Realm().beginWrite()
let existingObject = try! Realm().create(SwiftBoolObject)
try! Realm().commitWrite()
try! Realm().beginWrite()
let object = SwiftObject(value: ["objectCol" : existingObject])
try! Realm().add(object)
try! Realm().commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertEqual(object.objectCol, existingObject)
}
func testAddAndUpdateWithExisingNestedObjects() {
try! Realm().beginWrite()
let existingObject = try! Realm().create(SwiftPrimaryStringObject.self, value: ["primary", 1])
try! Realm().commitWrite()
try! Realm().beginWrite()
let object = SwiftLinkToPrimaryStringObject(value: ["primary", ["primary", 2], []])
try! Realm().add(object, update: true)
try! Realm().commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertEqual(object.object!, existingObject) // the existing object should be updated
XCTAssertEqual(existingObject.intCol, 2)
}
func testAddWithNumericOptionalPrimaryKeyProperty() {
let realm = try! Realm()
realm.beginWrite()
let object = SwiftPrimaryOptionalIntObject()
object.intCol.value = 1
realm.add(object, update: true)
let nilObject = SwiftPrimaryOptionalIntObject()
nilObject.intCol.value = nil
realm.add(nilObject, update: true)
try! realm.commitWrite()
XCTAssertNotNil(object.realm)
XCTAssertNotNil(nilObject.realm)
}
// MARK: Private utilities
private func verifySwiftObjectWithArrayLiteral(object: SwiftObject, array: [AnyObject], boolObjectValue: Bool,
boolObjectListValues: [Bool]) {
XCTAssertEqual(object.boolCol, (array[0] as! Bool))
XCTAssertEqual(object.intCol, (array[1] as! Int))
XCTAssertEqual(object.floatCol, (array[2] as! Float))
XCTAssertEqual(object.doubleCol, (array[3] as! Double))
XCTAssertEqual(object.stringCol, (array[4] as! String))
XCTAssertEqual(object.binaryCol, (array[5] as! NSData))
XCTAssertEqual(object.dateCol, (array[6] as! NSDate))
XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue)
XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count)
for i in 0..<boolObjectListValues.count {
XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i])
}
}
private func verifySwiftObjectWithDictionaryLiteral(object: SwiftObject, dictionary: [String:AnyObject],
boolObjectValue: Bool, boolObjectListValues: [Bool]) {
XCTAssertEqual(object.boolCol, (dictionary["boolCol"] as! Bool))
XCTAssertEqual(object.intCol, (dictionary["intCol"] as! Int))
XCTAssertEqual(object.floatCol, (dictionary["floatCol"] as! Float))
XCTAssertEqual(object.doubleCol, (dictionary["doubleCol"] as! Double))
XCTAssertEqual(object.stringCol, (dictionary["stringCol"] as! String))
XCTAssertEqual(object.binaryCol, (dictionary["binaryCol"] as! NSData))
XCTAssertEqual(object.dateCol, (dictionary["dateCol"] as! NSDate))
XCTAssertEqual(object.objectCol!.boolCol, boolObjectValue)
XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count)
for i in 0..<boolObjectListValues.count {
XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i])
}
}
private func verifySwiftOptionalObjectWithDictionaryLiteral(object: SwiftOptionalDefaultValuesObject,
dictionary: [String:AnyObject],
boolObjectValue: Bool?) {
XCTAssertEqual(object.optBoolCol.value, (dictionary["optBoolCol"] as! Bool?))
XCTAssertEqual(object.optIntCol.value, (dictionary["optIntCol"] as! Int?))
XCTAssertEqual(object.optInt8Col.value,
((dictionary["optInt8Col"] as! NSNumber?)?.longValue).map({Int8($0)}))
XCTAssertEqual(object.optInt16Col.value,
((dictionary["optInt16Col"] as! NSNumber?)?.longValue).map({Int16($0)}))
XCTAssertEqual(object.optInt32Col.value,
((dictionary["optInt32Col"] as! NSNumber?)?.longValue).map({Int32($0)}))
XCTAssertEqual(object.optInt64Col.value, (dictionary["optInt64Col"] as! NSNumber?)?.longLongValue)
XCTAssertEqual(object.optFloatCol.value, (dictionary["optFloatCol"] as! Float?))
XCTAssertEqual(object.optDoubleCol.value, (dictionary["optDoubleCol"] as! Double?))
XCTAssertEqual(object.optStringCol, (dictionary["optStringCol"] as! String?))
XCTAssertEqual(object.optNSStringCol, (dictionary["optNSStringCol"] as! String?))
XCTAssertEqual(object.optBinaryCol, (dictionary["optBinaryCol"] as! NSData?))
XCTAssertEqual(object.optDateCol, (dictionary["optDateCol"] as! NSDate?))
XCTAssertEqual(object.optObjectCol?.boolCol, boolObjectValue)
}
private func defaultSwiftObjectValuesWithReplacements(replace: [String: AnyObject]) -> [String: AnyObject] {
var valueDict = SwiftObject.defaultValues()
for (key, value) in replace {
valueDict[key] = value
}
return valueDict
}
// return an array of valid values that can be used to initialize each type
// swiftlint:disable:next cyclomatic_complexity
private func validValuesForSwiftObjectType(type: PropertyType) -> [AnyObject] {
try! Realm().beginWrite()
let managedObject = try! Realm().create(SwiftBoolObject.self, value: [true])
try! Realm().commitWrite()
switch type {
case .Bool: return [true, 0 as Int, 1 as Int]
case .Int: return [1 as Int]
case .Float: return [1 as Int, 1.1 as Float, 11.1 as Double]
case .Double: return [1 as Int, 1.1 as Float, 11.1 as Double]
case .String: return ["b"]
case .Data: return ["b".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! as NSData]
case .Date: return [NSDate(timeIntervalSince1970: 2) as AnyObject]
case .Object: return [[true], ["boolCol": true], SwiftBoolObject(value: [true]), managedObject]
case .Array: return [
[[true], [false]],
[["boolCol": true], ["boolCol": false]],
[SwiftBoolObject(value: [true]), SwiftBoolObject(value: [false])],
[managedObject, [false]]
]
case .Any: XCTFail("not supported")
case .LinkingObjects: XCTFail("not supported")
}
return []
}
// swiftlint:disable:next cyclomatic_complexity
private func invalidValuesForSwiftObjectType(type: PropertyType) -> [AnyObject] {
try! Realm().beginWrite()
let managedObject = try! Realm().create(SwiftIntObject)
try! Realm().commitWrite()
switch type {
case .Bool: return ["invalid", 2 as Int, 1.1 as Float, 11.1 as Double]
case .Int: return ["invalid", 1.1 as Float, 11.1 as Double]
case .Float: return ["invalid", true, false]
case .Double: return ["invalid", true, false]
case .String: return [0x197A71D, true, false]
case .Data: return ["invalid"]
case .Date: return ["invalid"]
case .Object: return ["invalid", ["a"], ["boolCol": "a"], SwiftIntObject()]
case .Array: return ["invalid", [["a"]], [["boolCol" : "a"]], [[SwiftIntObject()]], [[managedObject]]]
case .Any: XCTFail("not supported")
case .LinkingObjects: XCTFail("not supported")
}
return []
}
}
#endif
| mit | 3b07a6d316f1d95e176c00fbe257a68c | 44.041982 | 137 | 0.622593 | 5.384422 | false | true | false | false |
wenluma/swift | test/Generics/protocol_type_aliases.swift | 5 | 4258 | // RUN: %target-typecheck-verify-swift -typecheck %s
// RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures %s > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
func sameType<T>(_: T.Type, _: T.Type) {}
protocol P {
associatedtype A // expected-note{{'A' declared here}}
typealias X = A
}
protocol Q {
associatedtype B: P
}
// CHECK-LABEL: .requirementOnNestedTypeAlias@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: τ_0_0 : Q [τ_0_0: Explicit @ 22:51]
// CHECK-NEXT: τ_0_0[.Q].B : P [τ_0_0: Explicit @ 22:51 -> Protocol requirement (via Self.B in Q)
// CHECK-NEXT: τ_0_0[.Q].B[.P].A == Int [τ_0_0[.Q].B[.P].X: Explicit @ 22:62]
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Q, τ_0_0.B.A == Int>
func requirementOnNestedTypeAlias<T>(_: T) where T: Q, T.B.X == Int {}
struct S<T> {}
protocol P2 {
associatedtype A
typealias X = S<A>
}
protocol Q2 {
associatedtype B: P2
associatedtype C
}
// CHECK-LABEL: .requirementOnConcreteNestedTypeAlias@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: τ_0_0 : Q2 [τ_0_0: Explicit @ 42:59]
// CHECK-NEXT: τ_0_0[.Q2].B : P2 [τ_0_0: Explicit @ 42:59 -> Protocol requirement (via Self.B in Q2)
// CHECK-NEXT: τ_0_0[.Q2].C == S<T.B.A> [τ_0_0[.Q2].C: Explicit]
// CHECK-NEXT: τ_0_0[.Q2].B[.P2].X == S<T.B.A> [τ_0_0[.Q2].B[.P2].X: Concrete type binding]
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0.C == S<τ_0_0.B.A>>
func requirementOnConcreteNestedTypeAlias<T>(_: T) where T: Q2, T.C == T.B.X {}
// CHECK-LABEL: .concreteRequirementOnConcreteNestedTypeAlias@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: τ_0_0 : Q2 [τ_0_0: Explicit @ 51:67]
// CHECK-NEXT: τ_0_0[.Q2].B : P2 [τ_0_0: Explicit @ 51:67 -> Protocol requirement (via Self.B in Q2)
// CHECK-NEXT: τ_0_0[.Q2].C == τ_0_0[.Q2].B[.P2].A [τ_0_0[.Q2].C: Explicit]
// CHECK-NEXT: τ_0_0[.Q2].B[.P2].X == S<T.B.A> [τ_0_0[.Q2].B[.P2].X: Concrete type binding]
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0.C == τ_0_0.B.A>
func concreteRequirementOnConcreteNestedTypeAlias<T>(_: T) where T: Q2, S<T.C> == T.B.X {}
// Incompatible concrete typealias types are flagged as such
protocol P3 {
typealias T = Int
}
protocol Q3: P3 { // expected-error{{generic signature requires types 'Int'}}
typealias T = Float
}
protocol P3_1 {
typealias T = Float
}
protocol Q3_1: P3, P3_1 {} // expected-error{{generic signature requires types 'Float'}}
// Subprotocols can force associated types in their parents to be concrete, and
// this should be understood for types constrained by the subprotocols.
protocol Q4: P {
typealias A = Int // expected-warning{{typealias overriding associated type 'A' from protocol 'P'}}
}
protocol Q5: P {
typealias X = Int
}
// fully generic functions that manipulate the archetypes in a P
func getP_A<T: P>(_: T.Type) -> T.A.Type { return T.A.self }
func getP_X<T: P>(_: T.Type) -> T.X.Type { return T.X.self }
// ... which we use to check if the compiler is following through the concrete
// same-type constraints implied by the subprotocols.
func checkQ4_A<T: Q4>(x: T.Type) { sameType(getP_A(x), Int.self) }
func checkQ4_X<T: Q4>(x: T.Type) { sameType(getP_X(x), Int.self) }
// FIXME: these do not work, seemingly mainly due to the 'recursive decl validation'
// FIXME in GenericSignatureBuilder.cpp.
/*
func checkQ5_A<T: Q5>(x: T.Type) { sameType(getP_A(x), Int.self) }
func checkQ5_X<T: Q5>(x: T.Type) { sameType(getP_X(x), Int.self) }
*/
// Typealiases happen to allow imposing same type requirements between parent
// protocols
protocol P6_1 {
associatedtype A // expected-note{{'A' declared here}}
}
protocol P6_2 {
associatedtype B
}
protocol Q6: P6_1, P6_2 {
typealias A = B // expected-warning{{typealias overriding associated type}}
}
func getP6_1_A<T: P6_1>(_: T.Type) -> T.A.Type { return T.A.self }
func getP6_2_B<T: P6_2>(_: T.Type) -> T.B.Type { return T.B.self }
func checkQ6<T: Q6>(x: T.Type) {
sameType(getP6_1_A(x), getP6_2_B(x))
}
protocol P7 {
typealias A = Int
}
protocol P7a : P7 {
associatedtype A // expected-warning{{associated type 'A' is redundant with type 'A' declared in inherited protocol 'P7'}}
}
| mit | e7889032fb3ee4ee8bcfe99716b428a8 | 34.2 | 126 | 0.651752 | 2.741077 | false | false | false | false |
ealeksandrov/SomaFM-miniplayer | Source/Networking/MusicSearchAPI.swift | 1 | 1898 | //
// MusicSearchAPI.swift
//
// Copyright © 2017 Evgeny Aleksandrov. All rights reserved.
import Foundation
public struct MusicSearchAPI {
static var trackSearchURL: URL?
static func searchTrack() {
trackSearchURL = nil
searchItunes()
}
}
private extension MusicSearchAPI {
// MARK: - Networking
struct SearchResultsList: Codable {
let results: [SearchResult]
}
static func searchItunes() {
guard let trackName = RadioPlayer.currentTrack else { return }
var iTunesSearchURL = URLComponents(string: "https://itunes.apple.com/search")!
iTunesSearchURL.queryItems = [URLQueryItem(name: "term", value: trackName),
URLQueryItem(name: "entity", value: "song"),
URLQueryItem(name: "limit", value: "1"),
URLQueryItem(name: "at", value: "1000lHGx")]
guard let finalURL = iTunesSearchURL.url else { fallbackToGoogle(); return }
let session = URLSession(configuration: URLSessionConfiguration.default)
let request = URLRequest(url: finalURL)
session.dataTask(with: request) { data, _, _ in
guard let data = data else { fallbackToGoogle(); return }
if let channelList = try? JSONDecoder().decode(SearchResultsList.self, from: data), let resultURL = channelList.results.first?.trackViewUrl {
trackSearchURL = resultURL
} else {
fallbackToGoogle()
Log.error("iTunesSearch: error")
}
}.resume()
}
static func fallbackToGoogle() {
guard let trackName = RadioPlayer.currentTrack?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return }
trackSearchURL = URL(string: "https://www.google.ru/search?q=" + trackName)
}
}
| mit | 3a8d3715c56e320f920f53e9181cabb4 | 32.875 | 153 | 0.6136 | 4.965969 | false | false | false | false |
avito-tech/Marshroute | Marshroute/Sources/Transitions/TransitionAnimations/ModalEndpointNavigation/Presentation/ModalEndpointNavigationPresentationAnimationContext.swift | 1 | 1593 | import UIKit
/// Описание параметров анимаций прямого модального перехода на конечный UINavigationController,
/// например, на MFMailComposeViewController, UIImagePickerController
public struct ModalEndpointNavigationPresentationAnimationContext {
/// навигационный контроллер, на который нужно осуществить прямой модальный переход
public let targetNavigationController: UINavigationController
/// контроллер, с которого нужно осуществить прямой модальный переход
public let sourceViewController: UIViewController
public init(
targetNavigationController: UINavigationController,
sourceViewController: UIViewController)
{
self.targetNavigationController = targetNavigationController
self.sourceViewController = sourceViewController
}
public init?(
modalEndpointNavigationPresentationAnimationLaunchingContext animationLaunchingContext: ModalEndpointNavigationPresentationAnimationLaunchingContext)
{
guard let targetNavigationController = animationLaunchingContext.targetNavigationController
else { return nil }
guard let sourceViewController = animationLaunchingContext.sourceViewController
else { return nil }
self.targetNavigationController = targetNavigationController
self.sourceViewController = sourceViewController
}
}
| mit | c1fa192f3b30aec6650880c7ed7b1eac | 42.59375 | 157 | 0.773477 | 6.804878 | false | false | false | false |
galv/reddift | reddift/Network/Session+links.swift | 1 | 14584 | //
// Session+links.swift
// reddift
//
// Created by sonson on 2015/05/19.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
extension Session {
/**
Submit a new comment or reply to a message, whose parent is the fullname of the thing being replied to.
Its value changes the kind of object created by this request:
- the fullname of a Link: a top-level comment in that Link's thread.
- the fullname of a Comment: a comment reply to that comment.
- the fullname of a Message: a message reply to that message.
Response is JSON whose type is t1 Thing.
- parameter text: The body of comment, should be the raw markdown body of the comment or message.
- parameter parentName: Name of Thing is commented or replied to.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func postComment(text:String, parentName:String, completion:(Result<Comment>) -> Void) -> NSURLSessionDataTask? {
let parameter:[String:String] = ["thing_id":parentName, "api_type":"json", "text":text]
guard let request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/comment", parameter:parameter, method:"POST", token:token) else { return nil }
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
self.updateRateLimitWithURLResponse(response)
let result = resultFromOptionalError(Response(data: data, urlResponse: response), optionalError:error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(json2Comment)
completion(result)
})
task.resume()
return task
}
/**
Delete a Link or Comment.
- parameter thing: Thing object to be deleted.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func deleteCommentOrLink(name:String, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
let parameter:[String:String] = ["id":name]
guard let request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/del", parameter:parameter, method:"POST", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
/**
Vote specified thing.
- parameter direction: The type of voting direction as VoteDirection.
- parameter thing: Thing will be voted.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func setVote(direction:VoteDirection, name:String, completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
let parameter:[String:String] = ["dir":String(direction.rawValue), "id":name]
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/vote", parameter:parameter, method:"POST", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
/**
Save a specified content.
- parameter save: If you want to save the content, set to "true". On the other, if you want to remove the content from saved content, set to "false".
- parameter name: Name of Thing will be saved/unsaved.
- parameter category: Name of category into which you want to saved the content
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func setSave(save:Bool, name:String, category:String = "", completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
var parameter:[String:String] = ["id":name]
if !category.characters.isEmpty {
parameter["category"] = category
}
var request:NSMutableURLRequest! = nil
if save {
request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/save", parameter:parameter, method:"POST", token:token)
}
else {
request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/unsave", parameter:parameter, method:"POST", token:token)
}
return handleAsJSONRequest(request, completion:completion)
}
/**
Set hide/show a specified content.
- parameter save: If you want to hide the content, set to "true". On the other, if you want to show the content, set to "false".
- parameter name: Name of Thing will be hide/show.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func setHide(hide:Bool, name:String, completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
let parameter:[String:String] = ["id":name]
var request:NSMutableURLRequest! = nil
if hide {
request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/hide", parameter:parameter, method:"POST", token:token)
}
else {
request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/unhide", parameter:parameter, method:"POST", token:token)
}
return handleAsJSONRequest(request, completion:completion)
}
/**
Return a listing of things specified by their fullnames.
Only Links, Comments, and Subreddits are allowed.
- parameter names: Array of contents' fullnames.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func getInfo(names:[String], completion:(Result<Listing>) -> Void) -> NSURLSessionDataTask? {
let commaSeparatedNameString = commaSeparatedStringFromList(names)
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/info", parameter:["id":commaSeparatedNameString], method:"GET", token:token) else { return nil }
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
self.updateRateLimitWithURLResponse(response)
let result = resultFromOptionalError(Response(data: data, urlResponse: response), optionalError:error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(json2RedditAny)
.flatMap({
(redditAny: RedditAny) -> Result<Listing> in
if let listing = redditAny as? Listing {
return Result(value: listing)
}
return Result(error: ReddiftError.Malformed.error)
})
completion(result)
})
task.resume()
return task
}
/**
Mark or unmark a link NSFW.
- parameter thing: Thing object, to set fullname of a thing.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func setNSFW(mark:Bool, thing:Thing, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
var path = "/api/unmarknsfw"
if mark {
path = "/api/marknsfw"
}
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:path, parameter:["id":thing.name], method:"POST", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
// MARK: BDT does not cover following methods.
/**
Get a list of categories in which things are currently saved.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func getSavedCategories(completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/saved_categories", method:"GET", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
/**
Report a link, comment or message.
Reporting a thing brings it to the attention of the subreddit's moderators. Reporting a message sends it to a system for admin review.
For links and comments, the thing is implicitly hidden as well.
- parameter thing: Thing object, to set fullname of a thing.
- parameter reason: Reason of a string no longer than 100 characters.
- parameter otherReason: The other reason of a string no longer than 100 characters.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func report(thing:Thing, reason:String, otherReason:String, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
let parameter = [
"api_type" :"json",
"reason" :reason,
"other_reason":otherReason,
"thing_id" :thing.name]
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/report", parameter:parameter, method:"POST", token:token) else { return nil }
return handleRequest(request, completion:completion)
}
/**
Submit a link to a subreddit.
- parameter subreddit: The subreddit to which is submitted a link.
- parameter title: The title of the submission. up to 300 characters long.
- parameter URL: A valid URL
- parameter captcha: The user's response to the CAPTCHA challenge
- parameter captchaIden: The identifier of the CAPTCHA challenge
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func submitLink(subreddit:Subreddit, title:String, URL:String, captcha:String, captchaIden:String, completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
var parameter:[String:String] = [:]
parameter["api_type"] = "json"
parameter["captcha"] = captcha
parameter["iden"] = captchaIden
parameter["kind"] = "link"
parameter["resubmit"] = "true"
parameter["sendreplies"] = "true"
parameter["sr"] = subreddit.displayName
parameter["title"] = title
parameter["url"] = URL
guard let request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/submit", parameter:parameter, method:"POST", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
/**
Submit a text to a subreddit.
Response JSON is, {"json":{"data":{"id":"35ljt6","name":"t3_35ljt6","url":"https://www.reddit.com/r/sandboxtest/comments/35ljt6/this_is_test/"},"errors":[]}}
- parameter subreddit: The subreddit to which is submitted a link.
- parameter title: The title of the submission. up to 300 characters long.
- parameter text: Raw markdown text
- parameter captcha: The user's response to the CAPTCHA challenge
- parameter captchaIden: The identifier of the CAPTCHA challenge
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func submitText(subreddit:Subreddit, title:String, text:String, captcha:String, captchaIden:String, completion:(Result<JSON>) -> Void) -> NSURLSessionDataTask? {
var parameter:[String:String] = [:]
parameter["api_type"] = "json"
parameter["captcha"] = captcha
parameter["iden"] = captchaIden
parameter["kind"] = "self"
parameter["resubmit"] = "true"
parameter["sendreplies"] = "true"
parameter["sr"] = subreddit.displayName
parameter["text"] = text
parameter["title"] = title
guard let request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/submit", parameter:parameter, method:"POST", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
/**
Retrieve additional comments omitted from a base comment tree. When a comment tree is rendered, the most relevant comments are selected for display first. Remaining comments are stubbed out with "MoreComments" links. This API call is used to retrieve the additional comments represented by those stubs, up to 20 at a time. The two core parameters required are link and children. link is the fullname of the link whose comments are being fetched. children is a comma-delimited list of comment ID36s that need to be fetched. If id is passed, it should be the ID of the MoreComments object this call is replacing. This is needed only for the HTML UI's purposes and is optional otherwise. NOTE: you may only make one request at a time to this API endpoint. Higher concurrency will result in an error being returned.
- parameter children: A comma-delimited list of comment ID36s.
- parameter link: Thing object from which you get more children.
- parameter sort: The type of sorting children.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
public func getMoreChildren(children:[String], link:Link, sort:CommentSort, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
let commaSeparatedChildren = commaSeparatedStringFromList(children)
let parameter = ["children":commaSeparatedChildren, "link_id":link.name, "sort":sort.type, "api_type":"json"]
guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/morechildren", parameter:parameter, method:"GET", token:token) else { return nil }
return handleAsJSONRequest(request, completion:completion)
}
} | mit | 912d68f60bfbc0b0ce3b4ce3299f1efd | 54.030189 | 815 | 0.687629 | 4.846128 | false | false | false | false |
logkit/logkit | Sources/FileEndpoints.swift | 1 | 24826 | // FileEndpoints.swift
//
// Copyright (c) 2015 - 2016, Justin Pawela & The LogKit Project
// http://www.logkit.info/
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import Foundation
/// This notification is posted whenever a FileEndpoint-family Endpoint instance is about to rotate to a new log file.
///
/// The notification's `object` is the actual Endpoint instance that is rotating files. The `userInfo` dictionary
/// contains the current and next URLs, at the `LXFileEndpointRotationCurrentURLKey` and
/// `LXFileEndpointRotationNextURLKey` keys, respectively.
///
/// This notification is send _before_ the rotation occurs.
public let LXFileEndpointWillRotateFilesNotification: String = "info.logkit.endpoint.fileEndpoint.willRotateFiles"
/// This notification is posted whenever a FileEndpoint-family Endpoint instance has completed rotating to a new log
/// file.
///
/// The notification's `object` is the actual Endpoint instance that is rotating files. The `userInfo` dictionary
/// contains the current and previous URLs, at the `LXFileEndpointRotationCurrentURLKey` and
/// `LXFileEndpointRotationPreviousURLKey` keys, respectively.
///
/// This notification is send _after_ the rotation occurs, but _before_ any pending Log Entries have been written to
/// the new file.
public let LXFileEndpointDidRotateFilesNotification: String = "info.logkit.endpoint.fileEndpoint.didRotateFiles"
/// The value found at this key is the `NSURL` of the sender's previous log file.
public let LXFileEndpointRotationPreviousURLKey: String = "info.logkit.endpoint.fileEndpoint.previousURL"
/// The value found at this key is the `NSURL` of the sender's current log file.
public let LXFileEndpointRotationCurrentURLKey: String = "info.logkit.endpoint.fileEndpoint.currentURL"
/// The value found at this key is the `NSURL` of the sender's next log file.
public let LXFileEndpointRotationNextURLKey: String = "info.logkit.endpoint.fileEndpoint.nextURL"
/// The default file to use when logging: `log.txt`
private let defaultLogFileURL: NSURL? = LK_DEFAULT_LOG_DIRECTORY?.URLByAppendingPathComponent("log.txt", isDirectory: false)
/// A private UTC-based calendar used in date comparisons.
private let UTCCalendar: NSCalendar = {
//TODO: this is a cheap hack because .currentCalendar() compares dates based on local TZ
let cal = NSCalendar.currentCalendar().copy() as! NSCalendar
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return cal
}()
//MARK: Log File Wrapper
/// A wrapper for a log file.
private class LXLogFile {
private let lockQueue: dispatch_queue_t = dispatch_queue_create("logFile-Lock", DISPATCH_QUEUE_SERIAL)
private let handle: NSFileHandle
private var privateByteCounter: UIntMax?
private var privateModificationTracker: NSTimeInterval?
/// Clean up.
deinit {
dispatch_barrier_sync(self.lockQueue, {
self.handle.synchronizeFile()
self.handle.closeFile()
})
}
/// Open a log file.
private init(URL: NSURL, handle: NSFileHandle, appending: Bool) {
self.handle = handle
if appending {
self.privateByteCounter = UIntMax(self.handle.seekToEndOfFile())
} else {
self.handle.truncateFileAtOffset(0)
self.privateByteCounter = 0
}
let fileAttributes = try? URL.resourceValuesForKeys([NSURLContentModificationDateKey])
self.privateModificationTracker = (
fileAttributes?[NSURLContentModificationDateKey] as? NSDate
)?.timeIntervalSinceReferenceDate
}
/// Initialize a log file. `throws` if the file cannot be accessed.
///
/// - parameter URL: The URL of the log file.
/// - parameter shouldAppend: Indicates whether new data should be appended to existing data in the file, or if
/// the file should be truncated when opened.
/// - throws: `NSError` with domain `NSURLErrorDomain`
convenience init(URL: NSURL, shouldAppend: Bool) throws {
try NSFileManager.defaultManager().ensureFile(at: URL)
guard let handle = try? NSFileHandle(forWritingToURL: URL) else {
assertionFailure("Error opening log file at path: \(URL.absoluteString)")
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, userInfo: [NSURLErrorKey: URL])
}
self.init(URL: URL, handle: handle, appending: shouldAppend)
}
/// The size of this log file in bytes.
var sizeInBytes: UIntMax? {
var size: UIntMax?
dispatch_sync(self.lockQueue, { size = self.privateByteCounter })
return size
}
/// The date when this log file was last modified.
var modificationDate: NSDate? {
var interval: NSTimeInterval?
dispatch_sync(self.lockQueue, { interval = self.privateModificationTracker })
return interval == nil ? nil : NSDate(timeIntervalSinceReferenceDate: interval!)
}
/// Write data to this log file.
func writeData(data: NSData) {
dispatch_async(self.lockQueue, {
self.handle.writeData(data)
self.privateByteCounter = (self.privateByteCounter ?? 0) + UIntMax(data.length)
self.privateModificationTracker = CFAbsoluteTimeGetCurrent()
})
}
/// Set an extended attribute on the log file.
///
/// - note: Extended attributes are not available on watchOS.
func setExtendedAttribute(name name: String, value: String, options: CInt = 0) {
#if !os(watchOS) // watchOS 2 does not support extended attributes
dispatch_async(self.lockQueue, {
fsetxattr(self.handle.fileDescriptor, name, value, value.utf8.count, 0, options)
})
#endif
}
/// Empty this log file. Future writes will start from the the beginning of the file.
func reset() {
dispatch_sync(self.lockQueue, {
self.handle.synchronizeFile()
self.handle.truncateFileAtOffset(0)
self.privateByteCounter = 0
self.privateModificationTracker = CFAbsoluteTimeGetCurrent()
})
}
}
//MARK: Rotating File Endpoint
/// An Endpoint that writes Log Entries to a set of numbered files. Once a file has reached its maximum file size,
/// the Endpoint automatically rotates to the next file in the set.
///
/// The notifications `LXFileEndpointWillRotateFilesNotification` and `LXFileEndpointDidRotateFilesNotification`
/// are sent to the default notification center directly before and after rotating log files.
public class RotatingFileEndpoint: LXEndpoint {
/// The minimum Priority Level a Log Entry must meet to be accepted by this Endpoint.
public var minimumPriorityLevel: LXPriorityLevel
/// The formatter used by this Endpoint to serialize a Log Entry’s `dateTime` property to a string.
public var dateFormatter: LXDateFormatter
/// The formatter used by this Endpoint to serialize each Log Entry to a string.
public var entryFormatter: LXEntryFormatter
/// This Endpoint requires a newline character appended to each serialized Log Entry string.
public let requiresNewlines: Bool = true
/// The URL of the directory in which the set of log files is located.
public let directoryURL: NSURL
/// The base file name of the log files.
private let baseFileName: String
/// The maximum allowed file size in bytes. `nil` indicates no limit.
private let maxFileSizeBytes: UIntMax?
/// The number of files to include in the rotating set.
private let numberOfFiles: UInt
/// The index of the current file from the rotating set.
private lazy var currentIndex: UInt = { [unowned self] in
/* The goal here is to find the index of the file in the set that was last modified (has the largest
`modified` timestamp). If no file returns a `modified` property, it's probably because no files in this
set exist yet, in which case we'll just return index 1. */
let indexDates = Array(1...self.numberOfFiles).map({ (index) -> (index: UInt, modified: NSTimeInterval?) in
let fileAttributes = try? self.URLForIndex(index).resourceValuesForKeys([NSURLContentModificationDateKey])
let modified = fileAttributes?[NSURLContentModificationDateKey] as? NSDate
return (index: index, modified: modified?.timeIntervalSinceReferenceDate)
})
return (indexDates.maxElement({ $0.modified <= $1.modified && $1.modified != nil }))?.index ?? 1
}()
/// The file currently being written to.
private lazy var currentFile: LXLogFile? = { [unowned self] in
guard let file = try? LXLogFile(URL: self.currentURL, shouldAppend: true) else {
assertionFailure("Could not open the log file at URL '\(self.currentURL.absoluteString)'")
return nil
}
file.setExtendedAttribute(name: self.extendedAttributeKey, value: LK_LOGKIT_VERSION)
return file
}()
/// The name of the extended attribute metadata item used to identify one of this Endpoint's files.
private lazy var extendedAttributeKey: String = { [unowned self] in return "info.logkit.endpoint.\(self.dynamicType)" }()
/// Initialize a Rotating File Endpoint.
///
/// If the specified file cannot be opened, or if the index-prepended URL evaluates to `nil`, the initializer may
/// fail.
///
/// - parameter baseURL: The URL used to build the rotating file set’s file URLs. Each file's index
/// number will be prepended to the last path component of this URL. Defaults
/// to `Application Support/{bundleID}/logs/{number}_log.txt`. Must not be `nil`.
/// - parameter numberOfFiles: The number of files to be used in the rotation. Defaults to `5`.
/// - parameter maxFileSizeKiB: The maximum file size of each file in the rotation, specified in kilobytes.
/// Passing `nil` results in no limit, and no automatic rotation. Defaults
/// to `1024`.
/// - parameter minimumPriorityLevel: The minimum Priority Level a Log Entry must meet to be accepted by this
/// Endpoint. Defaults to `.All`.
/// - parameter dateFormatter: The formatter used by this Endpoint to serialize a Log Entry’s `dateTime`
/// property to a string. Defaults to `.standardFormatter()`.
/// - parameter entryFormatter: The formatter used by this Endpoint to serialize each Log Entry to a string.
/// Defaults to `.standardFormatter()`.
public init?(
baseURL: NSURL? = defaultLogFileURL,
numberOfFiles: UInt = 5,
maxFileSizeKiB: UInt? = 1024,
minimumPriorityLevel: LXPriorityLevel = .All,
dateFormatter: LXDateFormatter = LXDateFormatter.standardFormatter(),
entryFormatter: LXEntryFormatter = LXEntryFormatter.standardFormatter()
) {
self.dateFormatter = dateFormatter
self.entryFormatter = entryFormatter
self.maxFileSizeBytes = maxFileSizeKiB == nil ? nil : UIntMax(maxFileSizeKiB!) * 1024
self.numberOfFiles = numberOfFiles
//TODO: check file or directory to predict if file is accessible
guard let dirURL = baseURL?.URLByDeletingLastPathComponent, filename = baseURL?.lastPathComponent else {
assertionFailure("The log file URL '\(baseURL?.absoluteString ?? String())' is invalid")
self.minimumPriorityLevel = .None
self.directoryURL = NSURL(string: "")!
self.baseFileName = ""
return nil
}
self.minimumPriorityLevel = minimumPriorityLevel
self.directoryURL = dirURL
self.baseFileName = filename
}
/// The index of the next file in the rotation.
private var nextIndex: UInt { return self.currentIndex + 1 > self.numberOfFiles ? 1 : self.currentIndex + 1 }
/// The URL of the log file currently in use. Manually modifying this file is _not_ recommended.
public var currentURL: NSURL { return self.URLForIndex(self.currentIndex) }
/// The URL of the next file in the rotation.
private var nextURL: NSURL { return self.URLForIndex(self.nextIndex) }
/// The URL for the file at a given index.
private func URLForIndex(index: UInt) -> NSURL {
return self.directoryURL.URLByAppendingPathComponent(self.fileNameForIndex(index), isDirectory: false)
}
/// The name for the file at a given index.
private func fileNameForIndex(index: UInt) -> String {
let format = "%0\(Int(floor(log10(Double(self.numberOfFiles)) + 1.0)))d"
return "\(String(format: format, index))_\(self.baseFileName)"
}
/// Returns the next log file to be written to, already prepared for use.
private func nextFile() -> LXLogFile? {
guard let nextFile = try? LXLogFile(URL: self.nextURL, shouldAppend: false) else {
assertionFailure("The log file at URL '\(self.nextURL)' could not be opened.")
return nil
}
nextFile.setExtendedAttribute(name: self.extendedAttributeKey, value: LK_LOGKIT_VERSION)
return nextFile
}
/// Writes a serialized Log Entry string to the currently selected file.
public func write(string: String) {
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
//TODO: might pass test but file fills before write
if self.shouldRotateBeforeWritingDataWithLength(data.length), let nextFile = self.nextFile() {
self.rotateToFile(nextFile)
}
self.currentFile?.writeData(data)
} else {
assertionFailure("Failure to create data from entry string")
}
}
/// Clears the currently selected file and begins writing again at its beginning.
public func resetCurrentFile() {
self.currentFile?.reset()
}
/// Instructs the Endpoint to rotate to the next log file in its sequence.
public func rotate() {
if let nextFile = self.nextFile() {
self.rotateToFile(nextFile)
}
}
/// Sets the current file to the next index and notifies about rotation
private func rotateToFile(nextFile: LXLogFile) {
//TODO: Move these notifications into property observers, if the properties can be made non-lazy.
//TODO: Getting `nextURL` from `nextFile`, instead of calculating it again, might be more robust.
NSNotificationCenter.defaultCenter().postNotificationName(
LXFileEndpointWillRotateFilesNotification,
object: self,
userInfo: [
LXFileEndpointRotationCurrentURLKey: self.currentURL,
LXFileEndpointRotationNextURLKey: self.nextURL
]
)
let previousURL = self.currentURL
self.currentFile = nextFile
self.currentIndex = self.nextIndex
NSNotificationCenter.defaultCenter().postNotificationName(
LXFileEndpointDidRotateFilesNotification,
object: self,
userInfo: [
LXFileEndpointRotationCurrentURLKey: self.currentURL,
LXFileEndpointRotationPreviousURLKey: previousURL
]
)
}
/// This method provides an opportunity to determine whether a new log file should be selected before writing the
/// next Log Entry.
///
/// - parameter length: The length of the data (number of bytes) that will be written next.
///
/// - returns: A boolean indicating whether a new log file should be selected.
private func shouldRotateBeforeWritingDataWithLength(length: Int) -> Bool {
switch (self.maxFileSizeBytes, self.currentFile?.sizeInBytes) {
case (.Some(let maxSize), .Some(let size)) where size + UIntMax(length) > maxSize: // Won't fit
fallthrough
case (.Some, .None): // Can't determine current size
return true
case (.None, .None), (.None, .Some), (.Some, .Some): // No limit or will fit
return false
}
}
/// A utility method that will not return until all previously scheduled writes have completed. Useful for testing.
///
/// - returns: Timestamp of last write (scheduled before barrier).
internal func barrier() -> NSTimeInterval? {
return self.currentFile?.modificationDate?.timeIntervalSinceReferenceDate
}
}
//MARK: File Endpoint
/// An Endpoint that writes Log Entries to a specified file.
public class FileEndpoint: RotatingFileEndpoint {
/// Initialize a File Endpoint.
///
/// If the specified file cannot be opened, or if the URL evaluates to `nil`, the initializer may fail.
///
/// - parameter fileURL: The URL of the log file.
/// Defaults to `Application Support/{bundleID}/logs/log.txt`. Must not be `nil`.
/// - parameter shouldAppend: Indicates whether the Endpoint should continue appending Log Entries to the
/// end of the file, or clear it and start at the beginning. Defaults to `true`.
/// - parameter minimumPriorityLevel: The minimum Priority Level a Log Entry must meet to be accepted by this
/// Endpoint. Defaults to `.All`.
/// - parameter dateFormatter: The formatter used by this Endpoint to serialize a Log Entry’s `dateTime`
/// property to a string. Defaults to `.standardFormatter()`.
/// - parameter entryFormatter: The formatter used by this Endpoint to serialize each Log Entry to a string.
/// Defaults to `.standardFormatter()`.
public init?(
fileURL: NSURL? = defaultLogFileURL,
shouldAppend: Bool = true,
minimumPriorityLevel: LXPriorityLevel = .All,
dateFormatter: LXDateFormatter = LXDateFormatter.standardFormatter(),
entryFormatter: LXEntryFormatter = LXEntryFormatter.standardFormatter()
) {
super.init(
baseURL: fileURL,
numberOfFiles: 1,
maxFileSizeKiB: nil,
minimumPriorityLevel: minimumPriorityLevel,
dateFormatter: dateFormatter,
entryFormatter: entryFormatter
)
if !shouldAppend {
self.resetCurrentFile()
}
}
/// This Endpoint always uses `baseFileName` as its file name.
private override func fileNameForIndex(index: UInt) -> String {
return self.baseFileName
}
/// Does nothing. File Endpoint does not rotate.
public override func rotate() {}
/// This endpoint will never rotate files.
private override func shouldRotateBeforeWritingDataWithLength(length: Int) -> Bool {
return false
}
}
//MARK: Dated File Endpoint
/// An Endpoint that writes Log Enties to a dated file. A datestamp will be prepended to the file's name. The file
/// rotates automatically at midnight UTC.
///
/// The notifications `LXFileEndpointWillRotateFilesNotification` and `LXFileEndpointDidRotateFilesNotification` are
/// sent to the default notification center directly before and after rotating log files.
public class DatedFileEndpoint: RotatingFileEndpoint {
/// The formatter used for datestamp preparation.
private let nameFormatter = LXDateFormatter.dateOnlyFormatter()
/// Initialize a Dated File Endpoint.
///
/// If the specified file cannot be opened, or if the datestamp-prepended URL evaluates to `nil`, the initializer
/// may fail.
///
/// - parameter baseURL: The URL used to build the date files’ URLs. Today's date will be prepended
/// to the last path component of this URL. Must not be `nil`.
/// Defaults to `Application Support/{bundleID}/logs/{datestamp}_log.txt`.
/// - parameter minimumPriorityLevel: The minimum Priority Level a Log Entry must meet to be accepted by this
/// Endpoint. Defaults to `.All`.
/// - parameter dateFormatter: The formatter used by this Endpoint to serialize a Log Entry’s `dateTime`
/// property to a string. Defaults to `.standardFormatter()`.
/// - parameter entryFormatter: The formatter used by this Endpoint to serialize each Log Entry to a string.
/// Defaults to `.standardFormatter()`.
public init?(
baseURL: NSURL? = defaultLogFileURL,
minimumPriorityLevel: LXPriorityLevel = .All,
dateFormatter: LXDateFormatter = LXDateFormatter.standardFormatter(),
entryFormatter: LXEntryFormatter = LXEntryFormatter.standardFormatter()
) {
super.init(
baseURL: baseURL,
numberOfFiles: 1,
maxFileSizeKiB: nil,
minimumPriorityLevel: minimumPriorityLevel,
dateFormatter: dateFormatter,
entryFormatter: entryFormatter
)
}
/// The name for the file with today's date.
private override func fileNameForIndex(index: UInt) -> String {
return "\(self.nameFormatter.stringFromDate(NSDate()))_\(self.baseFileName)"
}
/// Does nothing. Dated File Endpoint only rotates by date.
public override func rotate() {}
/// Returns `true` if the current date no longer matches the log file's date. Disregards the `length` parameter.
private override func shouldRotateBeforeWritingDataWithLength(length: Int) -> Bool {
switch self.currentFile?.modificationDate {
case .Some(let modificationDate) where !UTCCalendar.isDateSameAsToday(modificationDate): // Wrong date
fallthrough
case .None: // Can't determine the date
return true
case .Some: // Correct date
return false
}
}
//TODO: Cap the max number trailing log files.
}
// ======================================================================== //
// MARK: Aliases
// ======================================================================== //
// Classes in LogKit 3.0 will drop the LX prefixes. To facilitate other 3.0
// features, the File Endpoint family classes have been renamed early. The
// aliases below ensure developers are not affected by this early change.
//TODO: Remove unnecessary aliases in LogKit 4.0
/// An Endpoint that writes Log Entries to a set of numbered files. Once a file has reached its maximum file size,
/// the Endpoint automatically rotates to the next file in the set.
///
/// The notifications `LXFileEndpointWillRotateFilesNotification` and `LXFileEndpointDidRotateFilesNotification`
/// are sent to the default notification center directly before and after rotating log files.
/// - note: This is a LogKit 3.0 forward-compatibility typealias to `RotatingFileEndpoint`.
public typealias LXRotatingFileEndpoint = RotatingFileEndpoint
/// An Endpoint that writes Log Entries to a specified file.
/// - note: This is a LogKit 3.0 forward-compatibility typealias to `FileEndpoint`.
public typealias LXFileEndpoint = FileEndpoint
/// An Endpoint that writes Log Enties to a dated file. A datestamp will be prepended to the file's name. The file
/// rotates automatically at midnight UTC.
///
/// The notifications `LXFileEndpointWillRotateFilesNotification` and `LXFileEndpointDidRotateFilesNotification` are
/// sent to the default notification center directly before and after rotating log files.
/// - note: This is a LogKit 3.0 forward-compatibility typealias to `DatedFileEndpoint`.
public typealias LXDatedFileEndpoint = DatedFileEndpoint
| isc | e9799a43a2416802f5af6de5450303c8 | 47.750491 | 127 | 0.664061 | 5.21193 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Utilis/Protos/GenericMessage+Hashing.swift | 1 | 3685 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
protocol BigEndianDataConvertible {
var asBigEndianData: Data { get }
}
extension GenericMessage {
func hashOfContent(with timestamp: Date) -> Data? {
guard let content = content else {
return nil
}
switch content {
case .location(let data as BigEndianDataConvertible),
.text(let data as BigEndianDataConvertible),
.edited(let data as BigEndianDataConvertible),
.asset(let data as BigEndianDataConvertible):
return data.hashWithTimestamp(timestamp: timestamp.timeIntervalSince1970)
case .ephemeral(let data):
guard let content = data.content else {
return nil
}
switch content {
case .location(let data as BigEndianDataConvertible),
.text(let data as BigEndianDataConvertible),
.asset(let data as BigEndianDataConvertible):
return data.hashWithTimestamp(timestamp: timestamp.timeIntervalSince1970)
default:
return nil
}
default:
return nil
}
}
}
extension MessageEdit: BigEndianDataConvertible {
var asBigEndianData: Data {
return text.asBigEndianData
}
}
extension WireProtos.Text: BigEndianDataConvertible {
var asBigEndianData: Data {
return content.asBigEndianData
}
}
extension Location: BigEndianDataConvertible {
var asBigEndianData: Data {
var data = latitude.times1000.asBigEndianData
data.append(longitude.times1000.asBigEndianData)
return data
}
}
extension WireProtos.Asset: BigEndianDataConvertible {
var asBigEndianData: Data {
return uploaded.assetID.asBigEndianData
}
}
fileprivate extension Float {
var times1000: Int {
return Int(roundf(self * 1000.0))
}
}
extension String: BigEndianDataConvertible {
var asBigEndianData: Data {
var data = Data([0xFE, 0xFF]) // Byte order marker
data.append(self.data(using: .utf16BigEndian)!)
return data
}
}
extension Int: BigEndianDataConvertible {
public var asBigEndianData: Data {
return withUnsafePointer(to: self.bigEndian) {
Data(bytes: $0, count: MemoryLayout.size(ofValue: self))
}
}
}
extension TimeInterval: BigEndianDataConvertible {
public var asBigEndianData: Data {
let long = Int64(self).bigEndian
return withUnsafePointer(to: long) {
return Data(bytes: $0, count: MemoryLayout.size(ofValue: long))
}
}
}
extension BigEndianDataConvertible {
public func dataWithTimestamp(timestamp: TimeInterval) -> Data {
var data = self.asBigEndianData
data.append(timestamp.asBigEndianData)
return data
}
public func hashWithTimestamp(timestamp: TimeInterval) -> Data {
return dataWithTimestamp(timestamp: timestamp).zmSHA256Digest()
}
}
| gpl-3.0 | e45e3ef148e7523a23f26435b5891148 | 27.565891 | 89 | 0.664858 | 4.993225 | false | false | false | false |
hooman/swift | stdlib/public/Concurrency/AsyncDropFirstSequence.swift | 3 | 4982 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 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
@available(SwiftStdlib 5.5, *)
extension AsyncSequence {
/// Omits a specified number of elements from the base asynchronous sequence,
/// then passes through all remaining elements.
///
/// Use `dropFirst(_:)` when you want to drop the first *n* elements from the
/// base sequence and pass through the remaining elements.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `10`. The `dropFirst(_:)` method causes the modified
/// sequence to ignore the values `0` through `4`, and instead emit `5` through `10`:
///
/// for await number in Counter(howHigh: 10).dropFirst(3) {
/// print("\(number) ", terminator: " ")
/// }
/// // prints "4 5 6 7 8 9 10"
///
/// If the number of elements to drop exceeds the number of elements in the
/// sequence, the result is an empty sequence.
///
/// - Parameter count: The number of elements to drop from the beginning of
/// the sequence. `count` must be greater than or equal to zero.
/// - Returns: An asynchronous sequence that drops the first `count`
/// elements from the base sequence.
@inlinable
public __consuming func dropFirst(
_ count: Int = 1
) -> AsyncDropFirstSequence<Self> {
precondition(count >= 0,
"Can't drop a negative number of elements from an async sequence")
return AsyncDropFirstSequence(self, dropping: count)
}
}
/// An asynchronous sequence which omits a specified number of elements from the
/// base asynchronous sequence, then passes through all remaining elements.
@available(SwiftStdlib 5.5, *)
@frozen
public struct AsyncDropFirstSequence<Base: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let count: Int
@inlinable
init(_ base: Base, dropping count: Int) {
self.base = base
self.count = count
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncDropFirstSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The drop-first sequence produces whatever type of element its base
/// iterator produces.
public typealias Element = Base.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the drop-first sequence.
@frozen
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
var count: Int
@inlinable
init(_ baseIterator: Base.AsyncIterator, count: Int) {
self.baseIterator = baseIterator
self.count = count
}
/// Produces the next element in the drop-first sequence.
///
/// Until reaching the number of elements to drop, this iterator calls
/// `next()` on its base iterator and discards the result. If the base
/// iterator returns `nil`, indicating the end of the sequence, this
/// iterator returns `nil`. After reaching the number of elements to
/// drop, this iterator passes along the result of calling `next()` on
/// the base iterator.
@inlinable
public mutating func next() async rethrows -> Base.Element? {
var remainingToDrop = count
while remainingToDrop > 0 {
guard try await baseIterator.next() != nil else {
count = 0
return nil
}
remainingToDrop -= 1
}
count = 0
return try await baseIterator.next()
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), count: count)
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncDropFirstSequence {
/// Omits a specified number of elements from the base asynchronous sequence,
/// then passes through all remaining elements.
///
/// When you call `dropFirst(_:)` on an asynchronous sequence that is already
/// an `AsyncDropFirstSequence`, the returned sequence simply adds the new
/// drop count to the current drop count.
@inlinable
public __consuming func dropFirst(
_ count: Int = 1
) -> AsyncDropFirstSequence<Base> {
// If this is already a AsyncDropFirstSequence, we can just sum the current
// drop count and additional drop count.
precondition(count >= 0,
"Can't drop a negative number of elements from an async sequence")
return AsyncDropFirstSequence(base, dropping: self.count + count)
}
}
| apache-2.0 | 836717f40b07b035653b1c32484a96ac | 34.841727 | 87 | 0.665998 | 4.762906 | false | false | false | false |
swilliams/DB5-Swift | Source/ThemeLoader.swift | 1 | 1148 | //
// ThemeLoader.swift
// DB5Demo
//
import UIKit
class ThemeLoader: NSObject {
var defaultTheme: Theme?
var themes: [Theme]
init(themeFilename filename: String) {
let themesFilePath = NSBundle.mainBundle().pathForResource(filename, ofType: "plist")
let themesDictionary = NSDictionary(contentsOfFile: themesFilePath!)!
themes = [Theme]()
for oneKey in themesDictionary.allKeys {
let key = oneKey as! String
let themeDictionary = themesDictionary[key] as! NSDictionary
let theme = Theme(fromDictionary: themeDictionary)
if key.lowercaseString == "default" {
defaultTheme = theme
}
theme.name = key
themes.append(theme)
}
for oneTheme in themes {
if oneTheme != defaultTheme {
oneTheme.parentTheme = defaultTheme
}
}
}
func themeNamed(themeName: String) -> Theme? {
for oneTheme in themes {
if themeName == oneTheme.name {
return oneTheme
}
}
return nil
}
}
| mit | 34bc4d5b7a680494dba95f4610b50273 | 27 | 93 | 0.568815 | 4.948276 | false | false | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/foundation_value_types/urlcomponents/main.swift | 2 | 1511 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
import Foundation
func main() {
var urlc = URLComponents(string: "https://www.apple.com:12345/thisurl/isnotreal/itoldyou.php?page=fake")!
print(urlc.scheme) //% self.expect('frame variable -d run -- urlc', substrs=['urlString = "https://www.apple.com:12345/thisurl/isnotreal/itoldyou.php?page=fake"'])
print(urlc.host) //% self.expect('frame variable -d run -- urlc', substrs=['scheme = "https"'])
print(urlc.port) //% self.expect('frame variable -d run -- urlc', substrs=['host = "www.apple.com"'])
print(urlc.path) //% self.expect('frame variable -d run -- urlc', substrs=['port = 0x', 'Int64(12345)'])
print(urlc.query) //% self.expect('frame variable -d run -- urlc', substrs=['path = "/thisurl/isnotreal/itoldyou.php"'])
print("break here last") //% self.expect('frame variable -d run -- urlc', substrs=['query = "page=fake"'])
//% self.expect('expression -d run -- urlc', substrs=['urlString = "https://www.apple.com:12345/thisurl/isnotreal/itoldyou.php?page=fake"', 'scheme = "https"', 'user = nil', 'fragment = nil'])
}
main()
| apache-2.0 | 56e6cba9038c3016c2d8f864e11ad288 | 59.44 | 195 | 0.647915 | 3.546948 | false | false | false | false |
ziogaschr/SwiftPasscodeLock | PasscodeLockTests/Fakes/FakePasscodeState.swift | 1 | 691 | //
// FakePasscodeState.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/28/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import Foundation
class FakePasscodeState: PasscodeLockStateType {
let title = "A"
let description = "B"
let isCancellableAction = true
var isTouchIDAllowed = true
var acceptPaccodeCalled = false
var acceptedPasscode = [String]()
var numberOfAcceptedPasscodes = 0
init() {}
func acceptPasscode(_ passcode: [String], fromLock lock: PasscodeLockType) {
acceptedPasscode = passcode
acceptPaccodeCalled = true
numberOfAcceptedPasscodes += 1
}
}
| mit | 3d5b1185432fa87336649e4f54870cc2 | 22 | 80 | 0.66087 | 4.6 | false | false | false | false |
benlangmuir/swift | test/Generics/concrete_contraction_unrelated_typealias.swift | 6 | 3315 | // RUN: %target-swift-frontend -typecheck -verify %s -debug-generic-signatures -warn-redundant-requirements 2>&1 | %FileCheck %s
// Another GenericSignatureBuilder oddity, reduced from RxSwift.
//
// The requirements 'Proxy.Parent == P' and 'Proxy.Delegate == D' in the
// init() below refer to both the typealias and the associated type,
// despite the class being unrelated to the protocol; it just happens to
// define typealiases with the same name.
//
// In the Requirement Machine, the concrete contraction pre-processing
// pass would eagerly substitute the concrete type into these two
// requirements, producing the useless requirements 'P == P' and 'D == D'.
//
// Make sure concrete contraction keeps these requirements as-is by
// checking the generic signature with and without concrete contraction.
class GenericDelegateProxy<P : AnyObject, D> {
typealias Parent = P
typealias Delegate = D
// Here if we resolve Proxy.Parent and Proxy.Delegate to the typealiases,
// we get vacuous requirements 'P == P' and 'D == D'. By keeping both
// the substituted and original requirement, we ensure that the
// unrelated associated type 'Parent' is constrained instead.
// CHECK-LABEL: .GenericDelegateProxy.init(_:)@
// CHECK-NEXT: <P, D, Proxy where P == Proxy.[DelegateProxyType]Parent, D == Proxy.[DelegateProxyType]Delegate, Proxy : GenericDelegateProxy<P, D>, Proxy : DelegateProxyType>
init<Proxy: DelegateProxyType>(_: Proxy.Type)
where Proxy: GenericDelegateProxy<P, D>,
Proxy.Parent == P, // expected-warning {{redundant same-type constraint 'GenericDelegateProxy<P, D>.Parent' (aka 'P') == 'P'}}
Proxy.Delegate == D {} // expected-warning {{redundant same-type constraint 'GenericDelegateProxy<P, D>.Delegate' (aka 'D') == 'D'}}
}
class SomeClass {}
struct SomeStruct {}
class ConcreteDelegateProxy {
typealias Parent = SomeClass
typealias Delegate = SomeStruct
// An even more esoteric edge case. Note that this one I made up; only
// the first one is relevant for compatibility with RxSwift.
//
// Here unfortunately we produce a different result from the GSB, because
// the hack for keeping both the substituted and original requirement means
// the substituted requirements become 'P == SomeClass' and 'D == SomeStruct'.
//
// The GSB does not constrain P and D in this way and instead produced the
// following minimized signature:
//
// <P, D, Proxy where P == Proxy.[DelegateProxyType]Parent, D == Proxy.[DelegateProxyType]Delegate, Proxy : ConcreteDelegateProxy, Proxy : DelegateProxyType>!
// CHECK-LABEL: .ConcreteDelegateProxy.init(_:_:_:)@
// CHECK-NEXT: <P, D, Proxy where P == SomeClass, D == SomeStruct, Proxy : ConcreteDelegateProxy, Proxy : DelegateProxyType, Proxy.[DelegateProxyType]Delegate == SomeStruct, Proxy.[DelegateProxyType]Parent == SomeClass>
// expected-warning@+2 {{same-type requirement makes generic parameter 'P' non-generic}}
// expected-warning@+1 {{same-type requirement makes generic parameter 'D' non-generic}}
init<P, D, Proxy: DelegateProxyType>(_: P, _: D, _: Proxy.Type)
where Proxy: ConcreteDelegateProxy,
Proxy.Parent == P,
Proxy.Delegate == D {}
}
protocol DelegateProxyType {
associatedtype Parent : AnyObject
associatedtype Delegate
}
| apache-2.0 | ace6691f17c535d34a4e0599fcf093e1 | 48.477612 | 221 | 0.722172 | 4.431818 | false | false | false | false |
soffes/deck | Deck/Card.swift | 1 | 649 | //
// Card.swift
// Deck
//
// Created by Sam Soffes on 11/5/14.
// Copyright (c) 2014 Sam Soffes. All rights reserved.
//
public struct Card: Comparable {
public let suit: Suit
public let rank: Rank
public var shortDescription: String {
return "\(suit.shortDescription)\(rank.shortDescription)"
}
public var description: String {
return "\(rank.description) of \(suit.description)"
}
public init(suit: Suit, rank: Rank) {
self.suit = suit
self.rank = rank
}
}
// MARK: - Comparable
public func ==(x: Card, y: Card) -> Bool {
return x.rank == y.rank
}
public func <(x: Card, y: Card) -> Bool {
return x.rank < y.rank
}
| mit | 479e44704e99aa69418d26328ae2ad83 | 17.027778 | 59 | 0.651772 | 3.075829 | false | false | false | false |
docopt/docopt.swift | Sources/Option.swift | 2 | 3103 | //
// Option.swift
// docopt
//
// Created by Pavel S. Mazurin on 2/28/15.
// Copyright (c) 2015 kovpas. All rights reserved.
//
import Foundation
internal class Option: LeafPattern {
internal var short: String?
internal var long: String?
internal var argCount: UInt
override internal var name: String? {
get {
return self.long ?? self.short
}
set {
}
}
override var description: String {
get {
var valueDescription : String = value?.description ?? "nil"
if value is Bool, let val = value as? Bool
{
valueDescription = val ? "true" : "false"
}
return "Option(\(String(describing: short)), \(String(describing: long)), \(argCount), \(valueDescription))"
}
}
convenience init(_ option: Option) {
self.init(option.short, long: option.long, argCount: option.argCount, value: option.value)
}
init(_ short: String? = nil, long: String? = nil, argCount: UInt = 0, value: AnyObject? = false as NSNumber) {
assert(argCount <= 1)
self.short = short
self.long = long
self.argCount = argCount
super.init("", value: value)
if argCount > 0 && value as? Bool == false {
self.value = nil
} else {
self.value = value
}
}
static func parse(_ optionDescription: String) -> Option {
var short: String? = nil
var long: String? = nil
var argCount: UInt = 0
var value: AnyObject? = kCFBooleanFalse
var (options, _, description) = optionDescription.strip().partition(" ")
options = options.replacingOccurrences(of: ",", with: " ", options: [], range: nil)
options = options.replacingOccurrences(of: "=", with: " ", options: [], range: nil)
for s in options.components(separatedBy: " ").filter({!$0.isEmpty}) {
if s.hasPrefix("--") {
long = s
} else if s.hasPrefix("-") {
short = s
} else {
argCount = 1
}
}
if argCount == 1 {
let matched = description.findAll("\\[default: (.*)\\]", flags: .caseInsensitive)
if matched.count > 0
{
value = matched[0] as AnyObject
}
else
{
value = nil
}
}
return Option(short, long: long, argCount: argCount, value: value)
}
override func singleMatch<T: LeafPattern>(_ left: [T]) -> SingleMatchResult {
for i in 0..<left.count {
let pattern = left[i]
if pattern.name == name {
return (i, pattern)
}
}
return (0, nil)
}
}
func ==(lhs: Option, rhs: Option) -> Bool {
let valEqual = lhs as LeafPattern == rhs as LeafPattern
return lhs.short == rhs.short
&& lhs.long == lhs.long
&& lhs.argCount == rhs.argCount
&& valEqual
}
| mit | b229d04ca6ed8d9dd62e3b78e3c663d4 | 29.126214 | 120 | 0.512407 | 4.523324 | false | false | false | false |
sol/aeson | tests/JSONTestSuite/parsers/test_Freddy_2_1_0/test_Freddy/main.swift | 12 | 771 | //
// main.swift
// test_Freddy
//
// Created by nst on 10/08/16.
// Copyright © 2016 Nicolas Seriot. All rights reserved.
//
import Foundation
func main() {
guard Process.arguments.count == 2 else {
let url = NSURL(fileURLWithPath: Process.arguments[0])
guard let programName = url.lastPathComponent else { exit(1) }
print("Usage: ./\(programName) file.json")
exit(1)
}
let path = Process.arguments[1]
let url = NSURL.fileURLWithPath(path)
guard let data = NSData(contentsOfURL:url) else {
print("*** CANNOT READ DATA AT \(url)")
return
}
var p = JSONParser(utf8Data: data)
do {
try p.parse()
exit(0)
} catch {
exit(1)
}
}
main()
| bsd-3-clause | 81b8adaf09db38f56835b480d7af543c | 19.810811 | 70 | 0.571429 | 3.701923 | false | false | false | false |
SwiftGen/templates | Pods/StencilSwiftKit/Sources/SwiftIdentifier.swift | 2 | 3717 | //
// StencilSwiftKit
// Copyright (c) 2017 SwiftGen
// MIT Licence
//
import Foundation
private func mr(_ char: Int) -> CountableClosedRange<Int> {
return char...char
}
// Official list of valid identifier characters
// swiftlint:disable:next line_length
// from: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/doc/uid/TP40014097-CH30-ID410
private let headRanges: [CountableClosedRange<Int>] = [
0x61...0x7a, 0x41...0x5a, mr(0x5f), mr(0xa8), mr(0xaa), mr(0xad), mr(0xaf),
0xb2...0xb5, 0xb7...0xba, 0xbc...0xbe, 0xc0...0xd6, 0xd8...0xf6, 0xf8...0xff,
0x100...0x2ff, 0x370...0x167f, 0x1681...0x180d, 0x180f...0x1dbf,
0x1e00...0x1fff, 0x200b...0x200d, 0x202a...0x202e, mr(0x203F), mr(0x2040),
mr(0x2054), 0x2060...0x206f, 0x2070...0x20cf, 0x2100...0x218f, 0x2460...0x24ff,
0x2776...0x2793, 0x2c00...0x2dff, 0x2e80...0x2fff, 0x3004...0x3007,
0x3021...0x302f, 0x3031...0x303f, 0x3040...0xd7ff, 0xf900...0xfd3d,
0xfd40...0xfdcf, 0xfdf0...0xfe1f, 0xfe30...0xfe44, 0xfe47...0xfffd,
0x10000...0x1fffd, 0x20000...0x2fffd, 0x30000...0x3fffd, 0x40000...0x4fffd,
0x50000...0x5fffd, 0x60000...0x6fffd, 0x70000...0x7fffd, 0x80000...0x8fffd,
0x90000...0x9fffd, 0xa0000...0xafffd, 0xb0000...0xbfffd, 0xc0000...0xcfffd,
0xd0000...0xdfffd, 0xe0000...0xefffd
]
private let tailRanges: [CountableClosedRange<Int>] = [
0x30...0x39, 0x300...0x36F, 0x1dc0...0x1dff, 0x20d0...0x20ff, 0xfe20...0xfe2f
]
private func identifierCharacterSets(exceptions: String) -> (head: NSMutableCharacterSet, tail: NSMutableCharacterSet) {
let addRange: (NSMutableCharacterSet, CountableClosedRange<Int>) -> Void = { (mcs, range) in
mcs.addCharacters(in: NSRange(location: range.lowerBound, length: range.count))
}
let head = NSMutableCharacterSet()
for range in headRanges {
addRange(head, range)
}
head.removeCharacters(in: exceptions)
guard let tail = head.mutableCopy() as? NSMutableCharacterSet else {
fatalError("Internal error: mutableCopy() should have returned a valid NSMutableCharacterSet")
}
for range in tailRanges {
addRange(tail, range)
}
tail.removeCharacters(in: exceptions)
return (head, tail)
}
enum SwiftIdentifier {
static func identifier(from string: String,
forbiddenChars exceptions: String = "",
replaceWithUnderscores underscores: Bool = false) -> String {
let (_, tail) = identifierCharacterSets(exceptions: exceptions)
let parts = string.components(separatedBy: tail.inverted)
let replacement = underscores ? "_" : ""
let mappedParts = parts.map({ (string: String) -> String in
// Can't use capitalizedString here because it will lowercase all letters after the first
// e.g. "SomeNiceIdentifier".capitalizedString will because "Someniceidentifier" which is not what we want
let ns = NSString(string: string)
if ns.length > 0 {
let firstLetter = ns.substring(to: 1)
let rest = ns.substring(from: 1)
return firstLetter.uppercased() + rest
} else {
return ""
}
})
let result = mappedParts.joined(separator: replacement)
return prefixWithUnderscoreIfNeeded(string: result, forbiddenChars: exceptions)
}
static func prefixWithUnderscoreIfNeeded(string: String,
forbiddenChars exceptions: String = "") -> String {
let (head, _) = identifierCharacterSets(exceptions: exceptions)
let chars = string.unicodeScalars
let firstChar = chars[chars.startIndex]
let prefix = !head.longCharacterIsMember(firstChar.value) ? "_" : ""
return prefix + string
}
}
| mit | 051234b1ac1516359839330efc0723a4 | 38.542553 | 170 | 0.690073 | 3.330645 | false | false | false | false |
realgreys/RGPageMenu | RGPageMenu/Classes/MenuItemView.swift | 1 | 3830 | //
// MenuItemView.swift
// paging
//
// Created by realgreys on 2016. 5. 10..
// Copyright © 2016 realgreys. All rights reserved.
//
import UIKit
class MenuItemView: UIView {
private var options: RGPageMenuOptions!
var titleLabel: UILabel = {
let label = UILabel(frame: .zero)
label.textAlignment = .Center
label.userInteractionEnabled = true
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private var labelSize: CGSize {
guard let text = titleLabel.text else { return .zero }
return NSString(string: text).boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max),
options: .UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: titleLabel.font],
context: nil).size
}
private var widthConstraint: NSLayoutConstraint!
var selected: Bool = false {
didSet {
backgroundColor = selected ? options.selectedColor : options.backgroundColor
titleLabel.textColor = selected ? options.selectedTextColor : options.textColor
// font가 변경되면 size 계산 다시 해야 한다.
}
}
// MARK: - Lifecycle
init(title: String, options: RGPageMenuOptions) {
super.init(frame: .zero)
self.options = options
backgroundColor = options.backgroundColor
translatesAutoresizingMaskIntoConstraints = false
setupLabel(title)
layoutLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Layout
private func setupLabel(title: String) {
titleLabel.text = title
titleLabel.textColor = options.textColor
titleLabel.font = options.font
addSubview(titleLabel)
}
private func layoutLabel() {
let viewsDictionary = ["label": titleLabel]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[label]|",
options: [],
metrics: nil,
views: viewsDictionary)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|",
options: [],
metrics: nil,
views: viewsDictionary)
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
let labelSize = calcLabelSize()
widthConstraint = NSLayoutConstraint(item: titleLabel, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: labelSize.width)
widthConstraint.active = true
}
private func calcLabelSize() -> CGSize {
let height = floor(labelSize.height) // why floor?
if options.menuAlign == .Fit {
let windowSize = UIApplication.sharedApplication().keyWindow!.bounds.size
let width = windowSize.width / CGFloat(options.menuItemCount)
return CGSizeMake(width, height)
} else {
let width = ceil(labelSize.width)
return CGSizeMake(width + options.menuItemMargin * 2, height)
}
}
}
| mit | 208129cf223a40ae5ab0a4a9928e4c7b | 36.284314 | 176 | 0.525638 | 6.306799 | false | false | false | false |
natecook1000/swift | stdlib/public/SDK/Foundation/Data.swift | 2 | 80964 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
import CoreFoundation
internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) {
munmap(mem, length)
}
internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) {
free(mem)
}
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
return data._isCompact()
}
#else
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
import _SwiftCoreFoundationOverlayShims
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) {
return data._isCompact()
} else {
var compact = true
let len = data.length
data.enumerateBytes { (_, byteRange, stop) in
if byteRange.length != len {
compact = false
}
stop.pointee = true
}
return compact
}
}
#endif
@usableFromInline
internal final class _DataStorage {
@usableFromInline
enum Backing {
// A mirror of the Objective-C implementation that is suitable to inline in Swift
case swift
// these two storage points for immutable and mutable data are reserved for references that are returned by "known"
// cases from Foundation in which implement the backing of struct Data, these have signed up for the concept that
// the backing bytes/mutableBytes pointer does not change per call (unless mutated) as well as the length is ok
// to be cached, this means that as long as the backing reference is retained no further objc_msgSends need to be
// dynamically dispatched out to the reference.
case immutable(NSData) // This will most often (perhaps always) be NSConcreteData
case mutable(NSMutableData) // This will often (perhaps always) be NSConcreteMutableData
// These are reserved for foreign sources where neither Swift nor Foundation are fully certain whom they belong
// to from an object inheritance standpoint, this means that all bets are off and the values of bytes, mutableBytes,
// and length cannot be cached. This also means that all methods are expected to dynamically dispatch out to the
// backing reference.
case customReference(NSData) // tracks data references that are only known to be immutable
case customMutableReference(NSMutableData) // tracks data references that are known to be mutable
}
static let maxSize = Int.max >> 1
static let vmOpsThreshold = NSPageSize() * 4
static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? {
if clear {
return calloc(1, size)
} else {
return malloc(size)
}
}
@usableFromInline
static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) {
var dest = dest_
var source = source_
var num = num_
if _DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 {
let pages = NSRoundDownToMultipleOfPageSize(num)
NSCopyMemoryPages(source!, dest, pages)
source = source!.advanced(by: pages)
dest = dest.advanced(by: pages)
num -= pages
}
if num > 0 {
memmove(dest, source!, num)
}
}
static func shouldAllocateCleared(_ size: Int) -> Bool {
return (size > (128 * 1024))
}
@usableFromInline
var _bytes: UnsafeMutableRawPointer?
@usableFromInline
var _length: Int
@usableFromInline
var _capacity: Int
@usableFromInline
var _needToZero: Bool
@usableFromInline
var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?
@usableFromInline
var _backing: Backing = .swift
@usableFromInline
var _offset: Int
@usableFromInline
var bytes: UnsafeRawPointer? {
@inlinable
get {
switch _backing {
case .swift:
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
case .immutable:
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
case .mutable:
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
case .customReference(let d):
return d.bytes.advanced(by: -_offset)
case .customMutableReference(let d):
return d.bytes.advanced(by: -_offset)
}
}
}
@usableFromInline
@discardableResult
func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
switch _backing {
case .swift: fallthrough
case .immutable: fallthrough
case .mutable:
return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, _length)))
case .customReference(let d):
if __NSDataIsCompact(d) {
let len = d.length
guard len > 0 else {
return try apply(UnsafeRawBufferPointer(start: nil, count: 0))
}
return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len)))
} else {
var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment)
defer { buffer.deallocate() }
let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count)
var enumerated = 0
d.enumerateBytes { (ptr, byteRange, stop) in
if byteRange.upperBound - _offset < range.lowerBound {
// before the range that we are looking for...
} else if byteRange.lowerBound - _offset > range.upperBound {
stop.pointee = true // we are past the range in question so we need to stop
} else {
// the byteRange somehow intersects the range in question that we are looking for...
let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound)
let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound)
let len = upper - lower
memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len)
enumerated += len
if upper == range.upperBound {
stop.pointee = true
}
}
}
return try apply(UnsafeRawBufferPointer(buffer))
}
case .customMutableReference(let d):
if __NSDataIsCompact(d) {
let len = d.length
guard len > 0 else {
return try apply(UnsafeRawBufferPointer(start: nil, count: 0))
}
return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len)))
} else {
var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment)
defer { buffer.deallocate() }
var enumerated = 0
d.enumerateBytes { (ptr, byteRange, stop) in
if byteRange.upperBound - _offset < range.lowerBound {
// before the range that we are looking for...
} else if byteRange.lowerBound - _offset > range.upperBound {
stop.pointee = true // we are past the range in question so we need to stop
} else {
// the byteRange somehow intersects the range in question that we are looking for...
let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound)
let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound)
let len = upper - lower
memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len)
enumerated += len
if upper == range.upperBound {
stop.pointee = true
}
}
}
return try apply(UnsafeRawBufferPointer(buffer))
}
}
}
@usableFromInline
@discardableResult
func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
switch _backing {
case .swift: fallthrough
case .mutable:
return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length)))
case .customMutableReference(let d):
let len = d.length
return try apply(UnsafeMutableRawBufferPointer(start: d.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len)))
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
_backing = .mutable(data)
_bytes = data.mutableBytes
return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length)))
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
_backing = .customMutableReference(data)
let len = data.length
return try apply(UnsafeMutableRawBufferPointer(start: data.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len)))
}
}
var mutableBytes: UnsafeMutableRawPointer? {
@inlinable
get {
switch _backing {
case .swift:
return _bytes?.advanced(by: -_offset)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .mutable(data)
_bytes = data.mutableBytes
return _bytes?.advanced(by: -_offset)
case .mutable:
return _bytes?.advanced(by: -_offset)
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .customMutableReference(data)
return data.mutableBytes.advanced(by: -_offset)
case .customMutableReference(let d):
return d.mutableBytes.advanced(by: -_offset)
}
}
}
@usableFromInline
var length: Int {
@inlinable
get {
switch _backing {
case .swift:
return _length
case .immutable:
return _length
case .mutable:
return _length
case .customReference(let d):
return d.length
case .customMutableReference(let d):
return d.length
}
}
@inlinable
set {
setLength(newValue)
}
}
func _freeBytes() {
if let bytes = _bytes {
if let dealloc = _deallocator {
dealloc(bytes, length)
} else {
free(bytes)
}
}
}
func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) {
var stopv: Bool = false
var data: NSData
switch _backing {
case .swift: fallthrough
case .immutable: fallthrough
case .mutable:
block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.count, _length)), 0, &stopv)
return
case .customReference(let d):
data = d
break
case .customMutableReference(let d):
data = d
break
}
data.enumerateBytes { (ptr, region, stop) in
// any region that is not in the range should be skipped
guard range.contains(region.lowerBound) || range.contains(region.upperBound) else { return }
var regionAdjustment = 0
if region.lowerBound < range.lowerBound {
regionAdjustment = range.lowerBound - (region.lowerBound - _offset)
}
let bytePtr = ptr.advanced(by: regionAdjustment).assumingMemoryBound(to: UInt8.self)
let effectiveLength = Swift.min((region.location - _offset) + region.length, range.upperBound) - (region.location - _offset)
block(UnsafeBufferPointer(start: bytePtr, count: effectiveLength - regionAdjustment), region.location + regionAdjustment - _offset, &stopv)
if stopv {
stop.pointee = true
}
}
}
@usableFromInline
@inline(never)
func _grow(_ newLength: Int, _ clear: Bool) {
let cap = _capacity
var additionalCapacity = (newLength >> (_DataStorage.vmOpsThreshold <= newLength ? 2 : 1))
if Int.max - additionalCapacity < newLength {
additionalCapacity = 0
}
var newCapacity = Swift.max(cap, newLength + additionalCapacity)
let origLength = _length
var allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity)
var newBytes: UnsafeMutableRawPointer? = nil
if _bytes == nil {
newBytes = _DataStorage.allocate(newCapacity, allocateCleared)
if newBytes == nil {
/* Try again with minimum length */
allocateCleared = clear && _DataStorage.shouldAllocateCleared(newLength)
newBytes = _DataStorage.allocate(newLength, allocateCleared)
}
} else {
let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4)
if allocateCleared && tryCalloc {
newBytes = _DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
/* Where calloc/memmove/free fails, realloc might succeed */
if newBytes == nil {
allocateCleared = false
if _deallocator != nil {
newBytes = _DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
_deallocator = nil
}
} else {
newBytes = realloc(_bytes!, newCapacity)
}
}
/* Try again with minimum length */
if newBytes == nil {
newCapacity = newLength
allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity)
if allocateCleared && tryCalloc {
newBytes = _DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
if newBytes == nil {
allocateCleared = false
newBytes = realloc(_bytes!, newCapacity)
}
}
}
if newBytes == nil {
/* Could not allocate bytes */
// At this point if the allocation cannot occur the process is likely out of memory
// and Bad-Things™ are going to happen anyhow
fatalError("unable to allocate memory for length (\(newLength))")
}
if origLength < newLength && clear && !allocateCleared {
memset(newBytes!.advanced(by: origLength), 0, newLength - origLength)
}
/* _length set by caller */
_bytes = newBytes
_capacity = newCapacity
/* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */
_needToZero = !allocateCleared
}
@inlinable
func setLength(_ length: Int) {
switch _backing {
case .swift:
let origLength = _length
let newLength = length
if _capacity < newLength || _bytes == nil {
_grow(newLength, true)
} else if origLength < newLength && _needToZero {
memset(_bytes! + origLength, 0, newLength - origLength)
} else if newLength < origLength {
_needToZero = true
}
_length = newLength
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .mutable(data)
_length = length
_bytes = data.mutableBytes
case .mutable(let d):
d.length = length
_length = length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.length = length
}
}
@inlinable
func append(_ bytes: UnsafeRawPointer, length: Int) {
precondition(length >= 0, "Length of appending bytes must not be negative")
switch _backing {
case .swift:
let origLength = _length
let newLength = origLength + length
if _capacity < newLength || _bytes == nil {
_grow(newLength, false)
}
_length = newLength
_DataStorage.move(_bytes!.advanced(by: origLength), bytes, length)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.append(bytes, length: length)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.append(bytes, length: length)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.append(bytes, length: length)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.append(bytes, length: length)
}
}
// fast-path for appending directly from another data storage
@inlinable
func append(_ otherData: _DataStorage, startingAt start: Int, endingAt end: Int) {
let otherLength = otherData.length
if otherLength == 0 { return }
if let bytes = otherData.bytes {
append(bytes.advanced(by: start), length: end - start)
}
}
@inlinable
func append(_ otherData: Data) {
otherData.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, _, _) in
append(buffer.baseAddress!, length: buffer.count)
}
}
@inlinable
func increaseLength(by extraLength: Int) {
if extraLength == 0 { return }
switch _backing {
case .swift:
let origLength = _length
let newLength = origLength + extraLength
if _capacity < newLength || _bytes == nil {
_grow(newLength, true)
} else if _needToZero {
memset(_bytes!.advanced(by: origLength), 0, extraLength)
}
_length = newLength
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.increaseLength(by: extraLength)
_backing = .mutable(data)
_length += extraLength
_bytes = data.mutableBytes
case .mutable(let d):
d.increaseLength(by: extraLength)
_length += extraLength
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.increaseLength(by: extraLength)
_backing = .customReference(data)
case .customMutableReference(let d):
d.increaseLength(by: extraLength)
}
}
@usableFromInline
func get(_ index: Int) -> UInt8 {
switch _backing {
case .swift: fallthrough
case .immutable: fallthrough
case .mutable:
return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
case .customReference(let d):
if __NSDataIsCompact(d) {
return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
} else {
var byte: UInt8 = 0
d.enumerateBytes { (ptr, range, stop) in
if NSLocationInRange(index, range) {
let offset = index - range.location - _offset
byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee
stop.pointee = true
}
}
return byte
}
case .customMutableReference(let d):
if __NSDataIsCompact(d) {
return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
} else {
var byte: UInt8 = 0
d.enumerateBytes { (ptr, range, stop) in
if NSLocationInRange(index, range) {
let offset = index - range.location - _offset
byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee
stop.pointee = true
}
}
return byte
}
}
}
@inlinable
func set(_ index: Int, to value: UInt8) {
switch _backing {
case .swift:
fallthrough
case .mutable:
_bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value
default:
var theByte = value
let range = NSRange(location: index, length: 1)
replaceBytes(in: range, with: &theByte, length: 1)
}
}
@inlinable
func replaceBytes(in range: NSRange, with bytes: UnsafeRawPointer?) {
if range.length == 0 { return }
switch _backing {
case .swift:
if _length < range.location + range.length {
let newLength = range.location + range.length
if _capacity < newLength {
_grow(newLength, false)
}
_length = newLength
}
_DataStorage.move(_bytes!.advanced(by: range.location - _offset), bytes!, range.length)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
}
}
@inlinable
func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) {
let range = NSRange(location: range_.location - _offset, length: range_.length)
let currentLength = _length
let resultingLength = currentLength - range.length + replacementLength
switch _backing {
case .swift:
let shift = resultingLength - currentLength
var mutableBytes = _bytes
if resultingLength > currentLength {
setLength(resultingLength)
mutableBytes = _bytes!
}
/* shift the trailing bytes */
let start = range.location
let length = range.length
if shift != 0 {
memmove(mutableBytes! + start + replacementLength, mutableBytes! + start + length, currentLength - start - length)
}
if replacementLength != 0 {
if let replacementBytes = replacementBytes {
memmove(mutableBytes! + start, replacementBytes, replacementLength)
} else {
memset(mutableBytes! + start, 0, replacementLength)
}
}
if resultingLength < currentLength {
setLength(resultingLength)
}
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .mutable(d)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
}
}
@inlinable
func resetBytes(in range_: NSRange) {
let range = NSRange(location: range_.location - _offset, length: range_.length)
if range.length == 0 { return }
switch _backing {
case .swift:
if _length < range.location + range.length {
let newLength = range.location + range.length
if _capacity < newLength {
_grow(newLength, false)
}
_length = newLength
}
memset(_bytes!.advanced(by: range.location), 0, range.length)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.resetBytes(in: range)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.resetBytes(in: range)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.resetBytes(in: range)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.resetBytes(in: range)
}
}
@usableFromInline
convenience init() {
self.init(capacity: 0)
}
@usableFromInline
init(length: Int) {
precondition(length < _DataStorage.maxSize)
var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
let clear = _DataStorage.shouldAllocateCleared(length)
_bytes = _DataStorage.allocate(capacity, clear)!
_capacity = capacity
_needToZero = !clear
_length = 0
_offset = 0
setLength(length)
}
@usableFromInline
init(capacity capacity_: Int) {
var capacity = capacity_
precondition(capacity < _DataStorage.maxSize)
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = 0
_bytes = _DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_offset = 0
}
@usableFromInline
init(bytes: UnsafeRawPointer?, length: Int) {
precondition(length < _DataStorage.maxSize)
_offset = 0
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
} else if _DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = _DataStorage.allocate(length, false)!
_DataStorage.move(_bytes!, bytes, length)
} else {
var capacity = length
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = _DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_DataStorage.move(_bytes!, bytes, length)
}
}
@usableFromInline
init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) {
precondition(length < _DataStorage.maxSize)
_offset = offset
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
if let dealloc = deallocator,
let bytes_ = bytes {
dealloc(bytes_, length)
}
} else if !copy {
_capacity = length
_length = length
_needToZero = false
_bytes = bytes
_deallocator = deallocator
} else if _DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = _DataStorage.allocate(length, false)!
_DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
} else {
var capacity = length
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = _DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
}
}
@usableFromInline
init(immutableReference: NSData, offset: Int) {
_offset = offset
_bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes)
_capacity = 0
_needToZero = false
_length = immutableReference.length
_backing = .immutable(immutableReference)
}
@usableFromInline
init(mutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = mutableReference.mutableBytes
_capacity = 0
_needToZero = false
_length = mutableReference.length
_backing = .mutable(mutableReference)
}
@usableFromInline
init(customReference: NSData, offset: Int) {
_offset = offset
_bytes = nil
_capacity = 0
_needToZero = false
_length = 0
_backing = .customReference(customReference)
}
@usableFromInline
init(customMutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = nil
_capacity = 0
_needToZero = false
_length = 0
_backing = .customMutableReference(customMutableReference)
}
deinit {
switch _backing {
case .swift:
_freeBytes()
default:
break
}
}
@inlinable
func mutableCopy(_ range: Range<Int>) -> _DataStorage {
switch _backing {
case .swift:
return _DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.count, copy: true, deallocator: nil, offset: range.lowerBound)
case .immutable(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
case .mutable(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
case .customReference(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
case .customMutableReference(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
}
}
func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T {
if range.isEmpty {
return try work(NSData()) // zero length data can be optimized as a singleton
}
switch _backing {
case .swift:
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false))
case .immutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false))
}
return try work(d)
case .mutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false))
}
return try work(d)
case .customReference(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false))
}
return try work(d)
case .customMutableReference(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false))
}
return try work(d)
}
}
func bridgedReference(_ range: Range<Int>) -> NSData {
if range.isEmpty {
return NSData() // zero length data can be optimized as a singleton
}
switch _backing {
case .swift:
return _NSSwiftData(backing: self, range: range)
case .immutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return _NSSwiftData(backing: self, range: range)
}
return d
case .mutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return _NSSwiftData(backing: self, range: range)
}
return d
case .customReference(let d):
guard range.lowerBound == 0 && range.upperBound == d.length else {
return _NSSwiftData(backing: self, range: range)
}
return d
case .customMutableReference(let d):
guard range.lowerBound == 0 && range.upperBound == d.length else {
return d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC()
}
return d.copy() as! NSData
}
}
@usableFromInline
func subdata(in range: Range<Data.Index>) -> Data {
switch _backing {
case .customReference(let d):
return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count))
case .customMutableReference(let d):
return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count))
default:
return Data(bytes: _bytes!.advanced(by: range.lowerBound - _offset), count: range.count)
}
}
}
internal class _NSSwiftData : NSData {
var _backing: _DataStorage!
var _range: Range<Data.Index>!
convenience init(backing: _DataStorage, range: Range<Data.Index>) {
self.init()
_backing = backing
_range = range
}
override var length: Int {
return _range.count
}
override var bytes: UnsafeRawPointer {
// NSData's byte pointer methods are not annotated for nullability correctly
// (but assume non-null by the wrapping macro guards). This placeholder value
// is to work-around this bug. Any indirection to the underlying bytes of an NSData
// with a length of zero would have been a programmer error anyhow so the actual
// return value here is not needed to be an allocated value. This is specifically
// needed to live like this to be source compatible with Swift3. Beyond that point
// this API may be subject to correction.
guard let bytes = _backing.bytes else {
return UnsafeRawPointer(bitPattern: 0xBAD0)!
}
return bytes.advanced(by: _range.lowerBound)
}
override func copy(with zone: NSZone? = nil) -> Any {
return self
}
override func mutableCopy(with zone: NSZone? = nil) -> Any {
return NSMutableData(bytes: bytes, length: length)
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@objc override
func _isCompact() -> Bool {
return true
}
#endif
#if DEPLOYMENT_RUNTIME_SWIFT
override func _providesConcreteBacking() -> Bool {
return true
}
#else
@objc(_providesConcreteBacking)
func _providesConcreteBacking() -> Bool {
return true
}
#endif
}
public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection {
public typealias ReferenceType = NSData
public typealias ReadingOptions = NSData.ReadingOptions
public typealias WritingOptions = NSData.WritingOptions
public typealias SearchOptions = NSData.SearchOptions
public typealias Base64EncodingOptions = NSData.Base64EncodingOptions
public typealias Base64DecodingOptions = NSData.Base64DecodingOptions
public typealias Index = Int
public typealias Indices = Range<Int>
@usableFromInline internal var _backing : _DataStorage
@usableFromInline internal var _sliceRange: Range<Index>
// A standard or custom deallocator for `Data`.
///
/// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated.
public enum Deallocator {
/// Use a virtual memory deallocator.
#if !DEPLOYMENT_RUNTIME_SWIFT
case virtualMemory
#endif
/// Use `munmap`.
case unmap
/// Use `free`.
case free
/// Do nothing upon deallocation.
case none
/// A custom deallocator.
case custom((UnsafeMutableRawPointer, Int) -> Void)
fileprivate var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) {
#if DEPLOYMENT_RUNTIME_SWIFT
switch self {
case .unmap:
return { __NSDataInvokeDeallocatorUnmap($0, $1) }
case .free:
return { __NSDataInvokeDeallocatorFree($0, $1) }
case .none:
return { _, _ in }
case .custom(let b):
return { (ptr, len) in
b(ptr, len)
}
}
#else
switch self {
case .virtualMemory:
return { NSDataDeallocatorVM($0, $1) }
case .unmap:
return { NSDataDeallocatorUnmap($0, $1) }
case .free:
return { NSDataDeallocatorFree($0, $1) }
case .none:
return { _, _ in }
case .custom(let b):
return { (ptr, len) in
b(ptr, len)
}
}
#endif
}
}
// MARK: -
// MARK: Init methods
/// Initialize a `Data` with copied memory content.
///
/// - parameter bytes: A pointer to the memory. It will be copied.
/// - parameter count: The number of bytes to copy.
public init(bytes: UnsafeRawPointer, count: Int) {
_backing = _DataStorage(bytes: bytes, length: count)
_sliceRange = 0..<count
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) {
let count = MemoryLayout<SourceType>.stride * buffer.count
_backing = _DataStorage(bytes: buffer.baseAddress, length: count)
_sliceRange = 0..<count
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) {
let count = MemoryLayout<SourceType>.stride * buffer.count
_backing = _DataStorage(bytes: buffer.baseAddress, length: count)
_sliceRange = 0..<count
}
/// Initialize a `Data` with a repeating byte pattern
///
/// - parameter repeatedValue: A byte to initialize the pattern
/// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue
public init(repeating repeatedValue: UInt8, count: Int) {
self.init(count: count)
withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Void in
memset(bytes, Int32(repeatedValue), count)
}
}
/// Initialize a `Data` with the specified size.
///
/// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount.
///
/// This method sets the `count` of the data to 0.
///
/// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page.
///
/// - parameter capacity: The size of the data.
public init(capacity: Int) {
_backing = _DataStorage(capacity: capacity)
_sliceRange = 0..<0
}
/// Initialize a `Data` with the specified count of zeroed bytes.
///
/// - parameter count: The number of bytes the data initially contains.
public init(count: Int) {
_backing = _DataStorage(length: count)
_sliceRange = 0..<count
}
/// Initialize an empty `Data`.
public init() {
_backing = _DataStorage(length: 0)
_sliceRange = 0..<0
}
/// Initialize a `Data` without copying the bytes.
///
/// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed.
/// - parameter bytes: A pointer to the bytes.
/// - parameter count: The size of the bytes.
/// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`.
public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) {
let whichDeallocator = deallocator._deallocator
_backing = _DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0)
_sliceRange = 0..<count
}
/// Initialize a `Data` with the contents of a `URL`.
///
/// - parameter url: The `URL` to read.
/// - parameter options: Options for the read operation. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if `url` cannot be read.
public init(contentsOf url: URL, options: Data.ReadingOptions = []) throws {
let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue))
_backing = _DataStorage(immutableReference: d, offset: 0)
_sliceRange = 0..<d.length
}
/// Initialize a `Data` from a Base-64 encoded String using the given options.
///
/// Returns nil when the input is not recognized as valid Base-64.
/// - parameter base64String: The string to parse.
/// - parameter options: Encoding options. Default value is `[]`.
public init?(base64Encoded base64String: String, options: Data.Base64DecodingOptions = []) {
if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) {
_backing = _DataStorage(immutableReference: d, offset: 0)
_sliceRange = 0..<d.length
} else {
return nil
}
}
/// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`.
///
/// Returns nil when the input is not recognized as valid Base-64.
///
/// - parameter base64Data: Base-64, UTF-8 encoded input data.
/// - parameter options: Decoding options. Default value is `[]`.
public init?(base64Encoded base64Data: Data, options: Data.Base64DecodingOptions = []) {
if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) {
_backing = _DataStorage(immutableReference: d, offset: 0)
_sliceRange = 0..<d.length
} else {
return nil
}
}
/// Initialize a `Data` by adopting a reference type.
///
/// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation.
///
/// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass.
///
/// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`.
public init(referencing reference: NSData) {
#if DEPLOYMENT_RUNTIME_SWIFT
let providesConcreteBacking = reference._providesConcreteBacking()
#else
let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false
#endif
if providesConcreteBacking {
_backing = _DataStorage(immutableReference: reference.copy() as! NSData, offset: 0)
_sliceRange = 0..<reference.length
} else {
_backing = _DataStorage(customReference: reference.copy() as! NSData, offset: 0)
_sliceRange = 0..<reference.length
}
}
// slightly faster paths for common sequences
@inlinable
public init<S: Sequence>(_ elements: S) where S.Iterator.Element == UInt8 {
let backing = _DataStorage(capacity: Swift.max(elements.underestimatedCount, 1))
var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: backing._bytes?.bindMemory(to: UInt8.self, capacity: backing._capacity), count: backing._capacity))
backing._length = endIndex
while var element = iter.next() {
backing.append(&element, length: 1)
}
self.init(backing: backing, range: 0..<backing._length)
}
@available(swift, introduced: 4.2)
@inlinable
public init<S: Sequence>(bytes elements: S) where S.Iterator.Element == UInt8 {
self.init(elements)
}
@available(swift, obsoleted: 4.2)
public init(bytes: Array<UInt8>) {
self.init(bytes)
}
@available(swift, obsoleted: 4.2)
public init(bytes: ArraySlice<UInt8>) {
self.init(bytes)
}
@usableFromInline
internal init(backing: _DataStorage, range: Range<Index>) {
_backing = backing
_sliceRange = range
}
@usableFromInline
internal func _validateIndex(_ index: Int, message: String? = nil) {
precondition(_sliceRange.contains(index), message ?? "Index \(index) is out of bounds of range \(_sliceRange)")
}
@usableFromInline
internal func _validateRange<R: RangeExpression>(_ range: R) where R.Bound == Int {
let lower = R.Bound(_sliceRange.lowerBound)
let upper = R.Bound(_sliceRange.upperBound)
let r = range.relative(to: lower..<upper)
precondition(r.lowerBound >= _sliceRange.lowerBound && r.lowerBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)")
precondition(r.upperBound >= _sliceRange.lowerBound && r.upperBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)")
}
// -----------------------------------
// MARK: - Properties and Functions
/// The number of bytes in the data.
public var count: Int {
get {
return _sliceRange.count
}
set {
precondition(count >= 0, "count must not be negative")
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.length = newValue
_sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + newValue)
}
}
/// Access the bytes in the data.
///
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
return try _backing.withUnsafeBytes(in: _sliceRange) {
return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!)
}
}
/// Mutate the bytes in the data.
///
/// This function assumes that you are mutating the contents.
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
return try _backing.withUnsafeMutableBytes(in: _sliceRange) {
return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!)
}
}
// MARK: -
// MARK: Copy Bytes
/// Copy the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter count: The number of bytes to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) {
precondition(count >= 0, "count of bytes to copy must not be negative")
if count == 0 { return }
_backing.withUnsafeBytes(in: _sliceRange) {
memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(count, $0.count))
}
}
private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) {
if range.length == 0 { return }
_backing.withUnsafeBytes(in: range.lowerBound..<range.upperBound) {
memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(range.length, $0.count))
}
}
/// Copy a subset of the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter range: The range in the `Data` to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) {
_copyBytesHelper(to: pointer, from: NSRange(range))
}
// Copy the contents of the data into a buffer.
///
/// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer.
/// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called.
/// - parameter buffer: A buffer to copy the data into.
/// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied.
/// - returns: Number of bytes copied into the destination buffer.
public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int {
let cnt = count
guard cnt > 0 else { return 0 }
let copyRange : Range<Index>
if let r = range {
guard !r.isEmpty else { return 0 }
copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count))
} else {
copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt)
}
_validateRange(copyRange)
guard !copyRange.isEmpty else { return 0 }
let nsRange = NSRange(location: copyRange.lowerBound, length: copyRange.upperBound - copyRange.lowerBound)
_copyBytesHelper(to: buffer.baseAddress!, from: nsRange)
return copyRange.count
}
// MARK: -
#if !DEPLOYMENT_RUNTIME_SWIFT
private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool {
// Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation.
if !options.contains(.atomic) {
#if os(macOS)
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max)
#else
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max)
#endif
} else {
return false
}
}
#endif
/// Write the contents of the `Data` to a location.
///
/// - parameter url: The location to write the data into.
/// - parameter options: Options for writing the data. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`.
public func write(to url: URL, options: Data.WritingOptions = []) throws {
try _backing.withInteriorPointerReference(_sliceRange) {
#if DEPLOYMENT_RUNTIME_SWIFT
try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue))
#else
if _shouldUseNonAtomicWriteReimplementation(options: options) {
var error: NSError? = nil
guard __NSDataWriteToURL($0, url, options, &error) else { throw error! }
} else {
try $0.write(to: url, options: options)
}
#endif
}
}
// MARK: -
/// Find the given `Data` in the content of this `Data`.
///
/// - parameter dataToFind: The data to be searched for.
/// - parameter options: Options for the search. Default value is `[]`.
/// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data.
/// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found.
/// - precondition: `range` must be in the bounds of the Data.
public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? {
let nsRange : NSRange
if let r = range {
_validateRange(r)
nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound)
} else {
nsRange = NSRange(location: 0, length: count)
}
let result = _backing.withInteriorPointerReference(_sliceRange) {
$0.range(of: dataToFind, options: options, in: nsRange)
}
if result.location == NSNotFound {
return nil
}
return (result.location + startIndex)..<((result.location + startIndex) + result.length)
}
/// Enumerate the contents of the data.
///
/// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes.
/// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`.
public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) {
_backing.enumerateBytes(in: _sliceRange, block)
}
@inlinable
internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
if buffer.isEmpty { return }
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.replaceBytes(in: NSRange(location: _sliceRange.upperBound, length: _backing.length - (_sliceRange.upperBound - _backing._offset)), with: buffer.baseAddress, length: buffer.count * MemoryLayout<SourceType>.stride)
_sliceRange = _sliceRange.lowerBound..<(_sliceRange.upperBound + buffer.count * MemoryLayout<SourceType>.stride)
}
public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) {
if count == 0 { return }
_append(UnsafeBufferPointer(start: bytes, count: count))
}
public mutating func append(_ other: Data) {
other.enumerateBytes { (buffer, _, _) in
_append(buffer)
}
}
/// Append a buffer of bytes to the data.
///
/// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
_append(buffer)
}
public mutating func append(contentsOf bytes: [UInt8]) {
bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in
_append(buffer)
}
}
@inlinable
public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Iterator.Element {
let underestimatedCount = Swift.max(newElements.underestimatedCount, 1)
_withStackOrHeapBuffer(underestimatedCount) { (buffer) in
let capacity = buffer.pointee.capacity
let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity)
var (iter, endIndex) = newElements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity))
_append(UnsafeBufferPointer(start: base, count: endIndex))
while var element = iter.next() {
append(&element, count: 1)
}
}
}
// MARK: -
/// Set a region of the data to `0`.
///
/// If `range` exceeds the bounds of the data, then the data is resized to fit.
/// - parameter range: The range in the data to set to `0`.
public mutating func resetBytes(in range: Range<Index>) {
// it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth)
precondition(range.lowerBound >= 0, "Ranges must not be negative bounds")
precondition(range.upperBound >= 0, "Ranges must not be negative bounds")
let range = NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.resetBytes(in: range)
if _sliceRange.upperBound < range.upperBound {
_sliceRange = _sliceRange.lowerBound..<range.upperBound
}
}
/// Replace a region of bytes in the data with new data.
///
/// This will resize the data if required, to fit the entire contents of `data`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append.
/// - parameter data: The replacement data.
public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) {
let cnt = data.count
data.withUnsafeBytes {
replaceSubrange(subrange, with: $0, count: cnt)
}
}
/// Replace a region of bytes in the data with new bytes from a buffer.
///
/// This will resize the data if required, to fit the entire contents of `buffer`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace.
/// - parameter buffer: The replacement bytes.
public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) {
guard !buffer.isEmpty else { return }
replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride)
}
/// Replace a region of bytes in the data with new bytes from a collection.
///
/// This will resize the data if required, to fit the entire contents of `newElements`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace.
/// - parameter newElements: The replacement bytes.
public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element {
_validateRange(subrange)
let totalCount: Int = numericCast(newElements.count)
_withStackOrHeapBuffer(totalCount) { conditionalBuffer in
let buffer = UnsafeMutableBufferPointer(start: conditionalBuffer.pointee.memory.assumingMemoryBound(to: UInt8.self), count: totalCount)
var (iterator, index) = newElements._copyContents(initializing: buffer)
while let byte = iterator.next() {
buffer[index] = byte
index = buffer.index(after: index)
}
replaceSubrange(subrange, with: conditionalBuffer.pointee.memory, count: totalCount)
}
}
public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) {
_validateRange(subrange)
let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
let upper = _sliceRange.upperBound
_backing.replaceBytes(in: nsRange, with: bytes, length: cnt)
let resultingUpper = upper - nsRange.length + cnt
_sliceRange = _sliceRange.lowerBound..<resultingUpper
}
/// Return a new copy of the data in a specified range.
///
/// - parameter range: The range to copy.
public func subdata(in range: Range<Index>) -> Data {
_validateRange(range)
if isEmpty {
return Data()
}
return _backing.subdata(in: range)
}
// MARK: -
//
/// Returns a Base-64 encoded string.
///
/// - parameter options: The options to use for the encoding. Default value is `[]`.
/// - returns: The Base-64 encoded string.
public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String {
return _backing.withInteriorPointerReference(_sliceRange) {
return $0.base64EncodedString(options: options)
}
}
/// Returns a Base-64 encoded `Data`.
///
/// - parameter options: The options to use for the encoding. Default value is `[]`.
/// - returns: The Base-64 encoded data.
public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data {
return _backing.withInteriorPointerReference(_sliceRange) {
return $0.base64EncodedData(options: options)
}
}
// MARK: -
//
/// The hash value for the data.
public var hashValue: Int {
var hashValue = 0
let hashRange: Range<Int> = _sliceRange.lowerBound..<Swift.min(_sliceRange.lowerBound + 80, _sliceRange.upperBound)
_withStackOrHeapBuffer(hashRange.count + 1) { buffer in
if !hashRange.isEmpty {
_backing.withUnsafeBytes(in: hashRange) {
memcpy(buffer.pointee.memory, $0.baseAddress!, hashRange.count)
}
}
hashValue = Int(bitPattern: CFHashBytes(buffer.pointee.memory.assumingMemoryBound(to: UInt8.self), hashRange.count))
}
return hashValue
}
public func advanced(by amount: Int) -> Data {
_validateIndex(startIndex + amount)
let length = count - amount
precondition(length > 0)
return withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data in
return Data(bytes: ptr.advanced(by: amount), count: length)
}
}
// MARK: -
// MARK: -
// MARK: Index and Subscript
/// Sets or returns the byte at the specified index.
public subscript(index: Index) -> UInt8 {
get {
_validateIndex(index)
return _backing.get(index)
}
set {
_validateIndex(index)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.set(index, to: newValue)
}
}
public subscript(bounds: Range<Index>) -> Data {
get {
_validateRange(bounds)
return Data(backing: _backing, range: bounds)
}
set {
replaceSubrange(bounds, with: newValue)
}
}
public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data
where R.Bound: FixedWidthInteger {
get {
let lower = R.Bound(_sliceRange.lowerBound)
let upper = R.Bound(_sliceRange.upperBound)
let range = rangeExpression.relative(to: lower..<upper)
let start: Int = numericCast(range.lowerBound)
let end: Int = numericCast(range.upperBound)
let r: Range<Int> = start..<end
_validateRange(r)
return Data(backing: _backing, range: r)
}
set {
let lower = R.Bound(_sliceRange.lowerBound)
let upper = R.Bound(_sliceRange.upperBound)
let range = rangeExpression.relative(to: lower..<upper)
let start: Int = numericCast(range.lowerBound)
let end: Int = numericCast(range.upperBound)
let r: Range<Int> = start..<end
_validateRange(r)
replaceSubrange(r, with: newValue)
}
}
/// The start `Index` in the data.
public var startIndex: Index {
get {
return _sliceRange.lowerBound
}
}
/// The end `Index` into the data.
///
/// This is the "one-past-the-end" position, and will always be equal to the `count`.
public var endIndex: Index {
get {
return _sliceRange.upperBound
}
}
public func index(before i: Index) -> Index {
return i - 1
}
public func index(after i: Index) -> Index {
return i + 1
}
public var indices: Range<Int> {
get {
return startIndex..<endIndex
}
}
public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) {
guard !isEmpty else { return (makeIterator(), buffer.startIndex) }
guard let p = buffer.baseAddress else {
preconditionFailure("Attempt to copy contents into nil buffer pointer")
}
let cnt = count
precondition(cnt <= buffer.count, "Insufficient space allocated to copy Data contents")
withUnsafeBytes { p.initialize(from: $0, count: cnt) }
return (Iterator(endOf: self), buffer.index(buffer.startIndex, offsetBy: cnt))
}
/// An iterator over the contents of the data.
///
/// The iterator will increment byte-by-byte.
public func makeIterator() -> Data.Iterator {
return Iterator(self)
}
public struct Iterator : IteratorProtocol {
// Both _data and _endIdx should be 'let' rather than 'var'.
// They are 'var' so that the stored properties can be read
// independently of the other contents of the struct. This prevents
// an exclusivity violation when reading '_endIdx' and '_data'
// while simultaneously mutating '_buffer' with the call to
// withUnsafeMutablePointer(). Once we support accessing struct
// let properties independently we should make these variables
// 'let' again.
private var _data: Data
private var _buffer: (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
private var _idx: Data.Index
private var _endIdx: Data.Index
fileprivate init(_ data: Data) {
_data = data
_buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
_idx = data.startIndex
_endIdx = data.endIndex
}
fileprivate init(endOf data: Data) {
self._data = data
_buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
_idx = data.endIndex
_endIdx = data.endIndex
}
public mutating func next() -> UInt8? {
guard _idx < _endIdx else { return nil }
defer { _idx += 1 }
let bufferSize = MemoryLayout.size(ofValue: _buffer)
return withUnsafeMutablePointer(to: &_buffer) { ptr_ in
let ptr = UnsafeMutableRawPointer(ptr_).assumingMemoryBound(to: UInt8.self)
let bufferIdx = (_idx - _data.startIndex) % bufferSize
if bufferIdx == 0 {
// populate the buffer
_data.copyBytes(to: ptr, from: _idx..<(_endIdx - _idx > bufferSize ? _idx + bufferSize : _endIdx))
}
return ptr[bufferIdx]
}
}
}
// MARK: -
//
@available(*, unavailable, renamed: "count")
public var length: Int {
get { fatalError() }
set { fatalError() }
}
@available(*, unavailable, message: "use withUnsafeBytes instead")
public var bytes: UnsafeRawPointer { fatalError() }
@available(*, unavailable, message: "use withUnsafeMutableBytes instead")
public var mutableBytes: UnsafeMutableRawPointer { fatalError() }
/// Returns `true` if the two `Data` arguments are equal.
public static func ==(d1 : Data, d2 : Data) -> Bool {
let backing1 = d1._backing
let backing2 = d2._backing
if backing1 === backing2 {
if d1._sliceRange == d2._sliceRange {
return true
}
}
let length1 = d1.count
if length1 != d2.count {
return false
}
if backing1.bytes == backing2.bytes {
if d1._sliceRange == d2._sliceRange {
return true
}
}
if length1 > 0 {
return d1.withUnsafeBytes { (b1) in
return d2.withUnsafeBytes { (b2) in
return memcmp(b1, b2, length1) == 0
}
}
}
return true
}
}
extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
/// A human-readable description for the data.
public var description: String {
return "\(self.count) bytes"
}
/// A human-readable debug description for the data.
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
let nBytes = self.count
var children: [(label: String?, value: Any)] = []
children.append((label: "count", value: nBytes))
self.withUnsafeBytes { (bytes : UnsafePointer<UInt8>) in
children.append((label: "pointer", value: bytes))
}
// Minimal size data is output as an array
if nBytes < 64 {
children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)])))
}
let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct)
return m
}
}
extension Data {
@available(*, unavailable, renamed: "copyBytes(to:count:)")
public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { }
@available(*, unavailable, renamed: "copyBytes(to:from:)")
public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { }
}
/// Provides bridging functionality for struct Data to class NSData and vice-versa.
extension Data : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSData {
return _backing.bridgedReference(_sliceRange)
}
public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
result = Data(referencing: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
result = Data(referencing: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data {
guard let src = source else { return Data() }
return Data(referencing: src)
}
}
extension NSData : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self))
}
}
extension Data : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
// It's more efficient to pre-allocate the buffer if we can.
if let count = container.count {
self.init(count: count)
// Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space.
// We don't want to write past the end of what we allocated.
for i in 0 ..< count {
let byte = try container.decode(UInt8.self)
self[i] = byte
}
} else {
self.init()
}
while !container.isAtEnd {
var byte = try container.decode(UInt8.self)
self.append(&byte, count: 1)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
// Since enumerateBytes does not rethrow, we need to catch the error, stow it away, and rethrow if we stopped.
var caughtError: Error? = nil
self.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, byteIndex: Data.Index, stop: inout Bool) in
do {
try container.encode(contentsOf: buffer)
} catch {
caughtError = error
stop = true
}
}
if let error = caughtError {
throw error
}
}
}
| apache-2.0 | 5fa4210893c94e60ee7f845debcb5082 | 40.328229 | 352 | 0.593044 | 4.929493 | false | false | false | false |