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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CoBug92/MyRestaurant
|
MyRestraunts/MyRestaurantTableViewController.swift
|
1
|
14001
|
//
// MyRestaurantTableViewController.swift
// MyRestaurant
//
// Created by Богдан Костюченко on 03/10/16.
// Copyright © 2016 Bogdan Kostyuchenko. All rights reserved.
//
import UIKit
import CoreData
class MyRestaurantTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {
@IBAction func unwindSegue(segue: UIStoryboardSegue) {
}
var restaurants: [Restaurant] = []
var searchController: UISearchController! //Объект который занимается поиском
var filterResultArray: [Restaurant] = [] //массив в который будет помещаться все результаты которые удовлетворяют поиску
var fetchResultsController: NSFetchedResultsController<Restaurant>!
override func viewDidLoad() {
super.viewDidLoad()
//Work with searchBar
searchController = UISearchController(searchResultsController: nil) //Nil because we want that point of entry blocked main list
searchController.searchResultsUpdater = self //какой котроллер будет обновлять результаты
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false //if true the controller dims
tableView.tableHeaderView = searchController.searchBar //SearchBar located in the header of table
definesPresentationContext = true //SearchBar works only on the mainPage (doesn't save in detailView)
//Create query
let fetchRequest: NSFetchRequest<Restaurant> = Restaurant.fetchRequest()
//Create descriptor
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
//For getting data
fetchRequest.sortDescriptors = [sortDescriptor]
//Create context
if let context = (UIApplication.shared.delegate as? AppDelegate)?.coreDataStack.persistentContainer.viewContext {
fetchResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fetchResultsController.delegate = self
//try to take data
do {
try fetchResultsController.performFetch()
//all data write in restaurants
restaurants = fetchResultsController.fetchedObjects!
} catch let error as NSError {
print("Couldn't save data \(error.localizedDescription)")
}
//reload table
tableView.reloadData()
}
//Clear unnecessary dividers
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
//Change the interface of BACK button
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
//Autosizing cell
self.tableView.estimatedRowHeight = 85 //default height of cell (for increase capacity)
self.tableView.rowHeight = UITableViewAutomaticDimension //Height is calculated automatically
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.searchController.hidesNavigationBarDuringPresentation = false
//NavigationBar hides
self.navigationController?.hidesBarsOnSwipe = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let userDefaults = UserDefaults.standard
let wasInWatched = userDefaults.bool(forKey: "wasInWatched")
guard !wasInWatched else { return }
//Вызов PageViewController по его идентификатору
if let PageViewController = storyboard?.instantiateViewController(withIdentifier: "pageViewController") as? PageViewController {
//отображаем контроллер
present(PageViewController, animated: true, completion: nil)
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1 //Count of sections in TableView
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
return filterResultArray.count
} else {
return restaurants.count //Count of rows in Section
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MyRestaurantTableViewCell
let restaurant = restaurantToDisplayAt(indexPath: indexPath)
//Configurate the cell:
//Writes the value of MyRestaurant.name in nameLabel
cell.nameLabel.text = restaurant.name
//Writes the value of MyRestaurant.type in typeLabel
cell.typeLabel.text = restaurant.type
//Writes the value of MyRestaurant.location in locationLabel
cell.locationLabel.text = restaurant.location
cell.checkImageView.isHidden = !restaurant.wasVisited
//Write the value of MyRestaurant.image in thumbnailImageView
cell.thumbnailImageView.image = UIImage(data: restaurant .image as! Data)
//Create the round pictures
//The side of square is equal the diameter of circle, that why /2
cell.thumbnailImageView.layer.cornerRadius = cell.thumbnailImageView.frame.size.height/2
cell.thumbnailImageView.clipsToBounds = true //Give access to change the ImageView
return cell
}
//Function creates swipe menu with additional buttons
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
//Create variable which will responsible for delete button
let deleteAction = UITableViewRowAction(style: .default, title: "Delete") { (action, indexPath) in
let context = (UIApplication.shared.delegate as! AppDelegate).coreDataStack.persistentContainer.viewContext
let objectToDelete = self.fetchResultsController.object(at: indexPath)
context.delete(objectToDelete)
do {
try context.save()
} catch {
print(error.localizedDescription)
}
tableView.reloadData()
}
//Create action menu when user clicks "Share"
let shareAction = UITableViewRowAction(style: .default, title: "Share") { (action, indexPath) in
// Share item by indexPath
let defaultText = "I am in \(self.restaurants[indexPath.row].name) now"
if let image = UIImage(data: self.restaurants[indexPath.row].image as! Data) {
let activityController = UIActivityViewController(activityItems: [defaultText, image], applicationActivities: nil)
self.present(activityController, animated: true, completion: nil)
}
}
//Change the color of Share button
shareAction.backgroundColor = UIColor(red: 63 / 255, green: 84 / 255, blue: 242 / 255, alpha: 1)
//return 2 possible button in action menu
return [deleteAction, shareAction]
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Delete selecting of row
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK: - Fetch results controller delegate
//вызывается перед тем как контроллер поменяет свой контент
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert: guard let indexPath = newIndexPath else { break }
tableView.insertRows(at: [indexPath], with: .fade)
case .delete: guard let indexPath = indexPath else { break }
tableView.deleteRows(at: [indexPath], with: .fade)
case .update: guard let indexPath = indexPath else { break }
tableView.reloadRows(at: [indexPath], with: .fade)
default: tableView.reloadData()
}
restaurants = controller.fetchedObjects as! [Restaurant]
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
//MARK: - Functions
//метод для отфильтровки результатов для filterResultArray
func filterContentSearch(searchText text: String){
filterResultArray = restaurants.filter{ (restaurant) -> Bool in
//в наш массив попадают элементы restaurant с маленькой буквы
return (restaurant.name?.lowercased().contains(text.lowercased()))!
}
}
func restaurantToDisplayAt(indexPath: IndexPath) -> Restaurant{
let restaurant: Restaurant
if searchController.isActive && searchController.searchBar.text != "" {
restaurant = filterResultArray[indexPath.row]
} else {
restaurant = restaurants[indexPath.row]
}
return restaurant
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DetailsSegue" {
if let indexPath = self.tableView.indexPathForSelectedRow{
let destinationVC = segue.destination as! DetailsViewController
destinationVC.restaurant = restaurantToDisplayAt(indexPath: indexPath)
}
}
}
// //The massive responsible for Restaurant objects
// var MyRestaurant: [Restaurant] = [
// Restaurant(name: "Barrafina", type: "Bar", image: "Barrafina", location: "10 Adelaide Street, Covent Garden, London", wasVisited: false),
// Restaurant(name: "Bourkestreetbakery", type: "Bakery", image: "Bourkestreetbakery", location: "480 Bourke St, Melbourne VIC 3000, Australia", wasVisited: false),
// Restaurant(name: "Cafe Deadend", type: "Cafe", image: "Cafedeadend", location: "72 Po Hing Fong, Hong Kong", wasVisited: false),
// Restaurant(name: "Cafe Lore", type: "Cafe", image: "Cafelore", location: "4601 4th Ave, Brooklyn, NY 11220, United States", wasVisited: false),
// Restaurant(name: "Confessional", type: "Restaurant", image: "Confessional", location: "308 E 6th St, New York, NY 10003, USA", wasVisited: false),
// Restaurant(name: "Donostia", type: "Restaurant", image: "Donostia", location: " 10 Seymour Pl, London W1H 7ND, United Kingdom", wasVisited: false),
// Restaurant(name: "Five Leaves", type: "Bar", image: "Fiveleaves", location: "18 Bedford Ave, Brooklyn, NY 11222, United States", wasVisited: false),
// Restaurant(name: "For Kee", type: "Restaurant", image: "Forkeerestaurant", location: "200 Hollywood Rd, Sheung Wan, Hong Kong", wasVisited: false),
// Restaurant(name: "Graham avenue meats", type: "Restaurant", image: "Grahamavenuemeats", location: "445 Graham Ave, Brooklyn, NY 11211, United States", wasVisited: false),
// Restaurant(name: "Haigh's chocolate", type: "Chocolate shope", image: "Haighschocolate", location: "The Strand Arcade, 1/412-414 George St, Sydney NSW 2000, Australia", wasVisited: false),
// Restaurant(name: "Homei", type: "Restaurant", image: "Homei", location: "Shop 8/38-52 Waterloo St, Surry Hills NSW 2010, Australia", wasVisited: false),
// Restaurant(name: "Palomino Espresso", type: "Espresso Bar", image: "Palominoespresso", location: "1/61 York St, Sydney NSW 2000, Australia", wasVisited: false),
// Restaurant(name: "Po's Atelier", type: "Bakery", image: "Posatelier", location: "70 Po Hing Fong, Hong Kong", wasVisited: false),
// Restaurant(name: "Teakha", type: "Cafe", image: "Teakha", location: "18 Tai Ping Shan St, Hong Kong", wasVisited: false),
// Restaurant(name: "Traif", type: "Restaurant", image: "Traif", location: "229 S 4th St, Brooklyn, NY 11211, United States", wasVisited: false),
// Restaurant(name: "Upstate", type: "Seafood Restaurant", image: "Upstate", location: "95 1st Avenue, New York, NY 10003, United States", wasVisited: false),
// Restaurant(name: "Waffle & Wolf", type: "Sandwich Shop", image: "Wafflewolf", location: "413 Graham Ave, Brooklyn, NY 11211, United States", wasVisited: false)
// ]
}
extension MyRestaurantTableViewController: UISearchResultsUpdating {
//метод автоматически срабатывает когда мы что либо меняем в поисковой строке
func updateSearchResults(for searchController: UISearchController) {
filterContentSearch(searchText: searchController.searchBar.text!)
tableView.reloadData() //заново срабатывае cellForRowAtIndexPath
}
}
extension MyRestaurantTableViewController: UISearchBarDelegate {
//когда мы щелкнули на поисковую строку
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
if searchBar.text == "" {
navigationController?.hidesBarsOnSwipe = false
}
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
navigationController?.hidesBarsOnSwipe = true
}
}
|
gpl-3.0
|
88a791502b026bd451dfc1d72d5f516d
| 51.378378 | 202 | 0.674775 | 4.790254 | false | false | false | false |
things-nyc/mapthethings-ios
|
MapTheThings/DevicesViewController.swift
|
1
|
5932
|
//
// DevicesViewController.swift
// MapTheThings
//
// Created by Frank on 2017/1/12.
// Copyright © 2017 The Things Network New York. All rights reserved.
//
import UIKit
import ReactiveSwift
import Crashlytics
extension UIImage {
class func circle(_ diameter: CGFloat, color: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(CGSize(width: diameter, height: diameter), false, 0)
if let ctx = UIGraphicsGetCurrentContext() {
defer {
UIGraphicsEndImageContext()
}
ctx.saveGState()
defer {
ctx.restoreGState()
}
let rect = CGRect(x: 0, y: 0, width: diameter, height: diameter)
ctx.setFillColor(color.cgColor)
ctx.fillEllipse(in: rect)
if let img = UIGraphicsGetImageFromCurrentImageContext() {
return img
}
}
return nil
}
}
class DeviceCellView : UITableViewCell {
@IBOutlet weak var deviceName: UILabel!
@IBOutlet weak var connectedImage: UIImageView!
}
class DevicesViewController: UITableViewController {
var stateDisposer: Disposable?
func observeAppState() {
// Copied from AppStateViewController because this inherits differently. Should mix in.
// Listen for app state changes...
self.stateDisposer = appStateObservable.observe(on: QueueScheduler.main).observeValues({state in
//print(state)
self.renderAppState(state.old, state: state.new)
})
}
@IBOutlet weak var refreshButton: UIBarButtonItem?
var state: AppState? = nil
var devices: [Device] = []
let connectedImage = UIImage.circle(15, color: UIColor.green)
func renderAppState(_ oldState: AppState, state: AppState) {
self.state = state
self.devices = state.bluetooth.values.sorted(by: { (a, b) -> Bool in
return a.identifier.uuidString < b.identifier.uuidString
})
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.refreshButton!.target = self
self.refreshButton!.action = #selector(DevicesViewController.rescanBluetooth)
observeAppState()
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
let signal = appStateProperty.value
renderAppState(signal.old, state: signal.new)
}
@IBAction func rescanBluetooth(_ sender: UIButton) {
Answers.logCustomEvent(withName: "RescanBT", customAttributes: nil)
debugPrint("rescanBluetooth")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.bluetooth!.rescan()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return devices.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DeviceCell", for: indexPath) as! DeviceCellView
let device = self.devices[indexPath.row]
cell.deviceName.text = device.name
cell.connectedImage.image = device.connected ? connectedImage : nil
// cell.detailTextLabel?.text = device.identifier.uuidString
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let row = self.tableView.indexPathForSelectedRow?.row {
updateAppState({
var state = $0
state.viewDetailDeviceID = self.devices[row].identifier
return state
})
}
}
}
|
mit
|
67b3ad47d692fe33248f7b801488ec58
| 34.51497 | 136 | 0.648794 | 5.234775 | false | false | false | false |
abhayamrastogi/ChatSDKPodSpecs
|
rgconnectsdk/Managers/RGConnectSharedManager.swift
|
1
|
2181
|
//
// RGConnectSharedManager.swift
// rgconnectsdk
//
// Created by Anurag Agnihotri on 21/07/16.
// Copyright © 2016 RoundGlass Partners. All rights reserved.
//
import Foundation
public class RGConnectSharedManager: NSObject {
/**
* Service Class Variables.
*
*/
public var chatMessageService: RGChatMessageService!
public var userService: RGUserService!
public var chatRoomService: RGChatRoomService!
public var notificationService: RGNotificationService!
private var socketManager: RGSocketManager!
/**
Static singleton instance for RGConnectSharedManager.
- returns: <#return value description#>
*/
public static func sharedInstance() -> RGConnectSharedManager {
return RGConnectSharedManager()
}
/**
Initialize RGConnectSharedManager.
- returns: <#return value description#>
*/
override init() {
super.init()
// TODO:- Look into initialisation of Services and Socket Manager. Should not clash.
self.socketManager = RGSocketManager()
let meteorClient = MeteorService.initializeMeteor()
MeteorService.addMeteorSubscriptions(meteorClient)
self.initializeServices(meteorClient)
}
/**
Function to initialize Services.
- parameter meteorClient: Meteor Client Object to initialize all the Services.
*/
private func initializeServices(meteorClient: MeteorClient) {
self.chatMessageService = RGChatMessageService(meteorClient: meteorClient)
self.userService = RGUserService(meteorClient: meteorClient)
self.chatRoomService = RGChatRoomService(meteorClient: meteorClient)
self.notificationService = RGNotificationService(meteorClient: meteorClient)
}
/**
Method to Add Delegate to the Socket Manager Class. All the socket connection activities will be broadcasted on these delegates.
- parameter delegate: RGConnectDelegate Subclass.
*/
public func addDelegate(delegate: RGConnectChatDelegate) {
self.socketManager.delegates.append(delegate)
}
}
|
mit
|
0a49ae4d7011b190eeddd6c0427e3ac4
| 28.472973 | 133 | 0.687156 | 5.023041 | false | false | false | false |
KrishMunot/swift
|
test/IDE/import_as_member.swift
|
1
|
2935
|
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.A -always-argument-labels > %t.printed.A.txt
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.B -always-argument-labels > %t.printed.B.txt
// RUN: FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt
// RUN: FileCheck %s -check-prefix=PRINTB -strict-whitespace < %t.printed.B.txt
// PRINT: struct Struct1 {
// PRINT-NEXT: var x: Double
// PRINT-NEXT: var y: Double
// PRINT-NEXT: var z: Double
// PRINT-NEXT: init()
// PRINT-NEXT: init(x x: Double, y y: Double, z z: Double)
// PRINT-NEXT: }
// Make sure the other extension isn't here.
// PRINT-NOT: static var static1: Double
// PRINT: extension Struct1 {
// PRINT-NEXT: static var globalVar: Double
// PRINT-NEXT: init(value value: Double)
// PRINT-NEXT: func inverted() -> Struct1
// PRINT-NEXT: mutating func invert()
// PRINT-NEXT: func translate(radians radians: Double) -> Struct1
// PRINT-NEXT: func scale(_ radians: Double) -> Struct1
// PRINT-NEXT: var radius: Double { get nonmutating set }
// PRINT-NEXT: var altitude: Double{{$}}
// PRINT-NEXT: var magnitude: Double { get }
// PRINT-NEXT: static func staticMethod() -> Int32
// PRINT-NEXT: static var property: Int32
// PRINT-NEXT: static var getOnlyProperty: Int32 { get }
// PRINT-NEXT: func selfComesLast(x x: Double)
// PRINT-NEXT: func selfComesThird(a a: Int32, b b: Float, x x: Double)
// PRINT-NEXT: }
// PRINT-NOT: static var static1: Double
// Make sure the other extension isn't here.
// PRINTB-NOT: static var globalVar: Double
// PRINTB: extension Struct1 {
// PRINTB: static var static1: Double
// PRINTB-NEXT: static var static2: Float
// PRINTB-NEXT: init(float value: Float)
// PRINTB-NEXT: static var zero: Struct1 { get }
// PRINTB-NEXT: }
// PRINTB: var currentStruct1: Struct1
// PRINTB-NOT: static var globalVar: Double
// RUN: %target-parse-verify-swift -I %S/Inputs/custom-modules
import ImportAsMember.A
import ImportAsMember.B
let iamStructFail = IAMStruct1CreateSimple()
// expected-error@-1{{use of unresolved identifier 'IAMStruct1CreateSimple'}}
var iamStruct = Struct1(x: 1.0, y: 1.0, z: 1.0)
let gVarFail = IAMStruct1GlobalVar
// expected-error@-1{{use of unresolved identifier 'IAMStruct1GlobalVar'}}
let gVar = Struct1.globalVar
print("\(gVar)")
let iamStructInitFail = IAMStruct1CreateSimple(42)
// expected-error@-1{{use of unresolved identifier 'IAMStruct1CreateSimple'}}
let iamStructInitFail = Struct1(value: 42)
let gVar2 = Struct1.static2
// Instance properties
iamStruct.radius += 1.5
_ = iamStruct.magnitude
// Static properties
iamStruct = Struct1.zero
// Global properties
currentStruct1.x += 1.5
|
apache-2.0
|
bdde61f38bf6311734ac078a188251b8
| 36.151899 | 206 | 0.705281 | 3.204148 | false | false | false | false |
threemonkee/VCLabs
|
VCLabs/UIKit Catalog/Source Code/SearchShowResultsInSourceViewController.swift
|
1
|
1368
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to show search results from a search controller within the source view controller (in this case, in the table view's header view).
*/
import UIKit
class SearchShowResultsInSourceViewController: SearchResultsViewController {
// MARK: Properties
// `searchController` is set in `viewDidLoad(_:)`.
var searchController: UISearchController!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
/*
Create the search controller, but we'll make sure that this
`SearchShowResultsInSourceViewController` performs the results updating.
*/
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
// Make sure the that the search bar is visible within the navigation bar.
searchController.searchBar.sizeToFit()
// Include the search controller's search bar within the table's header view.
tableView.tableHeaderView = searchController.searchBar
definesPresentationContext = true
}
}
|
gpl-2.0
|
a3236da2c1ad7419098535d4ba39e242
| 34.947368 | 174 | 0.697657 | 6.098214 | false | false | false | false |
tomasharkema/swift-bootcamp
|
TestApp/TestApp/ViewController.swift
|
1
|
1018
|
//
// ViewController.swift
// TestApp
//
// Created by Tomas Harkema on 09-11-15.
// Copyright © 2015 Tomas Harkema. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var button: UIButton!
var teller = 10
var timer: NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
label.text = String(NSDate().timeIntervalSince1970)
}
func count() {
teller--
if teller <= 0 {
timer?.invalidate()
timer = nil
}
label.text = String(teller)
}
func start() {
label.text = "10"
button.setTitle("Stop", forState: .Normal)
teller = 10
timer?.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "count", userInfo: nil, repeats: true)
}
@IBAction func labelPressed(sender: AnyObject) {
print("CLICK")
start()
}
}
|
cc0-1.0
|
45a0c0b1855b5abd77a65a4682c8b7e1
| 17.160714 | 116 | 0.653884 | 3.988235 | false | false | false | false |
maominghui/IQKeyboardManager
|
IQKeybordManagerSwift/IQKeyboardManager.swift
|
15
|
86574
|
//
// IQKeyboardManager.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-15 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
import UIKit
///---------------------
/// MARK: IQToolbar tags
///---------------------
/**
Default tag for toolbar with Done button -1002.
*/
let kIQDoneButtonToolbarTag : Int = -1002
/**
Default tag for toolbar with Previous/Next buttons -1005.
*/
let kIQPreviousNextButtonToolbarTag : Int = -1005
/**
Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
*/
class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate {
///---------------------------
/// MARK: UIKeyboard handling
///---------------------------
/**
Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method).
*/
var enable: Bool = false {
didSet {
//If not enable, enable it.
if enable == true && oldValue == false {
//If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard.
if _kbShowNotification != nil {
keyboardWillShow(_kbShowNotification)
}
_IQShowLog("enabled")
} else if enable == false && oldValue == true { //If not disable, desable it.
keyboardWillHide(nil)
_IQShowLog("disabled")
}
}
}
/**
To set keyboard distance from textField. can't be less than zero. Default is 10.0.
*/
var keyboardDistanceFromTextField: CGFloat {
set {
_privateKeyboardDistanceFromTextField = max(0, newValue)
_IQShowLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)")
}
get {
return _privateKeyboardDistanceFromTextField
}
}
/**
Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES.
*/
var preventShowingBottomBlankSpace = true
/**
Returns the default singleton instance.
*/
class func sharedManager() -> IQKeyboardManager {
struct Static {
//Singleton instance. Initializing keyboard manger.
static let kbManager = IQKeyboardManager()
}
/** @return Returns the default singleton instance. */
return Static.kbManager
}
///-------------------------
/// MARK: IQToolbar handling
///-------------------------
/**
Automatic add the IQToolbar functionality. Default is YES.
*/
var enableAutoToolbar: Bool = true {
didSet {
enableAutoToolbar ?addToolbarIfRequired():removeToolbarIfRequired()
var enableToolbar = enableAutoToolbar ? "Yes" : "NO"
_IQShowLog("enableAutoToolbar: \(enableToolbar)")
}
}
/**
AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews.
*/
var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.BySubviews
/**
If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO.
*/
var shouldToolbarUsesTextFieldTintColor = false
/**
If YES, then it add the textField's placeholder text on IQToolbar. Default is YES.
*/
var shouldShowTextFieldPlaceholder = true
/**
Placeholder Font. Default is nil.
*/
var placeholderFont: UIFont?
///--------------------------
/// MARK: UITextView handling
///--------------------------
/**
Adjust textView's frame when it is too big in height. Default is NO.
*/
var canAdjustTextView = false
/**
Adjust textView's contentInset to fix a bug. for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string Default is YES.
*/
var shouldFixTextViewClip = true
///---------------------------------------
/// MARK: UIKeyboard appearance overriding
///---------------------------------------
/**
Override the keyboardAppearance for all textField/textView. Default is NO.
*/
var overrideKeyboardAppearance = false
/**
If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property.
*/
var keyboardAppearance = UIKeyboardAppearance.Default
///-----------------------------------------------------------
/// MARK: UITextField/UITextView Next/Previous/Resign handling
///-----------------------------------------------------------
/**
Resigns Keyboard on touching outside of UITextField/View. Default is NO.
*/
var shouldResignOnTouchOutside: Bool = false {
didSet {
_tapGesture.enabled = shouldResignOnTouchOutside
let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO"
_IQShowLog("shouldResignOnTouchOutside: \(shouldResign)")
}
}
/**
Resigns currently first responder field.
*/
func resignFirstResponder() {
if let textFieldRetain = _textFieldView {
//Resigning first responder
let isResignFirstResponder = textFieldRetain.resignFirstResponder()
// If it refuses then becoming it as first responder again. (Bug ID: #96)
if isResignFirstResponder == false {
//If it refuses to resign then becoming it first responder again for getting notifications callback.
textFieldRetain.becomeFirstResponder()
_IQShowLog("Refuses to resign first responder: \(_textFieldView?._IQDescription())")
}
}
}
/**
Returns YES if can navigate to previous responder textField/textView, otherwise NO.
*/
var canGoPrevious: Bool {
get {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
if textFields.containsObject(textFieldRetain) == true {
//Getting index of current textField.
let index = textFields.indexOfObject(textFieldRetain)
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index > 0 {
return true
}
}
}
}
return false
}
}
/**
Returns YES if can navigate to next responder textField/textView, otherwise NO.
*/
var canGoNext: Bool {
get {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
if textFields.containsObject(textFieldRetain) == true {
//Getting index of current textField.
let index = textFields.indexOfObject(textFieldRetain)
//If it is not last textField. then it's next object canBecomeFirstResponder.
if index < textFields.count-1 {
return true
}
}
}
}
return false
}
}
/**
Navigate to previous responder textField/textView.
*/
func goPrevious() {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
if textFields.containsObject(textFieldRetain) == true {
//Getting index of current textField.
let index = textFields.indexOfObject(textFieldRetain)
//If it is not first textField. then it's previous object becomeFirstResponder.
if index > 0 {
let nextTextField = textFields[index-1] as! UIView
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
_IQShowLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
}
}
}
}
}
/**
Navigate to next responder textField/textView.
*/
func goNext() {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
if textFields.containsObject(textFieldRetain) == true {
//Getting index of current textField.
let index = textFields.indexOfObject(textFieldRetain)
//If it is not last textField. then it's next object becomeFirstResponder.
if index < textFields.count-1 {
let nextTextField = textFields[index+1] as! UIView
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
_IQShowLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
}
}
}
}
}
/** previousAction. */
func previousAction (segmentedControl : AnyObject?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.currentDevice().playInputClick()
}
if canGoPrevious == true {
goPrevious()
}
}
/** nextAction. */
func nextAction (segmentedControl : AnyObject?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.currentDevice().playInputClick()
}
if canGoNext {
goNext()
}
}
/** doneAction. Resigning current textField. */
func doneAction (barButton : IQBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.currentDevice().playInputClick()
}
//Resign textFieldView.
resignFirstResponder()
}
/** Resigning on tap gesture. (Enhancement ID: #14)*/
func tapRecognized(gesture: UITapGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.Ended {
//Resigning currently responder textField.
gesture.view?.endEditing(true)
}
}
/** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
/** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
// Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145)
return (touch.view is UIControl || touch.view is UINavigationBar) ? false : true
}
///----------------------------
/// MARK: UIScrollView handling
///----------------------------
/**
Restore scrollViewContentOffset when resigning from scrollView. Default is NO.
*/
var shouldRestoreScrollViewContentOffset = false
///-----------------------
/// MARK: UISound handling
///-----------------------
/**
If YES, then it plays inputClick sound on next/previous/done click.
*/
var shouldPlayInputClicks = false
///---------------------------
/// MARK: UIAnimation handling
///---------------------------
/**
If YES, then uses keyboard default animation curve style to move view, otherwise uses UIViewAnimationOptionCurveEaseInOut animation style. Default is YES.
@warning Sometimes strange animations may be produced if uses default curve style animation in iOS 7 and changing the textFields very frequently.
*/
var shouldAdoptDefaultKeyboardAnimation = true
/**
If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
*/
var layoutIfNeededOnUpdate = false
///------------------------------------
/// MARK: Class Level disabling methods
///------------------------------------
/**
Disable adjusting view in disabledClass
@param disabledClass Class in which library should not adjust view to show textField.
*/
func disableInViewControllerClass(disabledClass : AnyClass) {
_disabledClasses.addObject(NSStringFromClass(disabledClass))
}
/**
Re-enable adjusting textField in disabledClass
@param disabledClass Class in which library should re-enable adjust view to show textField.
*/
func removeDisableInViewControllerClass(disabledClass : AnyClass) {
_disabledClasses.removeObject(NSStringFromClass(disabledClass))
}
/**
Returns YES if ViewController class is disabled for library, otherwise returns NO.
@param disabledClass Class which is to check for it's disability.
*/
func isDisableInViewControllerClass(disabledClass : AnyClass) -> Bool {
return _disabledClasses.containsObject(NSStringFromClass(disabledClass))
}
/**
Disable automatic toolbar creation in in toolbarDisabledClass
@param toolbarDisabledClass Class in which library should not add toolbar over textField.
*/
func disableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) {
_disabledToolbarClasses.addObject(NSStringFromClass(toolbarDisabledClass))
}
/**
Re-enable automatic toolbar creation in in toolbarDisabledClass
@param toolbarDisabledClass Class in which library should re-enable automatic toolbar creation over textField.
*/
func removeDisableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) {
_disabledToolbarClasses.removeObject(NSStringFromClass(toolbarDisabledClass))
}
/**
Returns YES if toolbar is disabled in ViewController class, otherwise returns NO.
@param toolbarDisabledClass Class which is to check for toolbar disability.
*/
func isDisableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) -> Bool {
return _disabledToolbarClasses.containsObject(NSStringFromClass(toolbarDisabledClass))
}
/**
Consider provided customView class as superView of all inner textField for calculating next/previous button logic.
@param toolbarPreviousNextConsideredClass Custom UIView subclass Class in which library should consider all inner textField as siblings and add next/previous accordingly.
*/
func considerToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) {
_toolbarPreviousNextConsideredClass.addObject(NSStringFromClass(toolbarPreviousNextConsideredClass))
}
/**
Remove Consideration for provided customView class as superView of all inner textField for calculating next/previous button logic.
@param toolbarPreviousNextConsideredClass Custom UIView subclass Class in which library should remove consideration for all inner textField as superView.
*/
func removeConsiderToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) {
_toolbarPreviousNextConsideredClass.removeObject(NSStringFromClass(toolbarPreviousNextConsideredClass))
}
/**
Returns YES if inner hierarchy is considered for previous/next in class, otherwise returns NO.
@param toolbarPreviousNextConsideredClass Class which is to check for previous next consideration
*/
func isConsiderToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) -> Bool {
return _toolbarPreviousNextConsideredClass.containsObject(NSStringFromClass(toolbarPreviousNextConsideredClass))
}
/**************************************************************************************/
///------------------------
/// MARK: Private variables
///------------------------
/*******************************************/
/** To save UITextField/UITextView object voa textField/textView notifications. */
private weak var _textFieldView: UIView?
/** used with canAdjustTextView boolean. */
private var _textFieldViewIntialFrame = CGRectZero
/** To save rootViewController.view.frame. */
private var _topViewBeginRect = CGRectZero
/** To save rootViewController */
private weak var _rootViewController: UIViewController?
/** used with canAdjustTextView to detect a textFieldView frame is changes or not. (Bug ID: #92)*/
private var _isTextFieldViewFrameChanged = false
/*******************************************/
/** Variable to save lastScrollView that was scrolled. */
private weak var _lastScrollView: UIScrollView?
/** LastScrollView's initial contentOffset. */
private var _startingContentOffset = CGPointZero
/** LastScrollView's initial scrollIndicatorInsets. */
private var _startingScrollIndicatorInsets = UIEdgeInsetsZero
/** LastScrollView's initial contentInsets. */
private var _startingContentInsets = UIEdgeInsetsZero
/*******************************************/
/** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
private var _kbShowNotification: NSNotification?
/** To save keyboard size. */
private var _kbSize = CGSizeZero
/** To save keyboard animation duration. */
private var _animationDuration = 0.25
/** To mimic the keyboard animation */
private var _animationCurve = UIViewAnimationOptions.CurveEaseOut
/** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */
private var _isKeyboardShowing = false
/*******************************************/
/** TapGesture to resign keyboard on view's touch. */
private var _tapGesture: UITapGestureRecognizer!
/*******************************************/
/** Default toolbar tintColor to be used within the project. Default is black. */
private var _defaultToolbarTintColor = UIColor.blackColor()
/*******************************************/
/** Set of restricted classes for library */
private var _disabledClasses = NSMutableSet()
/** Set of restricted classes for adding toolbar */
private var _disabledToolbarClasses = NSMutableSet()
/** Set of permitted classes to add all inner textField as siblings */
private var _toolbarPreviousNextConsideredClass = NSMutableSet()
/*******************************************/
/** To use with keyboardDistanceFromTextField. */
private var _privateKeyboardDistanceFromTextField: CGFloat = 10.0
/**************************************************************************************/
///--------------------------------------
/// MARK: Initialization/Deinitialization
///--------------------------------------
/* Singleton Object Initialization. */
override init() {
super.init()
// Registering for keyboard notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHide:", name: UIKeyboardDidHideNotification, object: nil)
// Registering for textField notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextFieldTextDidBeginEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextFieldTextDidEndEditingNotification, object: nil)
// Registering for textView notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextViewTextDidBeginEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextViewTextDidEndEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidChange:", name: UITextViewTextDidChangeNotification, object: nil)
// Registering for orientation changes notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeStatusBarOrientation:", name: UIApplicationWillChangeStatusBarOrientationNotification, object: nil)
//Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
_tapGesture = UITapGestureRecognizer(target: self, action: "tapRecognized:")
_tapGesture.delegate = self
_tapGesture.enabled = shouldResignOnTouchOutside
_disabledClasses.addObject(NSStringFromClass(UITableViewController))
_toolbarPreviousNextConsideredClass.addObject(NSStringFromClass(UITableView))
_toolbarPreviousNextConsideredClass.addObject(NSStringFromClass(UICollectionView))
}
/** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */
// override class func load() {
// super.load()
//
// //Enabling IQKeyboardManager.
// IQKeyboardManager.sharedManager().enable = true
// }
deinit {
// Disable the keyboard manager.
enable = false
//Removing notification observers on dealloc.
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/** Getting keyWindow. */
private func keyWindow() -> UIWindow? {
if _textFieldView?.window != nil {
return _textFieldView?.window
} else {
struct Static {
/** @abstract Save keyWindow object for reuse.
@discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */
static var keyWindow : UIWindow?
}
/* (Bug ID: #23, #25, #73) */
let originalKeyWindow = UIApplication.sharedApplication().keyWindow
//If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
if originalKeyWindow != nil && (Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) {
Static.keyWindow = originalKeyWindow
}
//Return KeyWindow
return Static.keyWindow
}
}
///-----------------------
/// MARK: Helper Functions
///-----------------------
/* Helper function to manipulate RootViewController's frame with animation. */
private func setRootViewFrame(var frame: CGRect) {
// Getting topMost ViewController.
var controller = _textFieldView?.topMostController()
if controller == nil {
controller = keyWindow()?.topMostController()
}
if let unwrappedController = controller {
//frame size needs to be adjusted on iOS8 due to orientation structure changes.
if IQ_IS_IOS8_OR_GREATER == true {
frame.size = unwrappedController.view.frame.size
}
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
// Setting it's new frame
unwrappedController.view.frame = frame
self._IQShowLog("Set \(controller?._IQDescription()) frame to : \(frame)")
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
unwrappedController.view.setNeedsLayout()
unwrappedController.view.layoutIfNeeded()
}
}) { (animated:Bool) -> Void in}
} else { // If can't get rootViewController then printing warning to user.
_IQShowLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager")
}
}
/* Adjusting RootViewController's frame according to device orientation. */
private func adjustFrame() {
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
if _textFieldView == nil {
return
}
_IQShowLog("****** \(__FUNCTION__) %@ started ******")
// Boolean to know keyboard is showing/hiding
_isKeyboardShowing = true
// Getting KeyWindow object.
let optionalWindow = keyWindow()
// Getting RootViewController. (Bug ID: #1, #4)
var optionalRootController = _textFieldView?.topMostController()
if optionalRootController == nil {
optionalRootController = keyWindow()?.topMostController()
}
// Converting Rectangle according to window bounds.
let optionalTextFieldViewRect = _textFieldView?.superview?.convertRect(_textFieldView!.frame, toView: optionalWindow)
if optionalRootController == nil || optionalWindow == nil || optionalTextFieldViewRect == nil {
return
}
let rootController = optionalRootController!
let window = optionalWindow!
let textFieldView = _textFieldView!
let textFieldViewRect = optionalTextFieldViewRect!
//If it's iOS8 then we should do calculations according to portrait orientations. // (Bug ID: #64, #66)
let interfaceOrientation = (IQ_IS_IOS8_OR_GREATER) ? UIInterfaceOrientation.Portrait : rootController.interfaceOrientation
// Getting RootViewRect.
var rootViewRect = rootController.view.frame
//Getting statusBarFrame
var topLayoutGuide : CGFloat = 0
let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight:
topLayoutGuide = CGRectGetWidth(statusBarFrame)
case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown:
topLayoutGuide = CGRectGetHeight(statusBarFrame)
default: break
}
var move : CGFloat = 0.0
// Move positive = textField is hidden.
// Move negative = textField is showing.
// Calculating move position. Common for both normal and special cases.
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft:
move = min(CGRectGetMinX(textFieldViewRect)-(topLayoutGuide+5), CGRectGetMaxX(textFieldViewRect)-(CGRectGetWidth(window.frame)-_kbSize.width))
case UIInterfaceOrientation.LandscapeRight:
move = min(CGRectGetWidth(window.frame)-CGRectGetMaxX(textFieldViewRect)-(topLayoutGuide+5), _kbSize.width-CGRectGetMinX(textFieldViewRect))
case UIInterfaceOrientation.Portrait:
move = min(CGRectGetMinY(textFieldViewRect)-(topLayoutGuide+5), CGRectGetMaxY(textFieldViewRect)-(CGRectGetHeight(window.frame)-_kbSize.height))
case UIInterfaceOrientation.PortraitUpsideDown:
move = min(CGRectGetHeight(window.frame)-CGRectGetMaxY(textFieldViewRect)-(topLayoutGuide+5), _kbSize.height-CGRectGetMinY(textFieldViewRect))
default: break
}
_IQShowLog("Need to move: \(move)")
// Getting it's superScrollView. // (Enhancement ID: #21, #24)
let superScrollView : UIScrollView? = textFieldView.superviewOfClassType(UIScrollView) as? UIScrollView
//If there was a lastScrollView. // (Bug ID: #34)
if let lastScrollView = _lastScrollView {
//If we can't find current superScrollView, then setting lastScrollView to it's original form.
if superScrollView == nil {
_IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_startingContentInsets = UIEdgeInsetsZero
_startingScrollIndicatorInsets = UIEdgeInsetsZero
_startingContentOffset = CGPointZero
_lastScrollView = nil
} else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
_IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_lastScrollView = superScrollView
_startingContentInsets = superScrollView!.contentInset
_startingScrollIndicatorInsets = superScrollView!.scrollIndicatorInsets
_startingContentOffset = superScrollView!.contentOffset
_IQShowLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
//Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead
} else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
_lastScrollView = unwrappedSuperScrollView
_startingContentInsets = unwrappedSuperScrollView.contentInset
_startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
_startingContentOffset = unwrappedSuperScrollView.contentOffset
_IQShowLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
// Special case for ScrollView.
// If we found lastScrollView then setting it's contentOffset to show textField.
if let lastScrollView = _lastScrollView {
//Saving
var lastView = textFieldView
var superScrollView = _lastScrollView
while let scrollView = superScrollView {
//Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
if move > 0 ? move > -scrollView.contentOffset.y - scrollView.contentInset.top : scrollView.contentOffset.y>0 {
//Getting lastViewRect.
if let lastViewRect = lastView.superview?.convertRect(lastView.frame, toView: scrollView) {
//Calculating the expected Y offset from move and scrollView's contentOffset.
var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move)
//Rearranging the expected Y offset according to the view.
shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y /*-5*/) //-5 is for good UI.//Commenting -5 (Bug ID: #69)
//[superScrollView superviewOfClassType:[UIScrollView class]] == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//shouldOffsetY > 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92)
if textFieldView is UITextView == true && scrollView.superviewOfClassType(UIScrollView) == nil && shouldOffsetY > 0 {
var maintainTopLayout : CGFloat = 0
if let navigationBarFrame = textFieldView.viewController()?.navigationController?.navigationBar.frame {
maintainTopLayout = CGRectGetMaxY(navigationBarFrame)
}
maintainTopLayout += 10.0 //For good UI
// Converting Rectangle according to window bounds.
if let currentTextFieldViewRect = textFieldView.superview?.convertRect(textFieldView.frame, toView: window) {
var expectedFixDistance = shouldOffsetY
//Calculating expected fix distance which needs to be managed from navigation bar
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft:
expectedFixDistance = CGRectGetMinX(currentTextFieldViewRect) - maintainTopLayout
case UIInterfaceOrientation.LandscapeRight:
expectedFixDistance = (CGRectGetWidth(window.frame)-CGRectGetMaxX(currentTextFieldViewRect)) - maintainTopLayout
case UIInterfaceOrientation.Portrait:
expectedFixDistance = CGRectGetMinY(currentTextFieldViewRect) - maintainTopLayout
case UIInterfaceOrientation.PortraitUpsideDown:
expectedFixDistance = (CGRectGetHeight(window.frame)-CGRectGetMaxY(currentTextFieldViewRect)) - maintainTopLayout
default: break
}
//Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance)
shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance)
//Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic.
move = 0
}
else {
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
}
else
{
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
self._IQShowLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset")
self._IQShowLog("Remaining Move: \(move)")
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, shouldOffsetY)
}) { (animated:Bool) -> Void in }
}
// Getting next lastView & superScrollView.
lastView = scrollView
superScrollView = lastView.superviewOfClassType(UIScrollView) as? UIScrollView
} else {
break
}
}
//Updating contentInset
if let lastScrollViewRect = lastScrollView.superview?.convertRect(lastScrollView.frame, toView: window) {
var bottom : CGFloat = 0.0
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft:
bottom = _kbSize.width-(CGRectGetWidth(window.frame)-CGRectGetMaxX(lastScrollViewRect))
case UIInterfaceOrientation.LandscapeRight:
bottom = _kbSize.width-CGRectGetMinX(lastScrollViewRect)
case UIInterfaceOrientation.Portrait:
bottom = _kbSize.height-(CGRectGetHeight(window.frame)-CGRectGetMaxY(lastScrollViewRect))
case UIInterfaceOrientation.PortraitUpsideDown:
bottom = _kbSize.height-CGRectGetMinY(lastScrollViewRect)
default: break
}
// Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
var movedInsets = lastScrollView.contentInset
movedInsets.bottom = max(_startingContentInsets.bottom, bottom)
_IQShowLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)")
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
lastScrollView.contentInset = movedInsets
var newInset = lastScrollView.scrollIndicatorInsets
newInset.bottom = movedInsets.bottom - 10
lastScrollView.scrollIndicatorInsets = newInset
}) { (animated:Bool) -> Void in }
//Maintaining contentSize
if lastScrollView.contentSize.height < lastScrollView.frame.size.height {
var contentSize = lastScrollView.contentSize
contentSize.height = lastScrollView.frame.size.height
lastScrollView.contentSize = contentSize
}
_IQShowLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)")
}
}
//Going ahead. No else if.
//Special case for UITextView(Readjusting the move variable when textView hight is too big to fit on screen)
//_canAdjustTextView If we have permission to adjust the textView, then let's do it on behalf of user (Enhancement ID: #15)
//_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView.
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//_isTextFieldViewFrameChanged If frame is not change by library in past (Bug ID: #92)
if canAdjustTextView == true && _lastScrollView == nil && textFieldView is UITextView == true && _isTextFieldViewFrameChanged == false {
var textViewHeight = CGRectGetHeight(textFieldView.frame)
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight:
textViewHeight = min(textViewHeight, (CGRectGetWidth(window.frame)-_kbSize.width-(topLayoutGuide+5)))
case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown:
textViewHeight = min(textViewHeight, (CGRectGetHeight(window.frame)-_kbSize.height-(topLayoutGuide+5)))
default: break
}
UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve|UIViewAnimationOptions.BeginFromCurrentState), animations: { () -> Void in
self._IQShowLog("\(textFieldView._IQDescription()) Old Frame : \(textFieldView.frame)")
var textFieldViewRect = textFieldView.frame
textFieldViewRect.size.height = textViewHeight
textFieldView.frame = textFieldViewRect
self._isTextFieldViewFrameChanged = true
self._IQShowLog("\(textFieldView._IQDescription()) New Frame : \(textFieldView.frame)")
}, completion: { (finished) -> Void in })
}
// Special case for iPad modalPresentationStyle.
if rootController.modalPresentationStyle == UIModalPresentationStyle.FormSheet || rootController.modalPresentationStyle == UIModalPresentationStyle.PageSheet {
_IQShowLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)")
// Positive or zero.
if move >= 0 {
// We should only manipulate y.
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
var minimumY: CGFloat = 0
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight:
minimumY = CGRectGetWidth(window.frame)-rootViewRect.size.height-topLayoutGuide-(_kbSize.width-keyboardDistanceFromTextField)
case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown:
minimumY = (CGRectGetHeight(window.frame)-rootViewRect.size.height-topLayoutGuide)/2-(_kbSize.height-keyboardDistanceFromTextField)
default: break
}
rootViewRect.origin.y = max(CGRectGetMinY(rootViewRect), minimumY)
}
_IQShowLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
} else { // Negative
// Calculating disturbed distance. Pull Request #3
let disturbDistance = CGRectGetMinY(rootViewRect)-CGRectGetMinY(_topViewBeginRect)
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
// We should only manipulate y.
rootViewRect.origin.y -= max(move, disturbDistance)
_IQShowLog("Moving Downward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
}
}
} else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case)
// Positive or zero.
if move >= 0 {
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft: rootViewRect.origin.x -= move
case UIInterfaceOrientation.LandscapeRight: rootViewRect.origin.x += move
case UIInterfaceOrientation.Portrait: rootViewRect.origin.y -= move
case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.origin.y += move
default: break
}
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft:
rootViewRect.origin.x = max(rootViewRect.origin.x, min(0, -_kbSize.width+keyboardDistanceFromTextField))
case UIInterfaceOrientation.LandscapeRight:
rootViewRect.origin.x = min(rootViewRect.origin.x, +_kbSize.width-keyboardDistanceFromTextField)
case UIInterfaceOrientation.Portrait:
rootViewRect.origin.y = max(rootViewRect.origin.y, min(0, -_kbSize.height+keyboardDistanceFromTextField))
case UIInterfaceOrientation.PortraitUpsideDown:
rootViewRect.origin.y = min(rootViewRect.origin.y, +_kbSize.height-keyboardDistanceFromTextField)
default: break
}
}
_IQShowLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
} else { // Negative
var disturbDistance : CGFloat = 0
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft:
disturbDistance = CGRectGetMinX(rootViewRect)-CGRectGetMinX(_topViewBeginRect)
case UIInterfaceOrientation.LandscapeRight:
disturbDistance = CGRectGetMinX(_topViewBeginRect)-CGRectGetMinX(rootViewRect)
case UIInterfaceOrientation.Portrait:
disturbDistance = CGRectGetMinY(rootViewRect)-CGRectGetMinY(_topViewBeginRect)
case UIInterfaceOrientation.PortraitUpsideDown:
disturbDistance = CGRectGetMinY(_topViewBeginRect)-CGRectGetMinY(rootViewRect)
default: break
}
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft: rootViewRect.origin.x -= max(move, disturbDistance)
case UIInterfaceOrientation.LandscapeRight: rootViewRect.origin.x += max(move, disturbDistance)
case UIInterfaceOrientation.Portrait: rootViewRect.origin.y -= max(move, disturbDistance)
case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.origin.y += max(move, disturbDistance)
default: break
}
_IQShowLog("Moving Downward")
// Setting adjusted rootViewRect
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
}
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
///-------------------------------
/// MARK: UIKeyboard Notifications
///-------------------------------
/* UIKeyboardWillShowNotification. */
func keyboardWillShow(notification : NSNotification?) -> Void {
_kbShowNotification = notification
if enable == false {
return
}
_IQShowLog("****** \(__FUNCTION__) started ******")
//Due to orientation callback we need to resave it's original frame. // (Bug ID: #46)
//Added _isTextFieldViewFrameChanged check. Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed. (Bug ID: #92)
if _isTextFieldViewFrameChanged == false {
if let textFieldView = _textFieldView {
_textFieldViewIntialFrame = textFieldView.frame
_IQShowLog("Saving \(textFieldView._IQDescription()) Initial frame : \(_textFieldViewIntialFrame)")
}
}
// (Bug ID: #5)
if CGRectEqualToRect(_topViewBeginRect, CGRectZero) == true {
// keyboard is not showing(At the beginning only). We should save rootViewRect.
var rootController = _textFieldView?.topMostController()
if rootController == nil {
rootController = keyWindow()?.topMostController()
}
if let unwrappedRootController = rootController {
_topViewBeginRect = unwrappedRootController.view.frame
_IQShowLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRectZero
}
}
let oldKBSize = _kbSize
if let info = notification?.userInfo {
if shouldAdoptDefaultKeyboardAnimation {
// Getting keyboard animation.
if let curve = info[UIKeyboardAnimationCurveUserInfoKey]?.unsignedLongValue {
_animationCurve = UIViewAnimationOptions(rawValue: curve)
}
} else {
_animationCurve = UIViewAnimationOptions.CurveEaseOut
}
// Getting keyboard animation duration
if let duration = info[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue {
//Saving animation duration
if duration != 0.0 {
_animationDuration = duration
}
}
// Getting UIKeyboardSize.
if let kbFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue() {
_kbSize = kbFrame.size
_IQShowLog("UIKeyboard Size : \(_kbSize)")
}
}
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostController()
}
if let topController = topMostController {
//If it's iOS8 then we should do calculations according to portrait orientations. // (Bug ID: #64, #66)
let interfaceOrientation = (IQ_IS_IOS8_OR_GREATER) ? UIInterfaceOrientation.Portrait : topController.interfaceOrientation
let _keyboardDistanceFromTextField = keyboardDistanceFromTextField
// let _keyboardDistanceFromTextField = (_textFieldView.keyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance)?_keyboardDistanceFromTextField:_textFieldView.keyboardDistanceFromTextField
// Adding Keyboard distance from textField.
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight:
_kbSize.width += _keyboardDistanceFromTextField
case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown:
_kbSize.height += _keyboardDistanceFromTextField
default: break
}
}
//If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
if CGSizeEqualToSize(_kbSize, oldKBSize) == false {
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false {
//Getting textField viewController
if let textFieldViewController = _textFieldView?.viewController() {
var shouldIgnore = false
for disabledClassString in _disabledClasses {
//If viewController is kind of disabled viewController class, then ignoring to adjust view.
if textFieldViewController.isKindOfClass((NSClassFromString(disabledClassString as! String))) {
shouldIgnore = true
break
}
}
//If shouldn't ignore.
if shouldIgnore == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
func keyboardWillHide(notification : NSNotification?) -> Void {
//If it's not a fake notification generated by [self setEnable:NO].
if notification != nil {
_kbShowNotification = nil
}
//If not enabled then do nothing.
if enable == false {
return
}
_IQShowLog("****** \(__FUNCTION__) started ******")
//Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56)
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
// if (_textFieldView == nil) return
// Boolean to know keyboard is showing/hiding
_isKeyboardShowing = false
let info : [NSObject : AnyObject]? = notification?.userInfo
// Getting keyboard animation duration
if let duration = info?[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue {
if duration != 0 {
// Setitng keyboard animation duration
_animationDuration = duration
}
}
//Restoring the contentOffset of the lastScrollView
if let lastScrollView = _lastScrollView {
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
if self.shouldRestoreScrollViewContentOffset == true {
lastScrollView.contentOffset = self._startingContentOffset
}
self._IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)")
// TODO: restore scrollView state
// This is temporary solution. Have to implement the save and restore scrollView state
var superScrollView = self._lastScrollView?.superviewOfClassType(UIScrollView) as? UIScrollView
while let scrollView = superScrollView {
let contentSize = CGSizeMake(max(scrollView.contentSize.width, CGRectGetWidth(scrollView.frame)), max(scrollView.contentSize.height, CGRectGetHeight(scrollView.frame)))
let minimumY = contentSize.height - CGRectGetHeight(scrollView.frame)
if minimumY < scrollView.contentOffset.y {
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, minimumY)
self._IQShowLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)")
}
superScrollView = superScrollView?.superviewOfClassType(UIScrollView) as? UIScrollView
}
}) { (finished) -> Void in }
}
// Setting rootViewController frame to it's original position. // (Bug ID: #18)
if CGRectEqualToRect(_topViewBeginRect, CGRectZero) == false {
if let rootViewController = _rootViewController {
//frame size needs to be adjusted on iOS8 due to orientation API changes.
if IQ_IS_IOS8_OR_GREATER == true {
_topViewBeginRect.size = rootViewController.view.frame.size
}
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
self._IQShowLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)")
// Setting it's new frame
rootViewController.view.frame = self._topViewBeginRect
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
}) { (finished) -> Void in }
_rootViewController = nil
}
}
//Reset all values
_lastScrollView = nil
_kbSize = CGSizeZero
_startingContentInsets = UIEdgeInsetsZero
_startingScrollIndicatorInsets = UIEdgeInsetsZero
_startingContentOffset = CGPointZero
// topViewBeginRect = CGRectZero //Commented due to #82
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
func keyboardDidHide(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
_topViewBeginRect = CGRectZero
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
///-------------------------------------------
/// MARK: UITextField/UITextView Notifications
///-------------------------------------------
/** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
func textFieldViewDidBeginEditing(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
// Getting object
_textFieldView = notification.object as? UIView
if overrideKeyboardAppearance == true {
if let textFieldView = _textFieldView as? UITextField {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
} else if let textFieldView = _textFieldView as? UITextView {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
}
}
// Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed.
//Added _isTextFieldViewFrameChanged check. (Bug ID: #92)
if _isTextFieldViewFrameChanged == false {
if let textFieldView = _textFieldView {
_textFieldViewIntialFrame = textFieldView.frame
_IQShowLog("Saving \(textFieldView._IQDescription()) Initial frame : \(_textFieldViewIntialFrame)")
}
}
//If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
if enableAutoToolbar == true {
_IQShowLog("adding UIToolbars if required")
//UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
if _textFieldView is UITextView == true && _textFieldView?.inputAccessoryView == nil {
UIView.animateWithDuration(0.00001, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
self.addToolbarIfRequired()
}, completion: { (finished) -> Void in
//On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
self._textFieldView?.reloadInputViews()
})
} else {
//Adding toolbar
addToolbarIfRequired()
}
}
if enable == false {
_IQShowLog("****** \(__FUNCTION__) ended ******")
return
}
_textFieldView?.window?.addGestureRecognizer(_tapGesture) // (Enhancement ID: #14)
if _isKeyboardShowing == false { // (Bug ID: #5)
// keyboard is not showing(At the beginning only). We should save rootViewRect.
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostController()
}
if let rootViewController = _rootViewController {
_topViewBeginRect = rootViewController.view.frame
_IQShowLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)")
}
}
//If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
//See notes:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false {
//Getting textField viewController
if let textFieldViewController = _textFieldView?.viewController() {
var shouldIgnore = false
for disabledClassString in _disabledClasses {
//If viewController is kind of disabled viewController class, then ignoring to adjust view.
if textFieldViewController.isKindOfClass((NSClassFromString(disabledClassString as! String))) {
shouldIgnore = true
break
}
}
//If shouldn't ignore.
if shouldIgnore == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
func textFieldViewDidEndEditing(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
//Removing gesture recognizer (Enhancement ID: #14)
_textFieldView?.window?.removeGestureRecognizer(_tapGesture)
// We check if there's a change in original frame or not.
if _isTextFieldViewFrameChanged == true {
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
self._isTextFieldViewFrameChanged = false
self._IQShowLog("Restoring \(self._textFieldView?._IQDescription()) frame to : \(self._textFieldViewIntialFrame)")
self._textFieldView?.frame = self._textFieldViewIntialFrame
}, completion: { (finished) -> Void in })
}
//Setting object to nil
_textFieldView = nil
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/** UITextViewTextDidChangeNotificationBug, fix for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string */
func textFieldViewDidChange(notification:NSNotification) { // (Bug ID: #18)
if shouldFixTextViewClip {
let textView = notification.object as! UITextView
let line = textView .caretRectForPosition(textView.selectedTextRange?.start)
let overflow = CGRectGetMaxY(line) - (textView.contentOffset.y + CGRectGetHeight(textView.bounds) - textView.contentInset.bottom - textView.contentInset.top)
//Added overflow conditions (Bug ID: 95)
if overflow > 0.0 && overflow < CGFloat(FLT_MAX) {
// We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it)
// Scroll caret to visible area
var offset = textView.contentOffset
offset.y += overflow + 7 // leave 7 pixels margin
// Cannot animate with setContentOffset:animated: or caret will not appear
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
textView.contentOffset = offset
}, completion: { (finished) -> Void in })
}
}
}
///------------------------------------------
/// MARK: Interface Orientation Notifications
///------------------------------------------
/** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
func willChangeStatusBarOrientation(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
//If textFieldViewInitialRect is saved then restore it.(UITextView case @canAdjustTextView)
if _isTextFieldViewFrameChanged == true {
if let textFieldView = _textFieldView {
//Due to orientation callback we need to set it's original position.
UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve|UIViewAnimationOptions.BeginFromCurrentState), animations: { () -> Void in
self._isTextFieldViewFrameChanged = false
self._IQShowLog("Restoring \(textFieldView._IQDescription()) frame to : \(self._textFieldViewIntialFrame)")
//Setting textField to it's initial frame
textFieldView.frame = self._textFieldViewIntialFrame
}, completion: { (finished) -> Void in })
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
///------------------
/// MARK: AutoToolbar
///------------------
/** Get all UITextField/UITextView siblings of textFieldView. */
func responderViews()-> NSArray? {
var superConsideredView : UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView.
for disabledClassString in _toolbarPreviousNextConsideredClass {
if _textFieldView?.superviewOfClassType(NSClassFromString(disabledClassString as! String)) != nil {
break
}
}
//If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22)
if superConsideredView != nil {
return superConsideredView?.deepResponderViews()
} else { //Otherwise fetching all the siblings
if let textFields = _textFieldView?.responderSiblings() {
//Sorting textFields according to behaviour
switch toolbarManageBehaviour {
//If autoToolbar behaviour is bySubviews, then returning it.
case IQAutoToolbarManageBehaviour.BySubviews: return textFields
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.ByTag: return textFields.sortedArrayByTag()
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.ByPosition: return textFields.sortedArrayByPosition()
}
} else {
return nil
}
}
}
/** Add toolbar if it is required to add on textFields and it's siblings. */
private func addToolbarIfRequired() {
if let textFieldViewController = _textFieldView?.viewController() {
for disabledClassString in _disabledToolbarClasses {
if textFieldViewController.isKindOfClass((NSClassFromString(disabledClassString as! String))) {
removeToolbarIfRequired()
return
}
}
}
// Getting all the sibling textFields.
if let siblings = responderViews() {
// If only one object is found, then adding only Done button.
if siblings.count == 1 {
let textField = siblings.firstObject as! UIView
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
if textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == kIQPreviousNextButtonToolbarTag {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addDoneOnKeyboardWithTarget(self, action: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
textField.inputAccessoryView?.tag = kIQDoneButtonToolbarTag // (Bug ID: #78)
}
if textField.inputAccessoryView?.isKindOfClass(IQToolbar) == true && textField.inputAccessoryView?.tag == kIQDoneButtonToolbarTag {
let toolbar = textField.inputAccessoryView as! IQToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
toolbar.tintColor = UIColor.whiteColor()
default:
toolbar.barStyle = UIBarStyle.Default
toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textField.tintColor : _defaultToolbarTintColor
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
toolbar.tintColor = UIColor.whiteColor()
default:
toolbar.barStyle = UIBarStyle.Default
toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textView.tintColor : _defaultToolbarTintColor
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true && placeholderFont != nil {
let toolbar = textField.inputAccessoryView as! IQToolbar
//Updating placeholder font to toolbar. //(Bug ID: #148)
if let _textField = textField as? UITextField {
if toolbar.title != _textField.placeholder {
toolbar.title = _textField.placeholder
}
} else if let _textView = textField as? IQTextView {
if toolbar.title != _textView.placeholder {
toolbar.title = _textView.placeholder
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleFont = placeholderFont
}
}
}
} else if siblings.count != 0 {
// If more than 1 textField is found. then adding previous/next/done buttons on it.
for textField in siblings as! [UIView] {
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Done toolbar).
if textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == kIQDoneButtonToolbarTag {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: "previousAction:", nextAction: "nextAction:", doneAction: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
textField.inputAccessoryView?.tag = kIQPreviousNextButtonToolbarTag // (Bug ID: #78)
}
if textField.inputAccessoryView?.isKindOfClass(IQToolbar) == true && textField.inputAccessoryView?.tag == kIQPreviousNextButtonToolbarTag {
let toolbar = textField.inputAccessoryView as! IQToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
toolbar.tintColor = UIColor.whiteColor()
default:
toolbar.barStyle = UIBarStyle.Default
toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textField.tintColor : _defaultToolbarTintColor
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
toolbar.tintColor = UIColor.whiteColor()
default:
toolbar.barStyle = UIBarStyle.Default
toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textView.tintColor : _defaultToolbarTintColor
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true && placeholderFont != nil {
let toolbar = textField.inputAccessoryView as! IQToolbar
//Updating placeholder font to toolbar. //(Bug ID: #148)
if let _textField = textField as? UITextField {
if toolbar.title != _textField.placeholder {
toolbar.title = _textField.placeholder
}
} else if let _textView = textField as? IQTextView {
if toolbar.title != _textView.placeholder {
toolbar.title = _textView.placeholder
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleFont = placeholderFont
}
}
}
//If the toolbar is added by IQKeyboardManager then automatically enabling/disabling the previous/next button.
if textField.inputAccessoryView?.tag == kIQPreviousNextButtonToolbarTag {
//In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56)
// If firstTextField, then previous should not be enabled.
if siblings[0] as! UIView == textField {
textField.setEnablePrevious(false, isNextEnabled: true)
} else if siblings.lastObject as! UIView == textField { // If lastTextField then next should not be enaled.
textField.setEnablePrevious(true, isNextEnabled: false)
} else {
textField.setEnablePrevious(true, isNextEnabled: true)
}
}
}
}
}
}
/** Remove any toolbar if it is IQToolbar. */
private func removeToolbarIfRequired() { // (Bug ID: #18)
// Getting all the sibling textFields.
if let siblings = responderViews() {
for view in siblings as! [UIView] {
let toolbar = view.inputAccessoryView
if toolbar is IQToolbar == true && (toolbar?.tag == kIQDoneButtonToolbarTag || toolbar?.tag == kIQPreviousNextButtonToolbarTag) {
if view is UITextField == true {
let textField = view as! UITextField
textField.inputAccessoryView = nil
} else if view is UITextView == true {
let textView = view as! UITextView
textView.inputAccessoryView = nil
}
}
}
}
}
private func _IQShowLog(logString: String) {
#if IQKEYBOARDMANAGER_DEBUG
println("IQKeyboardManager: " + logString)
#endif
}
}
|
mit
|
8056d969139a046cad4c89e114fe1325
| 46.699174 | 370 | 0.576975 | 6.982337 | false | false | false | false |
Guzlan/Paths
|
Paths/DataSource.swift
|
1
|
2680
|
//
// DataSource.swift
// Paths
//
// Created by Amr Guzlan on 2016-07-03.
// Copyright © 2016 Amro Gazlan. All rights reserved.
//
import Foundation
import AppKit
import CoreServices
class DataSource: NSObject, NSOutlineViewDataSource{
let rootFile: FileSystemItem? // the root of the file system
override init(){
self.pb = NSPasteboard(name: NSDragPboard) // paste board to copy the file path/url for copying file item when dragging and dropping
self.rootFile = FileSystemItem.getRootItem() // getting the root file item
self.rootFile?.setChildren() // setting root children
super.init()
}
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
if item != nil {
let filetItem = item as? FileSystemItem
return filetItem!.numberOFChildren()
}else {
return 1
}
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
let filetItem = item as? FileSystemItem
filetItem?.setChildren()
let fileItemTruth = (filetItem!.numberOFChildren() != -1) ? true : false
return fileItemTruth
}
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
if item != nil{
let filetItem = item as? FileSystemItem
return filetItem!.getChildAtIndex(index)!
}else {
return self.rootFile!
}
}
func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject? {
if item != nil {
let filetItem = item as? FileSystemItem
return (filetItem?.getRelativePath() == "/") ? "root" : filetItem?.getRelativePath()
}else {
return "not set"
}
}
let pb: NSPasteboard?
func outlineView(outlineView: NSOutlineView, writeItems items: [AnyObject], toPasteboard pasteboard: NSPasteboard) -> Bool {
var array = [String]()
self.pb?.declareTypes([NSFilesPromisePboardType], owner: self)
// iterating through selected items on the table, adding their url's to
// array for them to be copied if dragged and dropeed
for item in items {
if let fileItem = item as? FileSystemItem {
let fileURL = fileItem.getFullPath()!
array.append(fileURL)
}
else {
return false
}
}
self.pb?.setPropertyList(array, forType: NSFilenamesPboardType)
return true
}
}
|
mit
|
b58195789dd55623eb9bdf5c05e26467
| 34.733333 | 144 | 0.623367 | 4.716549 | false | false | false | false |
michael-lehew/swift-corelibs-foundation
|
Foundation/NSAttributedString.swift
|
1
|
9918
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
open class NSAttributedString: NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
private let _cfinfo = _CFInfo(typeID: CFAttributedStringGetTypeID())
fileprivate var _string: NSString
fileprivate var _attributeArray: CFRunArrayRef
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
open func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
static public var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
NSUnimplemented()
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
NSUnimplemented()
}
open var string: String {
return _string._swiftObject
}
open func attributes(at location: Int, effectiveRange range: NSRangePointer) -> [String : Any] {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: false,
longestEffectiveRangeSearchRange: nil)
return _attributes(at: location, rangeInfo: rangeInfo)
}
open var length: Int {
return CFAttributedStringGetLength(_cfObject)
}
open func attribute(_ attrName: String, at location: Int, effectiveRange range: NSRangePointer?) -> Any? {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: false,
longestEffectiveRangeSearchRange: nil)
return _attribute(attrName, atIndex: location, rangeInfo: rangeInfo)
}
open func attributedSubstring(from range: NSRange) -> NSAttributedString { NSUnimplemented() }
open func attributes(at location: Int, longestEffectiveRange range: NSRangePointer?, in rangeLimit: NSRange) -> [String : Any] {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: true,
longestEffectiveRangeSearchRange: rangeLimit)
return _attributes(at: location, rangeInfo: rangeInfo)
}
open func attribute(_ attrName: String, at location: Int, longestEffectiveRange range: NSRangePointer?, in rangeLimit: NSRange) -> Any? {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: true,
longestEffectiveRangeSearchRange: rangeLimit)
return _attribute(attrName, atIndex: location, rangeInfo: rangeInfo)
}
open func isEqual(to other: NSAttributedString) -> Bool { NSUnimplemented() }
public init(string str: String) {
_string = str._nsObject
_attributeArray = CFRunArrayCreate(kCFAllocatorDefault)
super.init()
addAttributesToAttributeArray(attrs: nil)
}
public init(string str: String, attributes attrs: [String : Any]?) {
_string = str._nsObject
_attributeArray = CFRunArrayCreate(kCFAllocatorDefault)
super.init()
addAttributesToAttributeArray(attrs: attrs)
}
public init(NSAttributedString attrStr: NSAttributedString) { NSUnimplemented() }
open func enumerateAttributes(in enumerationRange: NSRange, options opts: NSAttributedString.EnumerationOptions = [], using block: ([String : Any], NSRange, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { NSUnimplemented() }
open func enumerateAttribute(_ attrName: String, in enumerationRange: NSRange, options opts: NSAttributedString.EnumerationOptions = [], using block: (Any?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { NSUnimplemented() }
}
private extension NSAttributedString {
struct RangeInfo {
let rangePointer: NSRangePointer?
let shouldFetchLongestEffectiveRange: Bool
let longestEffectiveRangeSearchRange: NSRange?
}
func _attributes(at location: Int, rangeInfo: RangeInfo) -> [String : Any] {
var cfRange = CFRange()
return withUnsafeMutablePointer(to: &cfRange) { (cfRangePointer: UnsafeMutablePointer<CFRange>) -> [String : Any] in
// Get attributes value using CoreFoundation function
let value: CFDictionary
if rangeInfo.shouldFetchLongestEffectiveRange, let searchRange = rangeInfo.longestEffectiveRangeSearchRange {
value = CFAttributedStringGetAttributesAndLongestEffectiveRange(_cfObject, location, CFRange(searchRange), cfRangePointer)
} else {
value = CFAttributedStringGetAttributes(_cfObject, location, cfRangePointer)
}
// Convert the value to [String : AnyObject]
let dictionary = unsafeBitCast(value, to: NSDictionary.self)
var results = [String : Any]()
for (key, value) in dictionary {
guard let stringKey = (key as? NSString)?._swiftObject else {
continue
}
results[stringKey] = value
}
// Update effective range
let hasAttrs = results.count > 0
rangeInfo.rangePointer?.pointee.location = hasAttrs ? cfRangePointer.pointee.location : NSNotFound
rangeInfo.rangePointer?.pointee.length = hasAttrs ? cfRangePointer.pointee.length : 0
return results
}
}
func _attribute(_ attrName: String, atIndex location: Int, rangeInfo: RangeInfo) -> Any? {
var cfRange = CFRange()
return withUnsafeMutablePointer(to: &cfRange) { (cfRangePointer: UnsafeMutablePointer<CFRange>) -> AnyObject? in
// Get attribute value using CoreFoundation function
let attribute: AnyObject?
if rangeInfo.shouldFetchLongestEffectiveRange, let searchRange = rangeInfo.longestEffectiveRangeSearchRange {
attribute = CFAttributedStringGetAttributeAndLongestEffectiveRange(_cfObject, location, attrName._cfObject, CFRange(searchRange), cfRangePointer)
} else {
attribute = CFAttributedStringGetAttribute(_cfObject, location, attrName._cfObject, cfRangePointer)
}
// Update effective range and return the result
if let attribute = attribute {
rangeInfo.rangePointer?.pointee.location = cfRangePointer.pointee.location
rangeInfo.rangePointer?.pointee.length = cfRangePointer.pointee.length
return attribute
} else {
rangeInfo.rangePointer?.pointee.location = NSNotFound
rangeInfo.rangePointer?.pointee.length = 0
return nil
}
}
}
func addAttributesToAttributeArray(attrs: [String : Any]?) {
guard _string.length > 0 else {
return
}
let range = CFRange(location: 0, length: _string.length)
if let attrs = attrs {
CFRunArrayInsert(_attributeArray, range, attrs._cfObject)
} else {
let emptyAttrs = [String : AnyObject]()
CFRunArrayInsert(_attributeArray, range, emptyAttrs._cfObject)
}
}
}
extension NSAttributedString: _CFBridgeable {
internal var _cfObject: CFAttributedString { return unsafeBitCast(self, to: CFAttributedString.self) }
}
extension NSAttributedString {
public struct EnumerationOptions: OptionSet {
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
public static let Reverse = EnumerationOptions(rawValue: 1 << 1)
public static let LongestEffectiveRangeNotRequired = EnumerationOptions(rawValue: 1 << 20)
}
}
open class NSMutableAttributedString : NSAttributedString {
open func replaceCharacters(in range: NSRange, with str: String) { NSUnimplemented() }
open func setAttributes(_ attrs: [String : Any]?, range: NSRange) { NSUnimplemented() }
open var mutableString: NSMutableString {
return _string as! NSMutableString
}
open func addAttribute(_ name: String, value: Any, range: NSRange) {
CFAttributedStringSetAttribute(_cfMutableObject, CFRange(range), name._cfObject, _SwiftValue.store(value))
}
open func addAttributes(_ attrs: [String : Any], range: NSRange) { NSUnimplemented() }
open func removeAttribute(_ name: String, range: NSRange) { NSUnimplemented() }
open func replaceCharacters(in range: NSRange, with attrString: NSAttributedString) { NSUnimplemented() }
open func insert(_ attrString: NSAttributedString, at loc: Int) { NSUnimplemented() }
open func append(_ attrString: NSAttributedString) { NSUnimplemented() }
open func deleteCharacters(in range: NSRange) { NSUnimplemented() }
open func setAttributedString(_ attrString: NSAttributedString) { NSUnimplemented() }
open func beginEditing() { NSUnimplemented() }
open func endEditing() { NSUnimplemented() }
public override init(string str: String) {
super.init(string: str)
_string = NSMutableString(string: str)
}
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
}
extension NSMutableAttributedString {
internal var _cfMutableObject: CFMutableAttributedString { return unsafeBitCast(self, to: CFMutableAttributedString.self) }
}
|
apache-2.0
|
420dbbd94c2fb7ea40b37cdeca6cd8e1
| 39.317073 | 238 | 0.659105 | 5.670669 | false | false | false | false |
ihomway/RayWenderlichCourses
|
iOS Concurrency with GCD and Operations/Operations In Practice/TiltShift/TiltShift/TiltShiftImageProvider.swift
|
1
|
2440
|
/*
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
class TiltShiftImageProvider {
fileprivate let operationQueue = OperationQueue()
let tiltShiftImage: TiltShiftImage
init(tiltShiftImage: TiltShiftImage, completion:@escaping(UIImage?) -> ()) {
self.tiltShiftImage = tiltShiftImage
let url = Bundle.main.url(forResource: tiltShiftImage.imageName, withExtension: "compressed")!
// create the operations
let dataLoad = DataLoadOperation(url: url)
let imageDecompress = ImageDecompressionOperation(data: nil)
let tiltShift = TiltShiftOperation(image: nil)
let filterOutput = ImageFilterOutputOperation(completion: completion)
let process = PostProcessImageOperation(image: nil);
let operations = [dataLoad, imageDecompress, tiltShift, process, filterOutput]
// add dependencies
filterOutput.addDependency(process)
process.addDependency(tiltShift)
tiltShift.addDependency(imageDecompress)
imageDecompress.addDependency(dataLoad)
operationQueue.addOperations(operations, waitUntilFinished: false)
}
func cancel() {
operationQueue.cancelAllOperations()
}
}
extension TiltShiftImageProvider: Hashable {
var hashValue: Int {
return (tiltShiftImage.title + tiltShiftImage.imageName).hashValue
}
}
func ==(lhs: TiltShiftImageProvider, rhs: TiltShiftImageProvider) -> Bool {
return lhs.tiltShiftImage == rhs.tiltShiftImage
}
|
mit
|
9ebc4e6c0a91775496c2f80f8141712b
| 35.41791 | 96 | 0.777869 | 4.221453 | false | false | false | false |
wuyezhiguhun/DDSwift
|
DDSwift/百思不得姐/Main/DDBsbdjNavigationController.swift
|
1
|
1785
|
//
// DDBsbdjNavigationController.swift
// DDSwift
//
// Created by yutongmac on 2017/7/10.
// Copyright © 2017年 王允顶. All rights reserved.
//
import UIKit
class DDBsbdjNavigationController: UINavigationController {
override open class func initialize() ->Void {
let navBar = UINavigationBar.appearance()
let imageSize = CGSize(width: 320, height: 64)
UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale)
DDAlphaColor(a: 0.9, r: 252, g: 49, b: 89).set()
UIRectFill(CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let pressedColorImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
navBar.setBackgroundImage(pressedColorImg, for: UIBarMetrics.default)
}
override func viewDidLoad() {
super.viewDidLoad()
let navBarHairlineImageView = findHairlineImageViewUnder(imageView: self.navigationBar)
navBarHairlineImageView.isHidden = true
// Do any additional setup after loading the view.
}
func findHairlineImageViewUnder(imageView: UIView) -> UIImageView {
if (imageView is UIImageView) && imageView.bounds.size.height <= 1.0 {
return imageView as! UIImageView
}
for subView in imageView.subviews {
let imgView: UIImageView? = findHairlineImageViewUnder(imageView: subView)
if imgView != nil {
return imgView!
}
}
return UIImageView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
a8d49bf1d72847e29dd971cc6da4c7f1
| 23 | 95 | 0.637387 | 5.031161 | false | false | false | false |
ihomway/RayWenderlichCourses
|
Advanced Swift 3/Advanced Swift 3.playground/Pages/Error Handling Challenge.xcplaygroundpage/Contents.swift
|
1
|
1464
|
//: [Previous](@previous)
import Foundation
// Implement the following methods.
enum Placeholder: Error {
case notImplemented
}
public extension File {
// Challenge 1
// Rewind the file to the beginning.
// Hint: use seek(to:)
func rewind() throws {
try seek(to: Position(offset: 0))
}
// Challenge 2
// Get the size of the file.
// Hint: use fseek(file, 0, SEEK_END) and ftell(file)
func size() throws -> Int {
guard let file = file else {
throw FileError.notOpen
}
let pos = try position()
if fseek(file, 0, SEEK_END) != 0 {
throw FileError.seek
}
let result = ftell(file)
try seek(to: pos)
return result
}
}
/* Test code for you to try out your code with */
func test() {
// Open a file and write to it
do {
let file = try FileSystem.default.open(filepath: "Hello.txt", for: .writing)
for i in 1...3 {
try file.put("Hello, World 🌎 \(i)\n")
}
file.close()
}
catch {
print(error)
}
// Open the file, get it's size.
do {
let file = try FileSystem.default.open(filepath: "Hello.txt", for: .readingAndWriting)
print("Size:", try file.size())
for line in file.lines() {
print(line, terminator: "")
}
// Rewind and read it a second time
print("Reading a second time...")
try file.rewind()
for line in file.lines() {
print(line, terminator: "")
}
}
catch {
print("failed: \(error)")
}
}
// Comment this in when you are ready!
test()
//: [Next](@next)
|
mit
|
cfe749f961482836c270a1aa5ed70bd8
| 17.493671 | 88 | 0.622861 | 3 | false | false | false | false |
ArinaYauk/WetterApp
|
WetterApp/WetterApp/TableViewController.swift
|
1
|
1692
|
//
// TableViewController.swift
// WetterApp
//
// Created by student on 08.02.16.
// Copyright © 2016 student. All rights reserved.
//
import UIKit
struct InfoBit {
var Info1: String
var Info2: String
var Info3: String
}
class TableViewController: UITableViewController { //, UITableViewDataSource { <- in Swift 2.0 nicht mehr erforderlich
var InfoBits: [InfoBit] = [
InfoBit(Info1: "Info 1", Info2: "Text 1.1", Info3: "Text 1.2"),
InfoBit(Info1: "Info 2", Info2: "Text 2.1", Info3: "Text 2.2"),
InfoBit(Info1: "Info 3", Info2: "Text 3.1", Info3: "Text 3.2"),
InfoBit(Info1: "Info 4", Info2: "Text 4.1", Info3: "Text 4.2")
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//var cell = tableView.dequeueReusableCellWithIdentifier("cell") as BspCell
let cell = tableView.dequeueReusableCellWithIdentifier("BspCell", forIndexPath: indexPath) as! BspCell
cell.Label1.text = InfoBits[indexPath.row].Info1
cell.Label2.text = InfoBits[indexPath.row].Info2
cell.Label3.text = InfoBits[indexPath.row].Info3
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return InfoBits.count
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
8544a96c21dc2c71d07ebd0ca505650f
| 30.314815 | 119 | 0.646363 | 4.064904 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
Buy/Generated/Storefront/SellingPlanCheckoutChargePercentageValue.swift
|
1
|
2921
|
//
// SellingPlanCheckoutChargePercentageValue.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// The percentage value of the price used for checkout charge.
open class SellingPlanCheckoutChargePercentageValueQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = SellingPlanCheckoutChargePercentageValue
/// The percentage value of the price used for checkout charge.
@discardableResult
open func percentage(alias: String? = nil) -> SellingPlanCheckoutChargePercentageValueQuery {
addField(field: "percentage", aliasSuffix: alias)
return self
}
}
/// The percentage value of the price used for checkout charge.
open class SellingPlanCheckoutChargePercentageValue: GraphQL.AbstractResponse, GraphQLObject, SellingPlanCheckoutChargeValue {
public typealias Query = SellingPlanCheckoutChargePercentageValueQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "percentage":
guard let value = value as? Double else {
throw SchemaViolationError(type: SellingPlanCheckoutChargePercentageValue.self, field: fieldName, value: fieldValue)
}
return value
default:
throw SchemaViolationError(type: SellingPlanCheckoutChargePercentageValue.self, field: fieldName, value: fieldValue)
}
}
/// The percentage value of the price used for checkout charge.
open var percentage: Double {
return internalGetPercentage()
}
func internalGetPercentage(alias: String? = nil) -> Double {
return field(field: "percentage", aliasSuffix: alias) as! Double
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
|
mit
|
e82bb195ac41db6e8ae949c03a22e79d
| 39.013699 | 127 | 0.758987 | 4.359701 | false | false | false | false |
NingPeiChao/DouYu
|
DouYuTV/DouYuTV/Classes/Main/View/PageTitleView.swift
|
1
|
6353
|
//
// PageTitleView.swift
// DouYuTV
//
// Created by lulutrip on 2017/5/25.
// Copyright © 2017年 宁培超. All rights reserved.
//
import UIKit
protocol PageTitleViewDelgate : class {
func pageTitleView(_ titleView : PageTitleView , selectedIndex index : Int)
}
// MARK:- 定义常量
private let kScrollLineH : CGFloat = 2
private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85)
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
class PageTitleView: UIView {
//定义属性
fileprivate var currentIndex : Int = 0
fileprivate var titles : [String]
weak var delegate : PageTitleViewDelgate?
//懒加载属性
fileprivate lazy var titleLables : [UILabel] = [UILabel]()
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
fileprivate lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = .orange
return scrollLine
}()
// MARK:- 自定义构造函数
init(frame: CGRect , titles : [String]) {
self.titles = titles;
super.init(frame : frame)
// 设置UI界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
@objc fileprivate func titleLabelClick(_ tapGes : UITapGestureRecognizer){
// 0.获取当前Label
guard let currentLabel = tapGes.view as? UILabel else { return }
// 1.如果是重复点击同一个Title,那么直接返回
if currentLabel.tag == currentIndex { return }
// 2.获取之前的Label
let oldLabel = titleLables[currentIndex]
// 3.切换文字的颜色
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
// 4.保存最新Label的下标值
currentIndex = currentLabel.tag
// 5.滚动条位置发生改变
let scrollLineX = CGFloat(currentIndex) * scrollLine.frame.width
UIView.animate(withDuration: 0.15, animations: {
self.scrollLine.frame.origin.x = scrollLineX
})
// 6.通知代理
delegate?.pageTitleView(self, selectedIndex: currentIndex)
}
}
// MARK: - 设置UI界面
extension PageTitleView {
fileprivate func setupUI() {
// 1.添加UIScrollView
addSubview(scrollView)
scrollView.frame = bounds
// 2.添加title对应的Label
setupTitleLable()
// 3.设置底线和滚动的滑块
setupBottomLineAndScrollLine()
}
fileprivate func setupTitleLable() {
// 0.确定label的一些frame的值
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labelH : CGFloat = frame.height - kScrollLineH
let labelY : CGFloat = 0
for (index , title) in titles.enumerated() {
// 1.创建UILabel
let label = UILabel()
// 2.设置Label的属性
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.textAlignment = .center
// 3.设置label的frame
let labelX : CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
// 4.将label添加到scrollView中
scrollView.addSubview(label)
titleLables.append(label)
// 5.给Label添加手势
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(_:)))
label.addGestureRecognizer(tapGes)
}
}
fileprivate func setupBottomLineAndScrollLine() {
//1.添加底线
let bottomLine = UIView()
bottomLine.backgroundColor = .lightGray
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
//2.添加滚动条
guard let firstLabel = titleLables.first else {
return
}
firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
// 2.2.设置scrollLine的属性
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH)
}
}
// MARK:- 对外暴露的方法
extension PageTitleView {
func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) {
// 1.取出sourceLabel/targetLabel
let sourceLabel = titleLables[sourceIndex]
let targetLabel = titleLables[targetIndex]
// 2.处理滑块的逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
// 3.颜色的渐变(复杂)
// 3.1.取出变化的范围
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
// 3.2.变化sourceLabel
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
// 3.2.变化targetLabel
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
// 4.记录最新的index
currentIndex = targetIndex
}
}
|
mit
|
d66f1d0b6eac2e597ee1660ebfb9116b
| 31.367568 | 174 | 0.61022 | 4.703849 | false | false | false | false |
apple/swift-experimental-string-processing
|
Sources/_StringProcessing/Regex/Core.swift
|
1
|
5541
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@_implementationOnly import _RegexParser
/// A type that represents a regular expression.
@available(SwiftStdlib 5.7, *)
public protocol RegexComponent<RegexOutput> {
associatedtype RegexOutput
var regex: Regex<RegexOutput> { get }
}
/// A regular expression.
///
/// let regex = try Regex("a(.*)b")
/// let match = "cbaxb".firstMatch(of: regex)
/// print(match.0) // "axb"
/// print(match.1) // "x"
///
@available(SwiftStdlib 5.7, *)
public struct Regex<Output>: RegexComponent {
let program: Program
var hasCapture: Bool {
program.tree.hasCapture
}
init(ast: AST) {
self.program = Program(ast: ast)
}
init(ast: AST.Node) {
self.program = Program(ast:
.init(ast, globalOptions: nil, diags: Diagnostics()))
}
// Compiler interface. Do not change independently.
@usableFromInline
init(_regexString pattern: String) {
self.init(ast: try! parse(pattern, .traditional))
}
// Compiler interface. Do not change independently.
@usableFromInline
init(_regexString pattern: String, version: Int) {
assert(version == currentRegexLiteralFormatVersion)
// The version argument is passed by the compiler using the value defined
// in libswiftParseRegexLiteral.
self.init(ast: try! parseWithDelimiters(pattern))
}
public var regex: Regex<Output> {
self
}
}
@available(SwiftStdlib 5.7, *)
extension Regex {
@available(*, deprecated, renamed: "init(verbatim:)")
public init(quoting string: String) {
self.init(node: .quotedLiteral(string))
}
}
@available(SwiftStdlib 5.7, *)
extension Regex {
/// A program representation that caches any lowered representation for
/// execution.
internal final class Program {
/// The underlying IR.
///
/// FIXME: If Regex is the unit of composition, then it should be a Node instead,
/// and we should have a separate type that handled both global options and,
/// likely, compilation/caching.
let tree: DSLTree
/// OptionSet of compiler options for testing purposes
fileprivate var compileOptions: _CompileOptions = .default
private final class ProgramBox {
let value: MEProgram
init(_ value: MEProgram) { self.value = value }
}
/// Do not use directly - all accesses must go through `loweredProgram`.
fileprivate var _loweredProgramStorage: AnyObject? = nil
/// The program for execution with the matching engine.
var loweredProgram: MEProgram {
/// Atomically loads the compiled program if it has already been stored.
func loadProgram() -> MEProgram? {
guard let loweredObject = _stdlib_atomicLoadARCRef(object: &_loweredProgramStorage)
else { return nil }
return unsafeDowncast(loweredObject, to: ProgramBox.self).value
}
// Use the previously compiled program, if available.
if let program = loadProgram() {
return program
}
// Compile the DSLTree into a lowered program and store it atomically.
let compiledProgram = try! Compiler(tree: tree, compileOptions: compileOptions).emit()
let storedNewProgram = _stdlib_atomicInitializeARCRef(
object: &_loweredProgramStorage,
desired: ProgramBox(compiledProgram))
// Return the winner of the storage race. We're guaranteed at this point
// to have compiled program stored in `_loweredProgramStorage`.
return storedNewProgram
? compiledProgram
: loadProgram()!
}
init(ast: AST) {
self.tree = ast.dslTree
}
init(tree: DSLTree) {
self.tree = tree
}
}
/// The set of matching options that applies to the start of this regex.
///
/// Note that the initial options may not apply to the entire regex. For
/// example, in this regex, only case insensitivity (`i`) and Unicode scalar
/// semantics (set by API) apply to the entire regex, while ASCII character
/// classes (`P`) is part of `initialOptions` but not global:
///
/// let regex = /(?i)(?P:\d+\s*)abc/.semanticLevel(.unicodeScalar)
var initialOptions: MatchingOptions {
program.loweredProgram.initialOptions
}
}
@available(SwiftStdlib 5.7, *)
extension Regex {
var root: DSLTree.Node {
program.tree.root
}
init(node: DSLTree.Node) {
self.program = Program(tree: .init(node))
}
}
@available(SwiftStdlib 5.7, *)
@_spi(RegexBenchmark)
extension Regex {
public enum _RegexInternalAction {
case recompile
case addOptions(_CompileOptions)
}
/// Internal API for RegexBenchmark
/// Forces the regex to perform the given action, returning if it was successful
public mutating func _forceAction(_ action: _RegexInternalAction) -> Bool {
do {
switch action {
case .addOptions(let opts):
program.compileOptions.insert(opts)
program._loweredProgramStorage = nil
return true
case .recompile:
let _ = try Compiler(
tree: program.tree,
compileOptions: program.compileOptions).emit()
return true
}
} catch {
return false
}
}
}
|
apache-2.0
|
e15f6e9159e31feabe4f80ed061ecea4
| 29.278689 | 92 | 0.650966 | 4.325527 | false | false | false | false |
iAladdin/SwiftyFORM
|
Example/Usecases/ChangePasswordViewController.swift
|
1
|
2378
|
//
// ChangePasswordViewController.swift
// Example
//
// Created by Simon Strandgaard on 20-06-15.
// Copyright © 2015 Simon Strandgaard. All rights reserved.
//
import UIKit
import SwiftyFORM
class ChangePasswordViewController: FormViewController {
override func loadView() {
super.loadView()
form_installSubmitButton()
}
override func populate(builder: FormBuilder) {
builder.navigationTitle = "Password"
builder.toolbarMode = .Simple
builder += SectionHeaderTitleFormItem().title("Your Old Password")
builder += passwordOld
builder += SectionHeaderTitleFormItem().title("Your New Password")
builder += passwordNew
builder += passwordNewRepeated
builder.alignLeft([passwordOld, passwordNew, passwordNewRepeated])
}
lazy var passwordOld: TextFieldFormItem = {
let instance = TextFieldFormItem()
instance.title("Old password").password().placeholder("required")
instance.keyboardType = .NumberPad
instance.autocorrectionType = .No
instance.validate(CharacterSetSpecification.decimalDigitCharacterSet(), message: "Must be digits")
instance.submitValidate(CountSpecification.min(4), message: "Length must be minimum 4 digits")
instance.validate(CountSpecification.max(6), message: "Length must be maximum 6 digits")
return instance
}()
lazy var passwordNew: TextFieldFormItem = {
let instance = TextFieldFormItem()
instance.title("New password").password().placeholder("required")
instance.keyboardType = .NumberPad
instance.autocorrectionType = .No
instance.validate(CharacterSetSpecification.decimalDigitCharacterSet(), message: "Must be digits")
instance.submitValidate(CountSpecification.min(4), message: "Length must be minimum 4 digits")
instance.validate(CountSpecification.max(6), message: "Length must be maximum 6 digits")
return instance
}()
lazy var passwordNewRepeated: TextFieldFormItem = {
let instance = TextFieldFormItem()
instance.title("Repeat password").password().placeholder("required")
instance.keyboardType = .NumberPad
instance.autocorrectionType = .No
instance.validate(CharacterSetSpecification.decimalDigitCharacterSet(), message: "Must be digits")
instance.submitValidate(CountSpecification.min(4), message: "Length must be minimum 4 digits")
instance.validate(CountSpecification.max(6), message: "Length must be maximum 6 digits")
return instance
}()
}
|
mit
|
d2306a360262b3f0e2700480f6de892a
| 37.967213 | 100 | 0.770719 | 4.442991 | false | false | false | false |
hughbe/swift
|
test/Sanitizers/tsan.swift
|
1
|
969
|
// RUN: %target-swiftc_driver %s -g -sanitize=thread -o %t_tsan-binary
// RUN: not env TSAN_OPTIONS=abort_on_error=0 %target-run %t_tsan-binary 2>&1 | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// REQUIRES: CPU=x86_64
// REQUIRES: tsan_runtime
// Make sure we can handle swifterror and don't bail during the LLVM
// threadsanitizer pass.
enum MyError : Error {
case A
}
public func foobar(_ x: Int) throws {
if x == 0 {
throw MyError.A
}
}
public func call_foobar() {
do {
try foobar(1)
} catch(_) { }
}
// Test ThreadSanitizer execution end-to-end.
import Darwin
var threads: [pthread_t?] = []
var racey_x: Int;
for _ in 1...5 {
var t : pthread_t?
pthread_create(&t, nil, { _ in
print("pthread ran")
racey_x = 5;
return nil
}, nil)
threads.append(t)
}
for t in threads {
if t == nil {
print("nil thread")
continue
}
pthread_join(t!, nil)
}
// CHECK: ThreadSanitizer: data race
|
apache-2.0
|
3ced466bf29695854516107b4d99bbba
| 17.283019 | 93 | 0.630547 | 3.018692 | false | false | false | false |
rohan1989/FacebookOauth2Swift
|
OAuthSwift-master/Demo/Common/Storyboards.swift
|
6
|
1114
|
//
// Storyboards.swift
// OAuthSwift
//
// Created by phimage on 23/07/16.
// Copyright © 2016 Dongri Jin. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
public typealias OAuthStoryboard = UIStoryboard
public typealias OAuthStoryboardSegue = UIStoryboardSegue
#elseif os(OSX)
import AppKit
public typealias OAuthStoryboard = NSStoryboard
public typealias OAuthStoryboardSegue = NSStoryboardSegue
#endif
struct Storyboards {
struct Main {
static let identifier = "Storyboard"
static var storyboard: OAuthStoryboard {
return OAuthStoryboard(name: self.identifier, bundle: nil)
}
static func instantiateForm() -> FormViewController {
#if os(iOS)
return self.storyboard.instantiateViewController(withIdentifier: "Form") as! FormViewController
#elseif os(OSX)
return self.storyboard.instantiateController(withIdentifier: "Form") as! FormViewController
#endif
}
static let FormSegue = "form"
}
}
|
mit
|
742834bab76dc23081bd95b0a00d5a27
| 24.883721 | 111 | 0.65319 | 5.200935 | false | false | false | false |
larryhou/swift
|
Keychain/Keychain/AppDelegate.swift
|
1
|
4554
|
//
// AppDelegate.swift
// Keychain
//
// Created by larryhou on 02/10/2017.
// Copyright © 2017 larryhou. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Keychain")
container.loadPersistentStores(completionHandler: { (_, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
mit
|
c61b417dd47c85f15f89ada1d4fbbdcd
| 49.032967 | 285 | 0.687459 | 5.852185 | false | false | false | false |
cotsog/BricBrac
|
BricBrac/BricIO.swift
|
1
|
20636
|
//
// BricIO.swift
// Bric-à-brac
//
// Created by Marc Prud'hommeaux on 6/17/15.
// Copyright © 2015 io.glimpse. All rights reserved.
//
extension Bric : Streamable {
/// Streamable protocol implementation that writes the Bric as JSON to the given Target
public func writeTo<Target : OutputStreamType>(inout target: Target) {
writeJSON(&target)
}
/// Serializes this Bric as an ECMA-404 JSON Data Interchange Format string.
///
/// :param: mapper When set, .Obj instances will be passed through the given mapper to filter, re-order, or modify the values
@warn_unused_result
public func stringify(space space: Int = 0, bufferSize: Int? = nil, recursive: Bool = false, mapper: [String: Bric]->AnyGenerator<(String, Bric)> = { anyGenerator($0.generate()) })->String {
if recursive {
return stringifyRecursive(level: 1, space: space, mapper: mapper)
} else {
var str = String()
if let bufferSize = bufferSize {
str.reserveCapacity(bufferSize)
}
self.writeJSON(&str, space: space, mapper: mapper)
return str
}
}
// the emission state; note that indexes go from -1...count, since the edges are markers for container open/close tokens
private enum State {
case Arr(index: Int, array: [Bric])
case Obj(index: Int, object: [(String, Bric)])
}
/// A non-recursive streaming JSON stringifier
public func writeJSON<Target: OutputStreamType>(inout output: Target, space: Int = 0, mapper: [String: Bric]->AnyGenerator<(String, Bric)> = { anyGenerator($0.generate()) }) {
// the current stack of containers; we use this instead of recursion to track where we are in the process
var stack: [State] = []
func indent(level: Int) {
if space != 0 {
output.write("\n")
}
for _ in 0..<space*level {
output.write(" ")
}
}
func quoteString(str: String) {
output.write("\"")
for c in str.unicodeScalars {
switch c {
case "\\": output.write("\\\\")
case "\n": output.write("\\n")
case "\r": output.write("\\r")
case "\t": output.write("\\t")
case "\"": output.write("\\\"")
// case "/": output.write("\\/") // you may escape slashes, but we don't (neither does JSC's JSON.stringify)
case UnicodeScalar(0x08): output.write("\\b") // backspace
case UnicodeScalar(0x0C): output.write("\\f") // formfeed
default: output.write(String(c))
}
}
output.write("\"")
}
func processBric(bric: Bric) {
switch bric {
case .Nul:
output.write("null")
case .Bol(let bol):
if bol == true {
output.write("true")
} else {
output.write("false")
}
case .Str(let str):
quoteString(str)
case .Num(let num):
let str = String(num) // FIXME: this outputs exponential notation for some large numbers
// when a string ends in ".0", we just append the rounded int FIXME: better string formatting
if str.hasSuffix(".0") {
output.write(str[str.startIndex..<str.endIndex.predecessor().predecessor()])
} else {
output.write(str)
}
case .Arr(let arr):
stack.append(State.Arr(index: -1, array: arr))
case .Obj(let obj):
let keyValues = Array(mapper(obj))
stack.append(State.Obj(index: -1, object: keyValues))
}
}
func processArrayElement(index: Int, array: [Bric]) {
if index == -1 {
output.write("[")
return
} else if index == array.count {
if index > 0 { indent(stack.count) }
output.write("]")
return
} else if index > 0 {
output.write(",")
}
let element = array[index]
indent(stack.count)
processBric(element)
}
func processObjectElement(index: Int, object: [(String, Bric)]) {
if index == -1 {
output.write("{")
return
} else if index == object.count {
if index > 0 { indent(stack.count) }
output.write("}")
return
} else if index > 0 {
output.write(",")
}
let element = object[index]
indent(stack.count)
quoteString(element.0)
output.write(":")
if space > 0 { output.write(" ") }
processBric(element.1)
}
processBric(self) // now process ourself as the root bric
// walk through the stack and process each element in turn; note that the processing of elements may itself increase the stack
while !stack.isEmpty {
switch stack.removeLast() {
case .Arr(let index, let array):
if index < array.count {
stack.append(.Arr(index: index+1, array: array))
}
processArrayElement(index, array: array)
case .Obj(let index, let object):
if index < object.count {
stack.append(.Obj(index: index+1, object: object))
}
processObjectElement(index, object: object)
}
}
}
// OLD slow version
/// Serializes this Bric as an ECMA-404 JSON Data Interchange Format string.
///
/// :param: mapper When set, .Obj instances will be passed through the given mapper to filter, re-order, or modify the values
///
/// *Note* This is about 2x-3x slower than NSJSONSerialization
@warn_unused_result
private func stringifyRecursive(level level: Int = 1, space: Int? = nil, mapper: [String: Bric]->AnyGenerator<(String, Bric)> = { anyGenerator($0.generate()) })->String {
func quoteString(str: String)->String {
return "\"" + str.replace("\"", replacement: "\\\"") + "\""
}
let pre1 = String(count: (space ?? 0)*(level-1), repeatedValue: Character(" "))
let pre2 = String(count: (space ?? 0)*(level), repeatedValue: Character(" "))
let post = (space != nil) ? "\n" : ""
let colon = (space != nil) ? " : " : ":"
let comma = ","
switch self {
case .Nul:
return "null"
case .Bol(let bol):
return bol ? "true" : "false"
case .Str(let str):
return quoteString(str)
case .Num(let num):
return num == Double(Int(num)) ? String(Int(num)) : String(num) // FIXME: "0.6000000000000001" outputs as "0.6"
case .Arr(let arr):
var buffer = ""
for e in arr {
if !buffer.isEmpty { buffer += comma }
buffer += post + pre2 + e.stringifyRecursive(level: level+1, space: space, mapper: mapper)
}
return "[" + buffer + post + pre1 + "]"
case .Obj(let obj):
var buffer = ""
for (key, value) in mapper(obj) {
if !buffer.isEmpty { buffer += comma }
buffer += post + pre2 + quoteString(key) + colon + value.stringifyRecursive(level: level+1, space: space, mapper: mapper)
}
return "{" + buffer + post + pre1 + "}"
}
}
}
extension Bric : CustomDebugStringConvertible {
public var debugDescription: String {
return stringify()
}
}
/// **bricolage (brēˌkō-läzhˈ, brĭkˌō-)** *n. Something made or put together using whatever materials happen to be available*
///
/// Bricolage is the target storage for a JSON parser; for typical parsing, the storage is just `Bric`, but
/// other storages are possible:
///
/// * `EmptyBricolage`: doesn't store any data, and exists for fast validation of a document
/// * `CocoaBricolage`: storage that is compatible with Cocoa's `NSJSONSerialization` APIs
///
/// Note that nothing prevents `Bricolage` storage from being lossy, such as numeric types overflowing
/// or losing precision from number strings
public protocol Bricolage {
typealias NulType
typealias StrType
typealias NumType
typealias BolType
typealias ArrType
typealias ObjType
init(nul: NulType)
init(str: StrType)
init(num: NumType)
init(bol: BolType)
init(arr: ArrType)
init(obj: ObjType)
@warn_unused_result
static func createNull() -> NulType
@warn_unused_result
static func createTrue() -> BolType
@warn_unused_result
static func createFalse() -> BolType
@warn_unused_result
static func createObject() -> ObjType
@warn_unused_result
static func createArray() -> ArrType
@warn_unused_result
static func createString(scalars: [UnicodeScalar]) -> StrType?
@warn_unused_result
static func createNumber(scalars: [UnicodeScalar]) -> NumType?
@warn_unused_result
static func putKeyValue(obj: ObjType, key: StrType, value: Self) -> ObjType
@warn_unused_result
static func putElement(arr: ArrType, element: Self) -> ArrType
}
/// An empty implementation of JSON storage which can be used for fast validation
public struct EmptyBricolage: Bricolage {
public typealias NulType = Void
public typealias BolType = Void
public typealias StrType = Void
public typealias NumType = Void
public typealias ArrType = Void
public typealias ObjType = Void
public init(nul: NulType) { }
public init(bol: BolType) { }
public init(str: StrType) { }
public init(num: NumType) { }
public init(arr: ArrType) { }
public init(obj: ObjType) { }
public static func createNull() -> NulType { }
public static func createTrue() -> BolType { }
public static func createFalse() -> BolType { }
public static func createString(scalars: [UnicodeScalar]) -> StrType? { return StrType() }
public static func createNumber(scalars: [UnicodeScalar]) -> NumType? { return NumType() }
public static func createArray() -> ArrType { }
public static func createObject() -> ObjType { }
public static func putElement(arr: ArrType, element: EmptyBricolage) -> ArrType { }
public static func putKeyValue(obj: ObjType, key: StrType, value: EmptyBricolage) -> ObjType { }
}
/// Storage for JSON that maintains the raw underlying JSON values, which means that long number
/// strings and object-key ordering information is preserved (although whitespace is still lost)
public enum FidelityBricolage : Bricolage {
public typealias NulType = Void
public typealias BolType = Bool
public typealias StrType = Array<UnicodeScalar>
public typealias NumType = Array<UnicodeScalar>
public typealias ArrType = Array<FidelityBricolage>
public typealias ObjType = Array<(StrType, FidelityBricolage)>
case Nul(NulType)
case Bol(BolType)
case Str(StrType)
case Num(NumType)
case Arr(ArrType)
case Obj(ObjType)
public init(nul: NulType) { self = .Nul(nul) }
public init(bol: BolType) { self = .Bol(bol) }
public init(str: StrType) { self = .Str(str) }
public init(num: NumType) { self = .Num(num) }
public init(arr: ArrType) { self = .Arr(arr) }
public init(obj: ObjType) { self = .Obj(obj) }
public static func createNull() -> NulType { }
public static func createTrue() -> BolType { return true }
public static func createFalse() -> BolType { return false }
public static func createObject() -> ObjType { return ObjType() }
public static func createArray() -> ArrType { return ArrType() }
public static func createString(scalars: [UnicodeScalar]) -> StrType? { return scalars }
public static func createNumber(scalars: [UnicodeScalar]) -> NumType? { return scalars }
public static func putElement(var arr: ArrType, element: FidelityBricolage) -> ArrType {
arr.append(element)
return arr
}
public static func putKeyValue(var obj: ObjType, key: StrType, value: FidelityBricolage) -> ObjType {
obj.append((key, value))
return obj
}
}
/// Storage for JSON that is tailored for Swift-fluent access
extension Bric: Bricolage {
public typealias Storage = Bric
public typealias NulType = Void
public typealias BolType = Bool
public typealias StrType = String
public typealias NumType = Double
public typealias ArrType = Array<Bric>
public typealias ObjType = Dictionary<StrType, Bric>
public init(nul: NulType) { self = .Nul }
public init(bol: BolType) { self = .Bol(bol) }
public init(str: StrType) { self = .Str(str) }
public init(num: NumType) { self = .Num(num) }
public init(arr: ArrType) { self = .Arr(arr) }
public init(obj: ObjType) { self = .Obj(obj) }
public static func createNull() -> NulType { }
public static func createTrue() -> BolType { return true }
public static func createFalse() -> BolType { return false }
public static func createObject() -> ObjType { return ObjType() }
public static func createArray() -> ArrType { return ArrType() }
public static func createString(scalars: [UnicodeScalar]) -> StrType? { return String(scalars: scalars) }
public static func createNumber(scalars: [UnicodeScalar]) -> NumType? { return Double(String(scalars: scalars)) }
public static func putElement(var arr: ArrType, element: Bric) -> ArrType {
arr.append(element)
return arr
}
public static func putKeyValue(var object: ObjType, key: StrType, value: Bric) -> ObjType {
object[key] = value
return object
}
}
extension Bric {
/// Parses the given JSON string and returns some Bric
public static func parse(string: String, options: JSONParser.Options = .Strict) throws -> Bric {
return try Bric.parseBricolage(Array(string.unicodeScalars), options: options)
// the following also works fine, but converting to an array first is dramatically faster (over 2x faster for caliper.json)
// return try Bric.parseBricolage(string.unicodeScalars, options: options)
}
/// Parses the given JSON array of unicode scalars and returns some Bric
public static func parse(scalars: [UnicodeScalar], options: JSONParser.Options = .Strict) throws -> Bric {
return try Bric.parseJSON(scalars, options: options)
}
}
extension Bric {
/// Validates the given JSON string and throws an error if there was a problem
public static func validate(string: String, options: JSONParser.Options) throws {
try JSONParser(options: options).parse(Array(string.unicodeScalars), complete: true)
}
/// Validates the given array of JSON unicode scalars and throws an error if there was a problem
public static func validate(scalars: [UnicodeScalar], options: JSONParser.Options) throws {
try JSONParser(options: options).parse(scalars, complete: true)
}
}
private enum Container<T : Bricolage> {
case Object(T.ObjType, T.StrType?)
case Array(T.ArrType)
}
extension Bricolage {
public static func parseJSON(scalars: [UnicodeScalar], options opts: JSONParser.Options) throws -> Self {
return try parseBricolage(scalars, options: opts)
}
public static func parseBricolage<S: SequenceType where S.Generator.Element == UnicodeScalar>(scalars: S, options opts: JSONParser.Options) throws -> Self {
typealias T = Self
var current: T = T(nul: T.createNull()) // the current object being processed
// the delegate merely remembers the last top-most bric element (which will hold all the children)
var parser = bricolageParser(options: opts) { (bric, level) in
if level == 0 { current = bric }
return bric
}
assert(isUniquelyReferencedNonObjC(&parser))
try parser.parse(scalars, complete: true)
assert(isUniquelyReferencedNonObjC(&parser)) // leak prevention
return current
}
/// Creates and returns a parser that will emit fully-formed Bricolage instances to the given delegate
/// Note that the delegate will emit the same Bricolage instance once the instance has been realized,
/// as well as once a container has been completed.
///
/// - param options: the options for the JSON parser to use
/// - param delegate: a closure through which each Bricolage instance will pass, returning the
/// actual Bricolage instance that should be added to the stack
///
/// - returns: a configured JSON parser with the Bricolage delegate
public static func bricolageParser(options opts: JSONParser.Options, delegate: (Self, level: Int) -> Self) -> JSONParser {
typealias T = Self
// the stack holds all of the currently-open containers; in order to handle parsing
// top-level non-containers, the top of the stack is always an array that should
// contain only a single element
var stack: [Container<T>] = []
let parser = JSONParser(options: opts)
parser.delegate = { [unowned parser] event in
func err(msg: String) -> ParseError { return ParseError(msg: msg, line: parser.row, column: parser.col) }
func closeContainer() throws {
if stack.count <= 0 { throw err("Cannot close top-level container") }
switch stack.removeLast() {
case .Object(let x, _): try pushValue(T(obj: x))
case .Array(let x): try pushValue(T(arr: x))
}
}
func pushValue(x: T) throws {
// inform the delegate that we have seen a fully-formed Bric
let value = delegate(x, level: stack.count)
switch stack.last {
case .Some(.Object(let x, let key)):
if let key = key {
stack[stack.endIndex.predecessor()] = .Object(T.putKeyValue(x, key: key, value: value), .None)
} else {
throw err("Put object with no key type")
}
case .Some(.Array(let x)):
stack[stack.endIndex.predecessor()] = .Array(T.putElement(x, element: value))
case .None:
break
}
}
switch event {
case .ObjectStart:
stack.append(.Object(T.createObject(), .None))
case .ObjectEnd:
try closeContainer()
case .ArrayStart:
stack.append(.Array(T.createArray()))
case .ArrayEnd:
try closeContainer()
case .StringContent(let s, let e):
let escaped = try JSONParser.unescape(s, escapeIndices: e, line: parser.row, column: parser.col)
if let str = T.createString(escaped) {
if case .Some(.Object(let x, let key)) = stack.last where key == nil {
stack[stack.endIndex.predecessor()] = .Object(x, str)
delegate(T(str: str), level: stack.count)
} else {
try pushValue(T(str: str))
}
} else {
throw err("Unable to create string")
}
case .Number(let n):
if let num = T.createNumber(Array(n)) {
try pushValue(T(num: num))
} else {
throw err("Unable to create number")
}
case .True:
try pushValue(T(bol: T.createTrue()))
case .False:
try pushValue(T(bol: T.createFalse()))
case .Null:
try pushValue(T(nul: T.createNull()))
case .Whitespace, .ElementSeparator, .KeyValueSeparator, .StringStart, .StringEnd:
break // whitespace is ignored in document parsing
}
}
return parser
}
}
extension String {
/// Convenience for creating a string from an array of UnicodeScalars
init(scalars: [UnicodeScalar]) {
self = String(String.UnicodeScalarView() + scalars) // seems a tiny bit faster
}
}
|
mit
|
b8e0e08c846ef8c7ede6d74a7c068e4f
| 39.363992 | 194 | 0.591923 | 4.356072 | false | false | false | false |
xedin/swift
|
test/IDE/complete_after_self.swift
|
5
|
16503
|
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONSTRUCTOR_SELF_NO_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=CONSTRUCTOR_SELF_NO_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=COMMON_SELF_NO_DOT_1 < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONSTRUCTOR_NONSELF_NO_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=COMMON_SELF_NO_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=NO_INIT < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONSTRUCTOR_SELF_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=CONSTRUCTOR_SELF_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=COMMON_SELF_DOT_1 < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONSTRUCTOR_NONSELF_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=COMMON_SELF_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=NO_INIT < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DESTRUCTOR_SELF_NO_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=DESTRUCTOR_SELF_NO_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=COMMON_SELF_NO_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=NO_INIT < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DESTRUCTOR_SELF_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=DESTRUCTOR_SELF_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=COMMON_SELF_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=NO_INIT < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_SELF_NO_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=FUNC_SELF_NO_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=COMMON_SELF_NO_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=NO_INIT < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STATIC_SELF_PAREN > %t.self.txt
// RUN: %FileCheck %s -check-prefix=STATIC_SELF_PAREN < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_SELF_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=FUNC_SELF_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=COMMON_SELF_DOT_1 < %t.self.txt
// RUN: %FileCheck %s -check-prefix=NO_INIT < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_STATIC_SELF_NO_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=FUNC_STATIC_SELF_NO_DOT_1 < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_STATIC_SELF_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=FUNC_STATIC_SELF_DOT_1 < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_CONSTRUCTOR_SELF_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=STRUCT_CONSTRUCTOR_SELF_DOT_1 < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_CONSTRUCTOR_NONSELF_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=NO_INIT < %t.self.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_FUNC_SELF_DOT_1 > %t.self.txt
// RUN: %FileCheck %s -check-prefix=NO_INIT < %t.self.txt
//===---
//===--- Tests for code completion after 'self'.
//===---
class ThisBase1 {
var baseInstanceVar: Int
func baseFunc0() {}
func baseFunc1(_ a: Int) {}
subscript(i: Int) -> Double {
get {
return Double(i)
}
set(v) {
baseInstanceVar = i
}
}
class var baseStaticVar: Int = 12
class func baseStaticFunc0() {}
}
extension ThisBase1 {
var baseExtProp : Int {
get {
return 42
}
set(v) {}
}
func baseExtInstanceFunc0() {}
var baseExtStaticVar: Int
var baseExtStaticProp: Int {
get {
return 42
}
sel(v) {}
}
class func baseExtStaticFunc0() {}
struct BaseExtNestedStruct {}
class BaseExtNestedClass {}
enum BaseExtNestedEnum {
case BaseExtEnumX(Int)
}
typealias BaseExtNestedTypealias = Int
}
class ThisDerived1 : ThisBase1 {
var derivedInstanceVar: Int
func derivedFunc0() {}
subscript(i: Double) -> Int {
get {
return Int(i)
}
set(v) {
baseInstanceVar = Int(i)
}
}
subscript(s s: String) -> Int {
get {
return 0
}
set(v) {
}
}
class var derivedStaticVar: Int = 42
class func derivedStaticFunc0() {}
// COMMON_SELF_NO_DOT_1: Begin completions
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceVar]/CurrNominal: .derivedInstanceVar[#Int#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: .derivedFunc0()[#Void#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[Subscript]/CurrNominal: [{#(i): Double#}][#Int#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[Subscript]/CurrNominal: [{#s: String#}][#Int#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: .test1()[#Void#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: .test2()[#Void#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceVar]/CurrNominal: .derivedExtProp[#Int#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: .derivedExtInstanceFunc0()[#Void#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceVar]/CurrNominal: .derivedExtStaticProp[#Int#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceVar]/Super: .baseInstanceVar[#Int#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceMethod]/Super: .baseFunc0()[#Void#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceMethod]/Super: .baseFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[Subscript]/Super: [{#(i): Int#}][#Double#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceVar]/Super: .baseExtProp[#Int#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceMethod]/Super: .baseExtInstanceFunc0()[#Void#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1-DAG: Decl[InstanceVar]/Super: .baseExtStaticProp[#Int#]{{; name=.+$}}
// COMMON_SELF_NO_DOT_1: End completions
// COMMON_SELF_DOT_1: Begin completions
// COMMON_SELF_DOT_1-DAG: Decl[InstanceVar]/CurrNominal: derivedInstanceVar[#Int#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: derivedFunc0()[#Void#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: test1()[#Void#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: test2()[#Void#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceVar]/CurrNominal: derivedExtProp[#Int#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: derivedExtInstanceFunc0()[#Void#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceVar]/CurrNominal: derivedExtStaticProp[#Int#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceVar]/Super: baseInstanceVar[#Int#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceMethod]/Super: baseFunc0()[#Void#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceMethod]/Super: baseFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceVar]/Super: baseExtProp[#Int#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceMethod]/Super: baseExtInstanceFunc0()[#Void#]{{; name=.+$}}
// COMMON_SELF_DOT_1-DAG: Decl[InstanceVar]/Super: baseExtStaticProp[#Int#]{{; name=.+$}}
// COMMON_SELF_DOT_1: End completions
init() {
self#^CONSTRUCTOR_SELF_NO_DOT_1^#
// CONSTRUCTOR_SELF_NO_DOT_1: Begin completions, 21 items
// CONSTRUCTOR_SELF_NO_DOT_1-NOT: Decl[Constructor]
// CONSTRUCTOR_SELF_NO_DOT_1: End completions
let d: ThisDerived1
d#^CONSTRUCTOR_NONSELF_NO_DOT_1^#
// NO_INIT-NOT: init()
}
init(a : Int) {
self.#^CONSTRUCTOR_SELF_DOT_1^#
// CONSTRUCTOR_SELF_DOT_1: Begin completions, 16 items
// CONSTRUCTOR_SELF_DOT_1-NOT: Decl[Constructor]
// CONSTRUCTOR_SELF_DOT_1: End completions
let d: ThisDerived1
d.#^CONSTRUCTOR_NONSELF_DOT_1^#
}
deinit {
self#^DESTRUCTOR_SELF_NO_DOT_1^#
// DESTRUCTOR_SELF_NO_DOT_1: Begin completions, 21 items
// DESTRUCTOR_SELF_NO_DOT_1: End completions
self.#^DESTRUCTOR_SELF_DOT_1^#
// DESTRUCTOR_SELF_DOT_1: Begin completions, 16 items
// DESTRUCTOR_SELF_DOT_1: End completions
}
func test1() {
self#^FUNC_SELF_NO_DOT_1^#
// FUNC_SELF_NO_DOT_1: Begin completions, 21 items
// FUNC_SELF_NO_DOT_1: End completions
}
func test2() {
self.#^FUNC_SELF_DOT_1^#
// FUNC_SELF_DOT_1: Begin completions, 16 items
// FUNC_SELF_DOT_1: End completions
}
class func staticTest1() {
self#^FUNC_STATIC_SELF_NO_DOT_1^#
// FUNC_STATIC_SELF_NO_DOT_1: Begin completions
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: .derivedFunc0({#(self): ThisDerived1#})[#() -> Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[StaticVar]/CurrNominal: .derivedStaticVar[#Int#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[StaticMethod]/CurrNominal: .derivedStaticFunc0()[#Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[Constructor]/CurrNominal: .init()[#ThisDerived1#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[Constructor]/CurrNominal: .init({#a: Int#})[#ThisDerived1#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: .test1({#(self): ThisDerived1#})[#() -> Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: .test2({#(self): ThisDerived1#})[#() -> Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[StaticMethod]/CurrNominal: .staticTest1()[#Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[StaticMethod]/CurrNominal: .staticTest2()[#Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: .derivedExtInstanceFunc0({#(self): ThisDerived1#})[#() -> Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[StaticMethod]/CurrNominal: .derivedExtStaticFunc0()[#Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[Struct]/CurrNominal: .DerivedExtNestedStruct[#ThisDerived1.DerivedExtNestedStruct#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[Class]/CurrNominal: .DerivedExtNestedClass[#ThisDerived1.DerivedExtNestedClass#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[Enum]/CurrNominal: .DerivedExtNestedEnum[#ThisDerived1.DerivedExtNestedEnum#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[TypeAlias]/CurrNominal: .DerivedExtNestedTypealias[#Int#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[Constructor]/CurrNominal: .init({#someExtensionArg: Int#})[#ThisDerived1#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[InstanceMethod]/Super: .baseFunc0({#(self): ThisBase1#})[#() -> Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[InstanceMethod]/Super: .baseFunc1({#(self): ThisBase1#})[#(Int) -> Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[StaticVar]/Super: .baseStaticVar[#Int#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[StaticMethod]/Super: .baseStaticFunc0()[#Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[InstanceMethod]/Super: .baseExtInstanceFunc0({#(self): ThisBase1#})[#() -> Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[StaticMethod]/Super: .baseExtStaticFunc0()[#Void#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[Struct]/Super: .BaseExtNestedStruct[#ThisBase1.BaseExtNestedStruct#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[Class]/Super: .BaseExtNestedClass[#ThisBase1.BaseExtNestedClass#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[Enum]/Super: .BaseExtNestedEnum[#ThisBase1.BaseExtNestedEnum#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Decl[TypeAlias]/Super: .BaseExtNestedTypealias[#Int#]
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: Keyword[self]/CurrNominal: .self[#ThisDerived1.Type#]; name=self
// FUNC_STATIC_SELF_NO_DOT_1-NEXT: End completions
}
class func staticTest2() {
self.#^FUNC_STATIC_SELF_DOT_1^#
// FUNC_STATIC_SELF_DOT_1: Begin completions
// FUNC_STATIC_SELF_DOT_1-NEXT: Keyword[self]/CurrNominal: self[#ThisDerived1.Type#]; name=self
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: derivedFunc0({#(self): ThisDerived1#})[#() -> Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[StaticVar]/CurrNominal: derivedStaticVar[#Int#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[StaticMethod]/CurrNominal: derivedStaticFunc0()[#Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[Constructor]/CurrNominal: init()[#ThisDerived1#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[Constructor]/CurrNominal: init({#a: Int#})[#ThisDerived1#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: test1({#(self): ThisDerived1#})[#() -> Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: test2({#(self): ThisDerived1#})[#() -> Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[StaticMethod]/CurrNominal: staticTest1()[#Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[StaticMethod]/CurrNominal: staticTest2()[#Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: derivedExtInstanceFunc0({#(self): ThisDerived1#})[#() -> Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[StaticMethod]/CurrNominal: derivedExtStaticFunc0()[#Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[Struct]/CurrNominal: DerivedExtNestedStruct[#ThisDerived1.DerivedExtNestedStruct#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[Class]/CurrNominal: DerivedExtNestedClass[#ThisDerived1.DerivedExtNestedClass#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[Enum]/CurrNominal: DerivedExtNestedEnum[#ThisDerived1.DerivedExtNestedEnum#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[TypeAlias]/CurrNominal: DerivedExtNestedTypealias[#Int#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[Constructor]/CurrNominal: init({#someExtensionArg: Int#})[#ThisDerived1#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[InstanceMethod]/Super: baseFunc0({#(self): ThisBase1#})[#() -> Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[InstanceMethod]/Super: baseFunc1({#(self): ThisBase1#})[#(Int) -> Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[StaticVar]/Super: baseStaticVar[#Int#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[StaticMethod]/Super: baseStaticFunc0()[#Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[InstanceMethod]/Super: baseExtInstanceFunc0({#(self): ThisBase1#})[#() -> Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[StaticMethod]/Super: baseExtStaticFunc0()[#Void#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[Struct]/Super: BaseExtNestedStruct[#ThisBase1.BaseExtNestedStruct#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[Class]/Super: BaseExtNestedClass[#ThisBase1.BaseExtNestedClass#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[Enum]/Super: BaseExtNestedEnum[#ThisBase1.BaseExtNestedEnum#]
// FUNC_STATIC_SELF_DOT_1-NEXT: Decl[TypeAlias]/Super: BaseExtNestedTypealias[#Int#]
// FUNC_STATIC_SELF_DOT_1-NEXT: End completions
}
}
class func staticTest3() {
self(#^STATIC_SELF_PAREN^#
// STATIC_SELF_PAREN-NOT: Decl[Constructor]
}
extension ThisDerived1 {
var derivedExtProp : Int {
get {
return 42
}
set(v) {}
}
func derivedExtInstanceFunc0() {}
var derivedExtStaticVar: Int
var derivedExtStaticProp: Int {
get {
return 42
}
set(v) {}
}
class func derivedExtStaticFunc0() {}
struct DerivedExtNestedStruct {}
class DerivedExtNestedClass {}
enum DerivedExtNestedEnum {
case DerivedExtEnumX(Int)
}
typealias DerivedExtNestedTypealias = Int
convenience init(someExtensionArg: Int) {
self.#^EXTENSION_CONSTRUCTOR_SELF_DOT_1^#
}
}
struct S1 {
init() {}
init(x: Int) {
self.#^STRUCT_CONSTRUCTOR_SELF_DOT_1^#
// STRUCT_CONSTRUCTOR_SELF_DOT_1: Begin completions, 2 items
// STRUCT_CONSTRUCTOR_SELF_DOT_1-DAG: Keyword[self]/CurrNominal: self[#S1#]; name=self
// STRUCT_CONSTRUCTOR_SELF_DOT_1-NOT: Decl[Constructor]
// STRUCT_CONSTRUCTOR_SELF_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: f()[#Void#];
// STRUCT_CONSTRUCTOR_SELF_DOT_1: End completions
let s: S1
s.#^STRUCT_CONSTRUCTOR_NONSELF_DOT_1^#
}
func f() {
self.#^STRUCT_FUNC_SELF_DOT_1^#
}
}
|
apache-2.0
|
b8ba0af183a9caa79a25744f1be7f889
| 48.558559 | 137 | 0.673999 | 3.244152 | false | true | false | false |
lucdion/aide-devoir
|
sources/AideDevoir/Classes/Helpers/UIScrollView.swift
|
1
|
696
|
//
// UIScrollView.swift
// iHeart
//
// Created by Luc Dion on 2016-07-07.
// Copyright © 2016 Bell Media. All rights reserved.
//
import UIKit
extension UIScrollView {
func insetSetTop(_ top: CGFloat, updateScrollInset: Bool) {
var inset = self.contentInset
inset.top = top
contentInset = inset
if updateScrollInset {
scrollIndicatorInsets = contentInset
}
}
func insetSetBottom(_ bottom: CGFloat, updateScrollInset: Bool) {
var inset = self.contentInset
inset.bottom = bottom
contentInset = inset
if updateScrollInset {
scrollIndicatorInsets = contentInset
}
}
}
|
apache-2.0
|
b11a9d03475b026aa6957ffa5a264769
| 21.419355 | 69 | 0.621583 | 4.602649 | false | false | false | false |
KevinChouRafael/Shrimp
|
Shrimp/Classes/ShrimpRequest.swift
|
1
|
18477
|
//
// ShrimpRequest.swift
// Shrimp
//
// Created by Rafael on 12/28/15.
// Copyright © 2015 Rafael. All rights reserved.
//
import Foundation
open class ShrimpRequest {
fileprivate var urlRequest:NSMutableURLRequest!
fileprivate var config:URLSessionConfiguration!
fileprivate var task:URLSessionDataTask!
fileprivate var responseDataHandler:((_ data:Data,_ response:URLResponse)->Void)?
fileprivate var responseStringHandler:((_ string:String,_ response:URLResponse)->Void)?
fileprivate var responseJSONObjectHandler:((_ json:Any,_ response:URLResponse)->Void)?
fileprivate var errorHandler:((_ error:Error?)->Void)?
//Saved ContentType: ContentType parameters > headers params > defaultContentType
fileprivate var contentType:ContentType!
public init(){
}
// open func defaultHeaders() ->[String:String]{
// return [String:String]()
// }
open func request(
_ method: Method,
api: ShrimpNetApi,
contentType:ContentType? = nil,
parameters: [String: Any]? = nil,
headers: [String: String]? = nil)
-> ShrimpRequest
{
buildURL(method, urlString: api.path,parameters: parameters)
buildHeader(method, headers: headers,contentType: contentType)
buildParameters(method, parameters: parameters)
return self
}
open func request(
_ method: Method,
urlString: String,
contentType:ContentType? = nil,
parameters: [String: Any]? = nil,
headers: [String: String]? = nil)
-> ShrimpRequest
{
buildURL(method, urlString: urlString,parameters: parameters)
buildHeader(method, headers: headers,contentType: contentType)
buildParameters(method, parameters: parameters)
return self
}
fileprivate func buildURL(_ method:Method,urlString:String,parameters: [String: Any]? = nil){
var requestURL:URL = URL(string:"\(urlString)")!
if parameters != nil {
switch method {
case .GET:
// requestURL = URL(string:"\(urlString)?\(query(parameters!))")!s
var components = URLComponents(string: urlString)!
components.queryItems = [URLQueryItem]()
for (key, value) in parameters ?? [:] {
let queryItem = URLQueryItem(name: key, value: "\(value)")
components.queryItems!.append(queryItem)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
requestURL = components.url!
break
case .POST, .PUT, .DELETE:
break
}
}
urlRequest = NSMutableURLRequest(url: requestURL)
urlRequest!.httpMethod = method.rawValue
}
fileprivate func buildHeader(_ method:Method,headers: [String: String]? = nil,contentType:ContentType? = nil){
//header
var headerDic = ShrimpConfigure.shared.defaultHeaders()
switch method {
case .GET:
headerDic["Content-Type"] = ShrimpConfigure.shared.DefaultGetContentType.rawValue
break
case .POST, .PUT, .DELETE:
headerDic["Content-Type"] = ShrimpConfigure.shared.DefaultPostContentType.rawValue
break
}
if headers != nil {
for (key,value) in headers! {
headerDic[key] = value
}
}
if let ctype = contentType{
headerDic["Content-Type"] = ctype.rawValue
}
self.contentType = ContentType(rawValue: headerDic["Content-Type"]!)!
config = URLSessionConfiguration.default
config!.httpAdditionalHeaders = headerDic
}
fileprivate func buildParameters(_ method:Method,parameters:[String: Any]? = nil){
switch method {
case .GET:
break
case .POST, .PUT, .DELETE:
if parameters != nil {
switch contentType {
case .UrlEncoded:
let queryString = query(parameters!)
urlRequest.httpBody = queryString.data(using: String.Encoding.utf8)
break;
case .JSON:
do{
let data = try JSONSerialization.data(withJSONObject: parameters!, options: .prettyPrinted)
urlRequest.httpBody = data
}catch{
}
break;
case .none:
assertionFailure("Content-Type Error.")
break
}
}
break
}
}
@discardableResult
public func responseData(_ responseHandler:@escaping (_ data:Data,_ response:URLResponse?)->Void,errorHandler:(@escaping (_ error:Error?)->Void))->ShrimpRequest{
self.responseDataHandler = responseHandler
self.errorHandler = errorHandler
requestNetWork()
return self
}
@discardableResult
public func responseData(_ responseHandler:@escaping (_ data:Data?,_ response:URLResponse?)->Void,errorHandler:((_ error:Error?)->Void)? = nil)->ShrimpRequest{
self.responseDataHandler = responseHandler
self.errorHandler = errorHandler
requestNetWork()
return self
}
@discardableResult
public func responseString(_ responseHandler:@escaping (_ string:String,_ response:URLResponse?)->Void,errorHandler:@escaping (_ error:Error?)->Void)->ShrimpRequest{
self.responseStringHandler = responseHandler
self.errorHandler = errorHandler
requestNetWork()
return self
}
@discardableResult
public func responseJSONObject(_ responseHandler:@escaping (_ json:Any,_ response:URLResponse?)->Void,errorHandler:@escaping (_ error:Error?)->Void)->ShrimpRequest{
self.responseJSONObjectHandler = responseHandler
self.errorHandler = errorHandler
requestNetWork()
return self
}
fileprivate func requestNetWork(){
let session = URLSession(configuration: config)
task = session.dataTask(with: urlRequest as URLRequest, completionHandler: { (data, response, error) in
//guard error
//guard data,response
guard error == nil else{
debugPrint("***ShrimpRequest-- Request URL --> \(String(describing: response?.url?.absoluteString)) \n Error -> \(error!.localizedDescription) \n")
DispatchQueue.main.async {
self.errorHandler?(error)
}
return
}
guard let data = data, let response = response, let httpResponse = response as? HTTPURLResponse else{
debugPrint("***ShrimpRequest-- no response and data. \n")
DispatchQueue.main.async {
self.errorHandler?(error)
}
return
}
let code = httpResponse.statusCode
let resultString = String(data: data, encoding: String.Encoding.utf8)
// let acceptableStatusCodes: CountableRange<Int> = 200..<300
// if acceptableStatusCodes.contains(httpResponse.statusCode) {
debugPrint("***ShrimpRequest-- Request URL --> \( String(describing: httpResponse.url?.absoluteString)) \n StatusCode -> \(code),Result -> \(String(describing: resultString))")
DispatchQueue.main.async {
if self.responseDataHandler != nil {
self.responseDataHandler!(data,response)
}else if self.responseStringHandler != nil {
self.responseStringHandler!(resultString ?? "",response)
}else if self.responseJSONObjectHandler != nil {
do {
let object: Any = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
self.responseJSONObjectHandler!(object,response)
} catch {
debugPrint("***ShrimpRequet-- Error -> ß\(error)")
self.errorHandler?(NSError(httpStatusCode: code,localizedDescription: "JSON serialization error"))
}
}
}
//狀態碼錯誤
// } else {
// debugPrint("***ShrimpRequest-- Request URL --> \( httpResponse.url?.absoluteString) \n data -> \(resultString) \n ErrorCode -> \(code) \n")
//
// if let msg = resultString {
// DispatchQueue.main.async {
// self.errorHandler?(ShrimpError.createError(code,localizedDescription: msg))
// }
// }else if let msg = httpResponse.allHeaderFields["Status"] as? String{
// DispatchQueue.main.async {
// self.errorHandler?(ShrimpError.createError(code,localizedDescription: msg))
// }
// }else{
// DispatchQueue.main.async {
// self.errorHandler?(ShrimpError.createError(code))
// }
// }
// }
})
if task != nil {
task!.resume()
}
}
/// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
///
/// - parameter key: The key of the query component.
/// - parameter value: The value of the query component.
///
/// - returns: The percent-escaped, URL encoded query string components.
public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: Any] {
for (nestedKey, value) in dictionary {
components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
}
} else if let array = value as? [Any] {
for value in array {
components += queryComponents(fromKey: "\(key)[]", value: value)
}
} else if let value = value as? NSNumber {
if value.isBool {
components.append((escape(key), escape((value.boolValue ? "1" : "0"))))
} else {
components.append((escape(key), escape("\(value)")))
}
} else if let bool = value as? Bool {
components.append((escape(key), escape((bool ? "1" : "0"))))
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/// Returns a percent-escaped string following RFC 3986 for a query string key or value.
///
/// RFC 3986 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
/// - parameter string: The string to be percent-escaped.
///
/// - returns: The percent-escaped string.
public func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
var escaped = ""
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//==========================================================================================================
if #available(iOS 8.3, *) {
escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
let range = startIndex..<endIndex
let substring = string.substring(with: range)
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring
index = endIndex
}
}
return escaped
}
private func query(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
}
//MARK: Utils
public enum Method: String {
case GET, POST, PUT, DELETE
}
public enum ContentType: String{
case UrlEncoded = "application/x-www-form-urlencoded; charset=utf-8"
case JSON = "application/json; charset=utf-8"
// case MultiPartFromData : "",
}
//let boundary = "Boundary+\(arc4random())\(arc4random())"
//headerDic["Content-Type"] = "multipart/form-data; boundary=\(boundary)"
//
//
//let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
//headerDic["Content-Type"] = "application/x-www-form-urlencoded; charset=\(charset)"
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (value as! String).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joined(separator: "&")
}
}
extension String{
//urlstring
/// Percent escapes values to be added to a URL query as specified in RFC 3986
///
/// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Returns percent-escaped string.
func stringByAddingPercentEncodingForURLQueryValue() -> String? {
// let allowedCharacters = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
// return self.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters)
return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
}
}
extension NSNumber {
var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
}
//extension String{
// //from wei wang
// var MD5: String {
// let cString = self.cString(using: String.Encoding.utf8)
// let length = CUnsignedInt(
// self.lengthOfBytes(using: String.Encoding.utf8)
// )
// let result = UnsafeMutablePointer<CUnsignedChar>.allocate(
// capacity: Int(CC_MD5_DIGEST_LENGTH)
// )
//
// CC_MD5(cString!, length, result)
//
// return String(format:
// "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
// result[0], result[1], result[2], result[3],
// result[4], result[5], result[6], result[7],
// result[8], result[9], result[10], result[11],
// result[12], result[13], result[14], result[15])
// }
//
// func md5() -> String {
//
// let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1)
// var digest = Array<UInt8>(repeating:0, count:Int(CC_MD5_DIGEST_LENGTH))
// CC_MD5_Init(context)
// CC_MD5_Update(context, self, CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8)))
// CC_MD5_Final(&digest, context)
// context.deallocate(capacity: 1)
// var hexString = ""
// for byte in digest {
// hexString += String(format:"%02x", byte)
// }
//
// return hexString
// }
//
//}
|
mit
|
afeaca3509f7617e4757dc8194e375cb
| 36.602851 | 192 | 0.548232 | 5.242192 | false | false | false | false |
makma/cloud-sdk-swift
|
Example/Tests/DeliveryService/DeliveryClient/GetItemsPreview.swift
|
1
|
5356
|
//
// GetItemsPreview.swift
// KenticoCloud
//
// Created by Martin Makarsky on 21/09/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import KenticoCloud
class GetItemsPreviewSpec: QuickSpec {
override func spec() {
describe("Get preview items request") {
let client = DeliveryClient.init(projectId: TestConstants.projectId, previewApiKey: TestConstants.previewApiKey)
//MARK: Custom Model mapping
context("using query parameter objects and custom model mapping", {
it("returns array of items") {
let contentTypeParameter = QueryParameter.init(parameterKey: QueryParameterKey.type, parameterValue: "cafe")
waitUntil(timeout: 5) { done in
client.getItems(modelType: CafeTestModel.self, queryParameters: [contentTypeParameter], completionHandler: { (isSuccess, deliveryItems, error) in
if !isSuccess {
fail("Response is not successful. Error: \(String(describing: error))")
}
if let items = deliveryItems?.items {
let itemsCount = items.count
let expectedCount = 10
expect(itemsCount) == expectedCount
done()
}
})
}
}
})
context("using custom query and custom model mapping", {
it("returns array of items") {
let customQuery = "items?system.type=cafe&order=elements.country[desc]&limit=3"
waitUntil(timeout: 5) { done in
client.getItems(modelType: CafeTestModel.self, customQuery: customQuery, completionHandler: { (isSuccess, deliveryItems, error) in
if !isSuccess {
fail("Response is not successful. Error: \(String(describing: error))")
}
if let items = deliveryItems?.items {
let itemsCount = items.count
let expectedCount = 3
expect(itemsCount) == expectedCount
done()
}
})
}
}
})
//MARK: Auto mapping using Delivery element types
context("using query parameter objects and Delivery element types", {
it("returns array of items") {
let contentTypeParameter = QueryParameter.init(parameterKey: QueryParameterKey.type, parameterValue: "cafe")
let languageParameter = QueryParameter.init(parameterKey: QueryParameterKey.language, parameterValue: "es-ES")
let parameters = [contentTypeParameter, languageParameter]
waitUntil(timeout: 5) { done in
client.getItems(modelType: ArticleTestModel.self, queryParameters: parameters, completionHandler: { (isSuccess, deliveryItems, error) in
if !isSuccess {
fail("Response is not successful. Error: \(String(describing: error))")
}
if let items = deliveryItems?.items {
let itemsCount = items.count
let expectedCount = 10
expect(itemsCount) == expectedCount
done()
}
})
}
}
})
context("using custom query and Delivery element types", {
it("returns array of items") {
let customQuery = "items?system.type=article&order=elements.title[desc]&limit=4"
waitUntil(timeout: 5) { done in
client.getItems(modelType: ArticleTestModel.self, customQuery: customQuery, completionHandler: { (isSuccess, deliveryItems, error) in
if !isSuccess {
fail("Response is not successful. Error: \(String(describing: error))")
}
if let items = deliveryItems?.items {
let itemsCount = items.count
let expectedCount = 4
expect(itemsCount) == expectedCount
done()
}
})
}
}
})
}
}
}
|
mit
|
265d0fbfe40e140cce07cbf430a4f811
| 43.256198 | 169 | 0.434921 | 6.856594 | false | false | false | false |
pennlabs/penn-mobile-ios
|
PennMobile/Home/Map/PennCoordinate.swift
|
1
|
4660
|
//
// PennCoordinates.swift
// PennMobile
//
// Created by Dominic Holmes on 8/3/18.
// Copyright © 2018 PennLabs. All rights reserved.
//
import Foundation
import MapKit
enum PennCoordinateScale: Double {
case close = 150.0
case mid = 300.0
case far = 1000.0
}
// MARK: - Coordinates and Regions
class PennCoordinate {
static let shared = PennCoordinate()
internal let collegeHall: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 39.9522, longitude: -75.1932)
func getDefault() -> CLLocationCoordinate2D {
return collegeHall
}
func getDefaultRegion(at scale: PennCoordinateScale) -> MKCoordinateRegion {
return MKCoordinateRegion.init(center: getDefault(), latitudinalMeters: scale.rawValue, longitudinalMeters: scale.rawValue)
}
func getCoordinates(for facility: FitnessFacilityName) -> CLLocationCoordinate2D {
switch facility {
case .pottruck: return CLLocationCoordinate2D(latitude: 39.953562, longitude: -75.197002)
case .fox: return CLLocationCoordinate2D(latitude: 39.950343, longitude: -75.189154)
case .climbing: return CLLocationCoordinate2D(latitude: 39.954034, longitude: -75.196960)
case .membership: return CLLocationCoordinate2D(latitude: 39.954057, longitude: -75.197188)
case .ringe: return CLLocationCoordinate2D(latitude: 39.950450, longitude: -75.188642)
case .rockwell: return CLLocationCoordinate2D(latitude: 39.953859, longitude: -75.196868)
case .sheerr: return CLLocationCoordinate2D(latitude: 39.953859, longitude: -75.196868)
case .unknown: return getDefault()
}
}
func getRegion(for facility: FitnessFacilityName, at scale: PennCoordinateScale) -> MKCoordinateRegion {
return MKCoordinateRegion.init(center: getCoordinates(for: facility), latitudinalMeters: scale.rawValue, longitudinalMeters: scale.rawValue)
}
func getCoordinates(for dining: DiningVenue) -> CLLocationCoordinate2D {
switch dining.id {
case 593:
// 1920 Commons
return CLLocationCoordinate2D(latitude: 39.952275, longitude: -75.199560)
case 636:
// Hill House
return CLLocationCoordinate2D(latitude: 39.953040, longitude: -75.190589)
case 637:
// English House
return CLLocationCoordinate2D(latitude: 39.954242, longitude: -75.194351)
case 638:
// Falk Kosher Dining
return CLLocationCoordinate2D(latitude: 39.953117, longitude: -75.200075)
case 639:
// Houston Market
return CLLocationCoordinate2D(latitude: 39.950920, longitude: -75.193892)
case 641:
// "Accenture Caf\u00e9"
return CLLocationCoordinate2D(latitude: 39.951827, longitude: -75.191315)
case 642:
// "Joe's Caf\u00e9"
return CLLocationCoordinate2D(latitude: 39.951818, longitude: -75.196089)
case 1442:
// "Lauder College House"
return CLLocationCoordinate2D(latitude: 39.953907, longitude: -75.191733)
case 747:
// "McClelland Express"
return CLLocationCoordinate2D(latitude: 39.950378, longitude: -75.197151)
case 1057:
// "1920 Gourmet Grocer"
return CLLocationCoordinate2D(latitude: 39.952115, longitude: -75.199492)
case 1163:
// "1920 Starbucks"
return CLLocationCoordinate2D(latitude: 39.952361, longitude: -75.199466)
case 1731:
// "LCH Retail"
return CLLocationCoordinate2D(latitude: 39.953907, longitude: -75.191733)
case 1732:
// Pret a Manger MBA
return CLLocationCoordinate2D(latitude: 39.952591, longitude: -75.198326)
default:
// case 1733:
// "Pret a Manger Locust Walk",
return CLLocationCoordinate2D(latitude: 39.952591, longitude: -75.198326)
}
}
func getRegion(for dining: DiningVenue, at scale: PennCoordinateScale) -> MKCoordinateRegion {
return MKCoordinateRegion.init(center: getCoordinates(for: dining), latitudinalMeters: scale.rawValue, longitudinalMeters: scale.rawValue)
}
}
// MARK: - Placemarks
extension PennCoordinate {
func getAnnotation(for facility: FitnessFacilityName) -> MKAnnotation {
let annotation = MKPointAnnotation()
annotation.coordinate = getCoordinates(for: facility)
annotation.title = facility.getFacilityName()
annotation.subtitle = "Penn Recreation"
return annotation
}
}
|
mit
|
e27133275668149a1769964c11003256
| 40.598214 | 148 | 0.663232 | 4.174731 | false | false | false | false |
niekang/NKDownload
|
NKDownload/DownloadCell.swift
|
1
|
3157
|
//
// DownloadCell.swift
// NKDownload
//
// Created by 聂康 on 2017/5/15.
// Copyright © 2017年 聂康. All rights reserved.
//
import UIKit
class DownloadObject: NSObject {
var urlString:String?
var currentSize:Int64 = 0
var totalSize:Int64 = 0
var state:NKDownloadState = .waiting
}
class DownloadCell: UITableViewCell {
lazy var downloadObject = DownloadObject()
@IBOutlet weak var urlLab: UILabel!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var lengthLab: UILabel!
@IBOutlet weak var speedLab: UILabel!
@IBOutlet weak var downloadBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
speedLab.isHidden = true
}
func disPlayCell(object:DownloadObject){
downloadObject = object
let progress = (downloadObject.totalSize == 0) ? 0 : (Float(downloadObject.currentSize)/Float(downloadObject.totalSize))
let currentSize = Float(downloadObject.currentSize)/1024
var currentSizeString = ""
if currentSize > 1024 {
currentSizeString = String(format: "%.2fMB", currentSize/1024) + "/" + String(format:"%.2fMB", Float(downloadObject.totalSize)/1024/1024)
}else{
currentSizeString = String(format: "%.2fKB", currentSize) + "/" + String(format:"%.2fMB", Float(downloadObject.totalSize)/1024/1024)
}
urlLab.text = object.urlString
progressView.progress = progress
lengthLab.text = currentSizeString
switch downloadObject.state {
case .waiting:
downloadBtn.setTitle("等待", for: .normal)
case .downloading:
downloadBtn.setTitle("下载中", for: .normal)
case .suspend:
downloadBtn.setTitle("暂停", for: .normal)
case .success:
downloadBtn.setTitle("完成", for: .normal)
case .fail:
downloadBtn.setTitle("下载失败", for: .normal)
}
}
@IBAction func downloadButtonClick(_ sender: Any) {
switch downloadObject.state {
case .waiting:
downloadObject.state = .suspend
downloadBtn.setTitle("暂停", for: .normal)
NKDownloadManger.shared.nk_suspendWaitingDownloadTaskWithURLString(urlString: urlLab.text!)
case .downloading:
downloadObject.state = .suspend
downloadBtn.setTitle("暂停", for: .normal)
NKDownloadManger.shared.nk_suspendCurrentDownloadTaskWithURLString(urlString: urlLab.text!)
case .suspend:
downloadObject.state = .waiting
downloadBtn.setTitle("等待", for: .normal)
NKDownloadManger.shared.nk_recoverDwonloadTaskWithURLString(urlString: urlLab.text!)
case .success:
break
case .fail:
downloadObject.state = .waiting
NKDownloadManger.shared.nk_recoverDwonloadTaskWithURLString(urlString: urlLab.text!)
downloadBtn.setTitle("等待", for: .normal)
}
}
}
|
apache-2.0
|
abcc5a4a179d8a0995d596a027ceb148
| 31.673684 | 149 | 0.615657 | 4.50508 | false | false | false | false |
PekanMmd/Pokemon-XD-Code
|
GoDToolOSX/View Controllers/UniversalEditorViewController.swift
|
1
|
4415
|
//
// UniversalEditorViewController.swift
// GoD Tool
//
// Created by Stars Momodu on 19/03/2021.
//
import Cocoa
class UniversalEditorViewController: GoDTableViewController {
@IBOutlet weak var tableNameLabel: NSTextField!
@IBOutlet weak var decodeButton: GoDButton!
@IBOutlet weak var encodeButton: GoDButton!
@IBOutlet weak var documentButton: GoDButton!
@IBOutlet weak var editButton: GoDButton!
@IBOutlet weak var detailsLabel: NSTextField!
private var lastSearchText: String?
private var filteredValues = [TableTypes]()
private var currentTable: TableTypes? {
didSet {
[decodeButton, encodeButton, documentButton].forEach { (button) in
button?.isEnabled = currentTable != nil
}
tableNameLabel.stringValue = currentTable?.name ?? "Data Table"
detailsLabel.stringValue = "Details: -"
if case .structTable(let table, _) = currentTable {
detailsLabel.stringValue =
"""
Details:
File: \(table.file.path)
Start Offset: \(table.firstEntryStartOffset.hexString()) (\(table.firstEntryStartOffset))
Number of Entries: \(table.numberOfEntries.hexString()) (\(table.numberOfEntries))
Entry Length: \(table.entryLength.hexString()) (\(table.entryLength))
"""
}
if case .codableData(let type) = currentTable {
detailsLabel.stringValue =
"""
Details:
Number of Entries: \(type.numberOfValues.hexString()) (\(type.numberOfValues))
"""
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
filteredValues = TableTypes.allTables
table.reloadData()
}
@IBAction func didClickEncodeButton(_ sender: Any) {
guard let tableInfo = currentTable else { return }
switch tableInfo {
case .structTable(let table, _): table.encodeCSVData()
case .codableData(let type): type.encodeData()
}
displayAlert(title: "Done", description: "Finished Encoding")
}
@IBAction func didClickDecodeButton(_ sender: Any) {
guard let tableInfo = currentTable else { return }
switch tableInfo {
#if !GAME_PBR
case .structTable(let table, type: .saveData):
table.decodeCSVData()
if let saveData = table.file.data {
let gciFile = XGFiles.nameAndFolder(saveData.file.fileName.replacingOccurrences(of: ".raw", with: ""), saveData.file.folder)
if gciFile.exists {
XGSaveManager(file: gciFile, saveType: .gciSaveData).save()
}
}
#endif
case .structTable(let table, _): table.decodeCSVData()
case .codableData(let type): type.decodeData()
}
displayAlert(title: "Done", description: "Finished Decoding")
}
@IBAction func didClickDocumentButton(_ sender: Any) {
guard let tableInfo = currentTable else { return }
switch tableInfo {
case .structTable(let table, _): table.documentCStruct(); table.documentEnumerationData(); table.documentData()
case .codableData(let type): type.documentData(); type.documentEnumerationData()
}
displayAlert(title: "Done", description: "Finished Documenting")
}
@IBAction func didClickEditButton(_ sender: Any) {
}
override func numberOfRows(in tableView: NSTableView) -> Int {
return filteredValues.count
}
override func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 50
}
override func searchBarBehaviourForTableView(_ tableView: GoDTableView) -> GoDSearchBarBehaviour {
.onTextChange
}
override func tableView(_ tableView: GoDTableView, didSelectRow row: Int) {
super.tableView(tableView, didSelectRow: row)
if row >= 0 {
currentTable = filteredValues[row]
}
}
override func tableView(_ tableView: GoDTableView, didSearchForText text: String) {
defer {
tableView.reloadData()
}
guard !text.isEmpty else {
lastSearchText = nil
filteredValues = TableTypes.allTables
return
}
lastSearchText = text
filteredValues = TableTypes.allTables.filter({ (tableInfo) -> Bool in
return tableInfo.name.simplified.contains(text.simplified)
})
}
override func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let tableInfo = filteredValues[row]
let cell = super.tableView(tableView, viewFor: tableColumn, row: row)
guard let view = cell as? GoDTableCellView else {
assertionFailure("GoDTableViewController didn't return GoDTableCellView")
return cell
}
view.setBackgroundColour(tableInfo.colour)
view.setTitle(tableInfo.name)
view.titleField.maximumNumberOfLines = 0
return view
}
}
|
gpl-2.0
|
096a34f856f043c6d521694b5086f5eb
| 29.034014 | 128 | 0.724122 | 3.741525 | false | false | false | false |
huonw/swift
|
stdlib/public/core/ThreadLocalStorage.swift
|
1
|
5595
|
//===--- ThreadLocalStorage.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
//
//===----------------------------------------------------------------------===//
import SwiftShims
// For testing purposes, a thread-safe counter to guarantee that destructors get
// called by pthread.
#if INTERNAL_CHECKS_ENABLED
public // @testable
let _destroyTLSCounter = _stdlib_AtomicInt()
#endif
// Thread local storage for all of the Swift standard library
//
// @moveonly/@pointeronly: shouldn't be used as a value, only through its
// pointer. Similarly, shouldn't be created, except by
// _initializeThreadLocalStorage.
//
@usableFromInline // FIXME(sil-serialize-all)
@_fixed_layout // FIXME(sil-serialize-all)
internal struct _ThreadLocalStorage {
// TODO: might be best to absract uBreakIterator handling and caching into
// separate struct. That would also make it easier to maintain multiple ones
// and other TLS entries side-by-side.
// Save a pre-allocated UBreakIterator, as they are very expensive to set up.
// Each thread can reuse their unique break iterator, being careful to reset
// the text when it has changed (see below). Even with a naive always-reset
// policy, grapheme breaking is 30x faster when using a pre-allocated
// UBreakIterator than recreating one.
//
// private
@usableFromInline // FIXME(sil-serialize-all)
internal var uBreakIterator: OpaquePointer
// TODO: Consider saving two, e.g. for character-by-character comparison
// The below cache key tries to avoid resetting uBreakIterator's text when
// operating on the same String as before. Avoiding the reset gives a 50%
// speedup on grapheme breaking.
//
// As a invalidation check, save the base address from the last used
// StringCore. We can skip resetting the uBreakIterator's text when operating
// on a given StringCore when both of these associated references/pointers are
// equal to the StringCore's. Note that the owner is weak, to force it to
// compare unequal if a new StringCore happens to be created in the same
// memory.
//
// TODO: unowned reference to string owner, base address, and _countAndFlags
// private: Should only be called by _initializeThreadLocalStorage
@inlinable // FIXME(sil-serialize-all)
internal init(_uBreakIterator: OpaquePointer) {
self.uBreakIterator = _uBreakIterator
}
// Get the current thread's TLS pointer. On first call for a given thread,
// creates and initializes a new one.
@inlinable // FIXME(sil-serialize-all)
internal static func getPointer()
-> UnsafeMutablePointer<_ThreadLocalStorage>
{
let tlsRawPtr = _stdlib_thread_getspecific(_tlsKey)
if _fastPath(tlsRawPtr != nil) {
return tlsRawPtr._unsafelyUnwrappedUnchecked.assumingMemoryBound(
to: _ThreadLocalStorage.self)
}
return _initializeThreadLocalStorage()
}
@inlinable // FIXME(sil-serialize-all)
internal static func getUBreakIterator(
start: UnsafePointer<UTF16.CodeUnit>,
count: Int32
) -> OpaquePointer {
let tlsPtr = getPointer()
let brkIter = tlsPtr[0].uBreakIterator
var err = __swift_stdlib_U_ZERO_ERROR
__swift_stdlib_ubrk_setText(brkIter, start, count, &err)
_precondition(err.isSuccess, "Unexpected ubrk_setUText failure")
return brkIter
}
}
// Destructor to register with pthreads. Responsible for deallocating any memory
// owned.
@usableFromInline // FIXME(sil-serialize-all)
@_silgen_name("_stdlib_destroyTLS")
internal func _destroyTLS(_ ptr: UnsafeMutableRawPointer?) {
_sanityCheck(ptr != nil,
"_destroyTLS was called, but with nil...")
let tlsPtr = ptr!.assumingMemoryBound(to: _ThreadLocalStorage.self)
__swift_stdlib_ubrk_close(tlsPtr[0].uBreakIterator)
tlsPtr.deinitialize(count: 1)
tlsPtr.deallocate()
#if INTERNAL_CHECKS_ENABLED
// Log the fact we've destroyed our storage
_destroyTLSCounter.fetchAndAdd(1)
#endif
}
// Lazily created global key for use with pthread TLS
@usableFromInline // FIXME(sil-serialize-all)
internal let _tlsKey: __swift_thread_key_t = {
let sentinelValue = __swift_thread_key_t.max
var key: __swift_thread_key_t = sentinelValue
let success = _stdlib_thread_key_create(&key, _destroyTLS)
_sanityCheck(success == 0, "somehow failed to create TLS key")
_sanityCheck(key != sentinelValue, "Didn't make a new key")
return key
}()
@inline(never)
@usableFromInline
internal func _initializeThreadLocalStorage()
-> UnsafeMutablePointer<_ThreadLocalStorage>
{
_sanityCheck(_stdlib_thread_getspecific(_tlsKey) == nil,
"already initialized")
// Create and initialize one.
var err = __swift_stdlib_U_ZERO_ERROR
let newUBreakIterator = __swift_stdlib_ubrk_open(
/*type:*/ __swift_stdlib_UBRK_CHARACTER, /*locale:*/ nil,
/*text:*/ nil, /*textLength:*/ 0, /*status:*/ &err)
_precondition(err.isSuccess, "Unexpected ubrk_open failure")
let tlsPtr: UnsafeMutablePointer<_ThreadLocalStorage>
= UnsafeMutablePointer<_ThreadLocalStorage>.allocate(
capacity: 1
)
tlsPtr.initialize(
to: _ThreadLocalStorage(_uBreakIterator: newUBreakIterator)
)
let success = _stdlib_thread_setspecific(_tlsKey, tlsPtr)
_sanityCheck(success == 0, "setspecific failed")
return tlsPtr
}
|
apache-2.0
|
dd3ddf37e2f9190dd50df13545be35dd
| 36.05298 | 80 | 0.715282 | 4.116998 | false | false | false | false |
myoungsc/SCWebPreview
|
SCWebPreview/Classes/SCWebPreview.swift
|
1
|
4893
|
//
// SCWebPreview.swift
// SCWebPreview
//
// Created by myoungsc on 2017. 8. 22..
// Copyright © 2017년 myoungsc. All rights reserved.
//
import UIKit
@IBDesignable public class SCWebPreview {
var webPages: [String] = []
var previewDatas: [Int: [String: String]] = [:]
/**
initializer webPages
*/
public func initWebPages(_ arr: [String]) {
webPages = arr
}
//MARK: ## public Function ##
/**
start crawling for Web Preview
*/
public func startCrawling(completionHandler: @escaping () -> Void) {
print("start crawling")
for (index, content) in self.webPages.enumerated() {
DispatchQueue.global().async {
self.urlFromCheck(content, completionHandler: { webPage in
guard let url = URL(string: webPage) else {
print("error: url is option value")
return
}
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: { (data, response, error) in
if error == nil {
let dic: [String: String] = self.htmlParser(data!, strUrl: content)
self.previewDatas[index] = dic
if self.previewDatas.count == self.webPages.count {
DispatchQueue.main.async {
print("finish crawling")
completionHandler()
}
}
} else {
print(error?.localizedDescription as Any)
}
})
task.resume()
})
}
}
}
/**
return preview data
*/
public func getPreviewDataFromIndex(_ index: Int) -> [String: String] {
guard previewDatas.count > index else {
print("error: receive index exceeded the limit")
return [:]
}
return previewDatas[index]!
}
/**
method - open safari
*/
public func openSafariFromUrl(_ index: Int) {
let dic = getPreviewDataFromIndex(index)
guard let strUrl: String = dic["og:url"] else {
print("error: og:url is optionl Value")
return
}
if let url = URL(string: strUrl) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:]) { (result) in }
} else {
UIApplication.shared.openURL(url)
}
}
}
//MARK: ## private Function ##
/**
arrangement og: data in html
*/
private func htmlParser(_ data: Data, strUrl: String) -> [String: String] {
var dic: [String: String] = [:]
let urlContent = String(data: data, encoding: String.Encoding.utf8)
let htmlTag = urlContent?.replacingOccurrences(of: "\n", with: "")
let arr = htmlTag?.components(separatedBy: "<meta")
func arrangement() {
for i in 1 ..< (arr?.count)! {
guard let content: String = arr?[i] else {
return
}
if content.contains("og:title") || content.contains("og:url")
|| content.contains("og:description") || content.contains("og:image") {
let arrContents = content.components(separatedBy: "\"")
var key: String = "", content: String = ""
for (index, value) in arrContents.enumerated() {
if value.contains("property=") {
let tempKey = arrContents[index+1]
key = tempKey.trimmingCharacters(in: .whitespaces)
} else if value.contains("content=") {
content = arrContents[index+1]
}
}
dic[key] = content
}
}
}
arrangement()
guard let _: String = dic["og:url"] else {
dic["og:url"] = strUrl
return dic
}
return dic
}
/**
url from check and edit
*/
private func urlFromCheck(_ strUrl: String, completionHandler: @escaping (_ result: String) -> Void) {
var webPage = strUrl
guard webPage.hasPrefix("https") || webPage.hasPrefix("http") else {
webPage = "https://" + webPage
completionHandler(webPage)
return
}
completionHandler(webPage)
}
}
|
mit
|
5f2af6c9a1c7dfc9f6d63dd32ae8e94c
| 32.265306 | 106 | 0.462577 | 5.141956 | false | false | false | false |
3DprintFIT/octoprint-ios-client
|
OctoPhone/Networking/DynamicProvider.swift
|
1
|
3438
|
//
// DynamicProvider.swift
// OctoPhone
//
// Created by Josef Dolezal on 27/02/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import Foundation
import Moya
import ReactiveSwift
import ReactiveMoya
/// Defines properties required by Target,
/// but does not require base URL as it's
/// added dynamically
protocol TargetPart {
/// The path to be appended to `baseURL` to form the full `URL`.
var path: String { get }
/// The HTTP method used in the request.
var method: Moya.Method { get }
/// The parameters to be incoded in the request.
var parameters: [String: Any]? { get }
/// The method used for parameter encoding.
var parameterEncoding: ParameterEncoding { get }
/// Provides stub data for use in testing.
var sampleData: Data { get }
/// The type of HTTP task to be performed.
var task: Task { get }
/// Whether or not to perform Alamofire validation. Defaults to `false`.
var validate: Bool { get }
}
/// Layer between actual requests provider and target type,
/// allows to use dynamic base URL created during run time
struct DynamicTarget: TargetType {
let baseURL: URL
let target: TargetPart
var path: String { return target.path }
var method: Moya.Method { return target.method }
var parameters: [String : Any]? { return target.parameters }
var parameterEncoding: ParameterEncoding { return target.parameterEncoding }
var sampleData: Data { return target.sampleData }
var task: Task { return target.task }
var validate: Bool { return target.validate }
init(baseURL: URL, target: TargetPart) {
self.baseURL = baseURL
self.target = target
}
}
/// Requests provider allowing to pass base URL during run time
final class DynamicProvider<Target: TargetPart>: ReactiveSwiftMoyaProvider<DynamicTarget> {
/// Request base URL
let baseURL: URL
init(
baseURL: URL,
endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping,
requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping,
stubClosure: @escaping StubClosure = MoyaProvider.neverStub,
manager: Manager = ReactiveSwiftMoyaProvider<DynamicTarget>.defaultAlamofireManager(),
plugins: [PluginType] = [], stubScheduler: DateScheduler? = nil,
trackInflights: Bool = false
) {
self.baseURL = baseURL
super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure:
stubClosure, manager: manager, plugins: plugins, trackInflights: trackInflights)
}
/// Creates request from TargetPart
///
/// - Parameter target: Target without base URL
/// - Returns: Response signal
func request(_ target: Target) -> SignalProducer<Response, MoyaError> {
let dynamicTarget = DynamicTarget(baseURL: baseURL, target: target)
return request(dynamicTarget)
}
/// Creates actual request from TargetPart, the request can be observed for progress
///
/// - Parameter target: Request Target without base URL
/// - Returns: Response producer which can be observed for progress
func requestWithProgress(_ target: Target) -> SignalProducer<ProgressResponse, MoyaError> {
let dynamicTarget = DynamicTarget(baseURL: baseURL, target: target)
return requestWithProgress(token: dynamicTarget)
}
}
|
mit
|
6750754e9655d860e9a8a37a9a05fae5
| 31.424528 | 97 | 0.695374 | 4.868272 | false | false | false | false |
ripventura/VCHTTPConnect
|
Example/Pods/EFQRCode/Source/QRMath.swift
|
2
|
2429
|
//
// QRMath.swift
// EFQRCode
//
// Created by Apollo Zhu on 12/27/17.
//
// Copyright (c) 2017 EyreFree <[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(iOS) || os(tvOS) || os(macOS)
#else
struct QRMath {
/// glog
///
/// - Parameter n: n | n >= 1.
/// - Returns: glog(n), or a fatal error if n < 1.
static func glog(_ n: Int) -> Int {
precondition(n > 0, "glog only works with n > 0, not \(n)")
return QRMath.instance.LOG_TABLE[n]
}
static func gexp(_ n: Int) -> Int {
var n = n
while n < 0 { n += 255 }
while (n >= 256) { n -= 255 }
return QRMath.instance.EXP_TABLE[n]
}
private var EXP_TABLE: [Int]
private var LOG_TABLE: [Int]
private static let instance = QRMath()
private init() {
EXP_TABLE = [Int](repeating: 0, count: 256)
LOG_TABLE = [Int](repeating: 0, count: 256)
for i in 0..<8 {
EXP_TABLE[i] = 1 << i
}
for i in 8..<256 {
EXP_TABLE[i] = EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8]
}
for i in 0..<255 {
LOG_TABLE[EXP_TABLE[i]] = i
}
}
}
#endif
|
mit
|
67452126709acc429e77e6643220f416
| 36.369231 | 104 | 0.581309 | 3.855556 | false | false | false | false |
skylib/SnapOnboarding-iOS
|
SnapOnboarding-iOS/Snapshot_tests/IntroViewControllerSnapshots.swift
|
2
|
1284
|
import SnapFBSnapshotBase
@testable import SnapOnboarding_iOS
class IntroViewControllerSnapshots: SnapFBSnapshotBase {
override func setUp() {
let vc = getSnapOnboardingViewController()
let delegate = mockSnapOnboardingDelegate()
let configuration = SnapOnboardingConfiguration(delegate: delegate, viewModel: viewModel)
vc.applyConfiguration(configuration)
sutBackingViewController = vc
sut = vc.view
// vc.viewWillAppear(false)
UIApplication.shared.keyWindow?.rootViewController = vc
UIApplication.shared.keyWindow?.rootViewController = nil
// Setup the loaded view
currentPage = 0
super.setUp()
recordMode = recordAll || false
}
override func tearDown() {
super.tearDown()
}
}
extension IntroViewController {
override func viewWillLayoutSubviews() {
setupForScreenSize(parent!.view.frame.size)
}
}
extension TagsCollectionViewController {
override func viewWillLayoutSubviews() {
setupForScreenSize(parent!.parent!.view.frame.size)
configuration = createConfiguration()
buttonConfiguration = createButtonConfiguration()
}
}
|
bsd-3-clause
|
a967c550722fb4dab96601fe7861b8ee
| 25.204082 | 97 | 0.6581 | 5.757848 | false | true | false | false |
wikimedia/apps-ios-wikipedia
|
Wikipedia/Code/SizeThatFitsReusableView.swift
|
1
|
4421
|
import UIKit
// This is largely identical to CollectionViewCell. They both could be refactored to be
// wrappers around a SizeThatFitsView that determines cell & header/footer size.
class SizeThatFitsReusableView: UICollectionReusableView {
// Subclassers should override setup instead of any of the initializers. Subclassers must call super.setup()
open func setup() {
translatesAutoresizingMaskIntoConstraints = false
preservesSuperviewLayoutMargins = false
insetsLayoutMarginsFromSafeArea = false
autoresizesSubviews = false
reset()
setNeedsLayout()
}
open func reset() {
}
// Subclassers should call super
open func updateBackgroundColorOfLabels() {
}
// Subclassers should override sizeThatFits:apply: instead of layoutSubviews to lay out subviews.
// In this method, subclassers should calculate the appropriate layout size and if apply is `true`,
// apply the layout to the subviews.
open func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
return size
}
// Subclassers should override updateAccessibilityElements to update any accessibility elements
// that should be updated after layout. Subclassers must call super.updateAccessibilityElements()
open func updateAccessibilityElements() {
}
// MARK - Initializers
// Don't override these initializers, use setup() instead
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK - Cell lifecycle
open override func prepareForReuse() {
super.prepareForReuse()
reset()
}
// MARK - Layout
final override public func layoutSubviews() {
super.layoutSubviews()
let size = bounds.size
let _ = sizeThatFits(size, apply: true)
updateAccessibilityElements()
#if DEBUG
for view in subviews {
assert(view.autoresizingMask == [])
assert(view.constraints == [])
}
#endif
}
final override public func sizeThatFits(_ size: CGSize) -> CGSize {
return sizeThatFits(size, apply: false)
}
final override public func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
if let attributesToFit = layoutAttributes as? ColumnarCollectionViewLayoutAttributes {
layoutMargins = attributesToFit.layoutMargins
if attributesToFit.precalculated {
return attributesToFit
}
}
var sizeToFit = layoutAttributes.size
sizeToFit.height = UIView.noIntrinsicMetric
var fitSize = self.sizeThatFits(sizeToFit)
if fitSize == sizeToFit {
return layoutAttributes
} else if let attributes = layoutAttributes.copy() as? UICollectionViewLayoutAttributes {
fitSize.width = sizeToFit.width
if fitSize.height == CGFloat.greatestFiniteMagnitude || fitSize.height == UIView.noIntrinsicMetric {
fitSize.height = layoutAttributes.size.height
}
attributes.frame = CGRect(origin: layoutAttributes.frame.origin, size: fitSize)
return attributes
} else {
return layoutAttributes
}
}
// MARK - Dynamic Type
// Only applies new fonts if the content size category changes
override open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
maybeUpdateFonts(with: traitCollection)
}
var contentSizeCategory: UIContentSizeCategory?
fileprivate func maybeUpdateFonts(with traitCollection: UITraitCollection) {
guard contentSizeCategory == nil || contentSizeCategory != traitCollection.wmf_preferredContentSizeCategory else {
return
}
contentSizeCategory = traitCollection.wmf_preferredContentSizeCategory
updateFonts(with: traitCollection)
}
// Override this method and call super
open func updateFonts(with traitCollection: UITraitCollection) {
}
}
|
mit
|
084c1d9189c893ccb1501ab379f380d7
| 34.653226 | 155 | 0.661615 | 6.183217 | false | false | false | false |
AaronBratcher/ALBNoSQLDB
|
SwiftUI App/SwiftUI App/Foundation Extensions/DateExtensions.swift
|
1
|
4275
|
//
// NSDateExtensions.swift
// Money Trak
//
// Created by Aaron Bratcher on 3/26/16.
// Copyright © 2016 Aaron L. Bratcher. All rights reserved.
//
import Foundation
var dateFormatter: DateFormatter = {
let format = DateFormatter.dateFormat(fromTemplate: "MMM d yyyy", options: 0, locale: NSLocale.current)
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter
}()
let dayFormatter: DateFormatter = {
let format = DateFormatter.dateFormat(fromTemplate: "MMM d", options: 0, locale: NSLocale.current)
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter
}()
let monthFormatter: DateFormatter = {
let format = DateFormatter.dateFormat(fromTemplate: "MMM yyyy", options: 0, locale: NSLocale.current)
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter
}()
let yearFormatter: DateFormatter = {
let format = DateFormatter.dateFormat(fromTemplate: "yyyy", options: 0, locale: NSLocale.current)
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter
}()
let mediumDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.medium
return formatter
}()
let fullDateFormatter: DateFormatter = {
let _dateFormatter = DateFormatter()
_dateFormatter.calendar = Calendar(identifier: .gregorian)
_dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'.'SSSZZZZZ"
return _dateFormatter
}()
func gregorianMonthForDate(_ monthDate: Date) -> (start: Date, end: Date) {
let calendar = Calendar.current
let year = calendar.component(.year, from: monthDate)
let month = calendar.component(.month, from: monthDate)
var components = DateComponents()
components.year = year
components.month = month
components.day = 1
let start = calendar.date(from: components)!
let days = calendar.range(of: Calendar.Component.day, in: Calendar.Component.month, for: start)!
var end = calendar.date(byAdding: DateComponents(day: days.count), to: start)!
end = calendar.date(byAdding: DateComponents(second: -1), to: end)!
return (start, end)
}
extension Date {
func stringValue() -> String {
let strDate = fullDateFormatter.string(from: self)
return strDate
}
func mediumDateString() -> String {
mediumDateFormatter.doesRelativeDateFormatting = false
let strDate = mediumDateFormatter.string(from: self)
return strDate
}
func relativeDateString() -> String {
mediumDateFormatter.doesRelativeDateFormatting = true
let strDate = mediumDateFormatter.string(from: self)
return strDate
}
func relativeTimeFrom(_ date: Date) -> String {
let interval = abs(self.timeIntervalSince(date))
if interval < 60 {
return "less than a minute ago"
}
if interval < 3600 {
return "\(floor(interval / 60)) minutes ago"
}
return "\(floor(interval / 60 / 60)) hours ago"
}
func addDate(years: Int, months: Int, weeks: Int, days: Int) -> Date {
let calendar = Calendar.current
var components = DateComponents()
components.year = years
components.month = months
components.weekOfYear = weeks
components.day = days
let nextDate = calendar.date(byAdding: components, to: self)
return nextDate!
}
func addTime(hours: Int, minutes: Int, seconds: Int) -> Date {
let calendar = Calendar.current
var components = DateComponents()
components.hour = hours
components.minute = minutes
components.second = seconds
let nextDate = calendar.date(byAdding: components, to: self)
return nextDate!
}
func midnight() -> Date {
let calendar = Calendar.current
let year = calendar.component(.year, from: self)
let month = calendar.component(.month, from: self)
let day = calendar.component(.day, from: self)
var components = DateComponents()
components.year = year
components.month = month
components.day = day
let midnight = calendar.date(from: components)!
return midnight
}
func calendarYear() -> Int {
let calendar = Calendar.current
let year = calendar.component(.year, from: self)
return year
}
func monthKey() -> String {
let calendar = NSCalendar.current
let year = calendar.component(.year, from: self)
let month = calendar.component(.month, from: self)
let monthKey = "\(year)_\(month)"
return monthKey
}
}
|
mit
|
1a6323b01dba6de50a1334f887c98f45
| 25.382716 | 104 | 0.726486 | 3.749123 | false | false | false | false |
liuduoios/HLDBadgeControls
|
HLDBadgeControls/UITableViewCell+Badge.swift
|
1
|
1369
|
//
// UITableViewCell+Badge.swift
// HLDBadgeControlsDemo
//
// Created by 刘铎 on 15/9/9.
// Copyright © 2015年 Derek Liu. All rights reserved.
//
import UIKit
import ObjectiveC
private var cellBadgeViewAssociationKey: UInt8 = 0
extension UITableViewCell {
var cellBadgeView: HLDBadgeView? {
get {
return objc_getAssociatedObject(self, &cellBadgeViewAssociationKey) as? HLDBadgeView
}
set(newValue) {
objc_setAssociatedObject(self, &cellBadgeViewAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public func hld_setCellBadgeCount(count: UInt) {
if cellBadgeView == nil {
cellBadgeView = HLDBadgeView()
cellBadgeView!.autoHideWhenZero = true
contentView.addSubview(cellBadgeView!)
}
cellBadgeView!.setCount(count)
_updateBadgeViewCenter()
}
private func _updateBadgeViewCenter() {
cellBadgeView?.center = CGPoint(x: CGRectGetMaxX(contentView.bounds) - CGRectGetWidth(contentView.bounds) * 0.2, y: CGRectGetMidY(contentView.bounds))
}
public func hld_setX(x: CGFloat) {
if let badgeView = cellBadgeView {
var rect = badgeView.frame
rect.origin.x = x
badgeView.frame = rect
}
}
}
|
mit
|
48bffc4fdcd8ae3e44ac776b2545a261
| 27.375 | 158 | 0.643172 | 4.465574 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/BasicChartTypes/MountainChartView.swift
|
1
|
2482
|
//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// MountainChartView.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
class MountainChartView: SingleChartLayout {
override func initExample() {
let xAxis = SCIDateTimeAxis()
xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
let yAxis = SCINumericAxis()
yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
let priceData = DataManager.getPriceDataIndu()
let dataSeries = SCIXyDataSeries(xType: .dateTime, yType: .double)
dataSeries.appendRangeX(SCIGeneric(priceData!.dateData()), y: SCIGeneric(priceData!.closeData()), count: priceData!.size())
let rSeries = SCIFastMountainRenderableSeries()
rSeries.dataSeries = dataSeries
rSeries.zeroLineY = 10000
rSeries.areaStyle = SCILinearGradientBrushStyle(colorCodeStart: 0xAAFF8D42, finish: 0x88090E11, direction: .vertical)
rSeries.strokeStyle = SCISolidPenStyle(colorCode: 0xAAFFC9A8, withThickness: 1.0)
let xAxisDragmodifier = SCIXAxisDragModifier()
xAxisDragmodifier.clipModeX = .none
let yAxisDragmodifier = SCIYAxisDragModifier()
yAxisDragmodifier.dragMode = .pan
SCIUpdateSuspender.usingWithSuspendable(surface) {
self.surface.xAxes.add(xAxis)
self.surface.yAxes.add(yAxis)
self.surface.renderableSeries.add(rSeries)
self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [xAxisDragmodifier, yAxisDragmodifier, SCIPinchZoomModifier(), SCIZoomExtentsModifier(), SCITooltipModifier()])
rSeries.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut))
}
}
}
|
mit
|
3fe10a8f440061bf55f2023e0da52c84
| 47.607843 | 196 | 0.654699 | 4.625 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Models/CoreData/Data Rows/DataPersons.swift
|
1
|
3259
|
//
// DataPersons.swift
// MEGameTracker
//
// Created by Emily Ivie on 9/6/15.
// Copyright © 2015 urdnot. All rights reserved.
//
import Foundation
import CoreData
extension DataPerson: DataRowStorable, DataEventsable {
/// (CodableCoreDataStorable Protocol)
/// Type of the core data entity.
public typealias EntityType = DataPersons
/// (CodableCoreDataStorable Protocol)
/// Sets core data values to match struct values (specific).
public func setAdditionalColumnsOnSave(
coreItem: EntityType
) {
// only save searchable columns
coreItem.id = id
coreItem.name = name
coreItem.personType = gameValues(key: "personType", defaultValue: "0")
coreItem.isMaleLoveInterest = gameValues(key: "isMaleLoveInterest", defaultValue: "0")
coreItem.isFemaleLoveInterest = gameValues(key: "isFemaleLoveInterest", defaultValue: "0")
coreItem.relatedEvents = getRelatedDataEvents(context: coreItem.managedObjectContext)
}
/// (DataRowStorable Protocol)
public mutating func migrateId(id newId: String) {
id = newId
}
}
extension DataPerson {
/// The closure type for editing fetch requests.
/// (Duplicate these per file or use Whole Module Optimization, which is slow in dev)
public typealias AlterFetchRequest<T: NSManagedObject> = ((NSFetchRequest<T>) -> Void)
// MARK: Methods customized with GameVersion
/// Retrieves a DataPerson matching an id, set to gameVersion.
/// Leave gameVersion nil to get current gameVersion (recommended use).
public static func get(
id: String,
gameVersion: GameVersion?,
with manager: CodableCoreDataManageable? = nil
) -> DataPerson? {
let one: DataPerson? = get(gameVersion: gameVersion, with: manager) { fetchRequest in
fetchRequest.predicate = NSPredicate(
format: "(%K == %@)",
"id", id
)
}
return one
}
/// Retrieves a DataPerson matching some criteria, set to gameVersion.
/// Leave gameVersion nil to get current gameVersion (recommended use).
public static func get(
gameVersion: GameVersion?,
with manager: CodableCoreDataManageable? = nil,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> DataPerson? {
let preferredGameVersion = gameVersion ?? App.current.gameVersion
let one: DataPerson? = get(with: manager, alterFetchRequest: alterFetchRequest)
return one?.changed(gameVersion: preferredGameVersion)
}
/// Retrieves multiple DataPersons matching some criteria, set to gameVersion.
/// Leave gameVersion nil to get current gameVersion (recommended use).
public static func getAll(
gameVersion: GameVersion?,
with manager: CodableCoreDataManageable? = nil,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> [DataPerson] {
let preferredGameVersion = gameVersion ?? App.current.gameVersion
let all: [DataPerson] = getAll(with: manager, alterFetchRequest: alterFetchRequest)
return all.map { $0.changed(gameVersion: preferredGameVersion) }
}
public mutating func delete(
with manager: CodableCoreDataManageable? = nil
) -> Bool {
let manager = manager ?? defaultManager
var isDeleted = true
isDeleted = isDeleted && (photo?.delete() ?? true)
isDeleted = isDeleted && (manager.deleteValue(item: self) )
return isDeleted
}
}
|
mit
|
060b1df0ab48c3fd4d22d779c4041e25
| 33.294737 | 92 | 0.734193 | 4.247718 | false | false | false | false |
leo150/Pelican
|
Sources/Pelican/Pelican/Builder/Builder.swift
|
1
|
5724
|
//
// Builder.swift
//
// Created by Takanu Kyriako on 07/07/2017.
//
import Foundation
import Vapor
/**
Defines a class that will be used by Pelican to automatically generate Sessions based on two key components:
- Spawner: A function that checks an update to see whether or not it matches given criteria in that function, returning a non-nil ID value if true.
Pre-built spawners are available through the `Spawn` class, or you can just make your own so long as they conform to the type `(Update) -> Int?`.
- Session: The type of session to be created if the spawner succeeds.
## SessionBuilder Example
```
let chatSpawner = Spawn.perChatID(updateType: [.message], chatType: [.private])
pelican.addBuilder(SessionBuilder(spawner: chatSpawner, session: ChatSession.self, setup: nil) )
```
*/
public class SessionBuilder {
/** The identifier for the Builder, to allow Pelican to identify and send events to it from an individual Session.
This is an internal ID and should not be changed. */
var id: Int = 0
public var getID: Int { return id }
/// A function that checks an update to see whether or not it matches given criteria in that function, returning a non-nil value if true.
var spawner: (Update) -> Int?
/// The type of identification the spawner function generates, which is then used to identify a Session.
var idType: SessionIDType
/// The session type that's created using the builder.
var session: Session.Type
/** An optional function type that can be used to initialise a Session type in a custom way, such as if it has any additional initialisation paramaters.
If left empty, the default Session initialiser will be used. */
var setup: ((Pelican, SessionTag, Update) -> (Session))?
/** An optional closure designed to resolve "collisions", when two or more builders capture the same update.
The closure must return a specific enumerator that determines whether based on the collision, the builder will either not
execute the update for a session, include itself in the update object for other sessions to use, or execute it.
- note: If left unused, the builder will always execute an update it has successfully captured, even if another builder has also captured it.
*/
public var collision: ((Pelican, Update) -> (BuilderCollision))?
/// The number of sessions the builder can have active at any given time. Leave at 0 for no limit.
var maxSessions: Int = 0
/// The sessions that have been spawned by the builder and are currently active.
var sessions: [Int:Session] = [:]
public var getSessionCount: Int { return sessions.count }
/**
Creates a SessionBuilder, responsible for automatically generating different session types.
- parameter spawner: A function that checks an update to see whether or not it matches given criteria in that function, returning a non-nil ID value if true.
- parameter setup: An optional function type that can be used to setup Sessions when created to be given anything else that isn't available during
initialisation, such as specific Flood Limits and Timeouts.
*/
public init(spawner: @escaping (Update) -> Int?, idType: SessionIDType, session: Session.Type, setup: ((Pelican, SessionTag, Update) -> (Session))?) {
self.spawner = spawner
self.idType = idType
self.session = session
self.setup = setup
}
/**
Assigns the Builder an ID to allow sessions that are spawned from it to generate events that Pelican can apply to the builder.
This should only be used by Pelican once it receives a builder, and nowhere else.
*/
func setID(_ id: Int) {
self.id = id
}
/**
Checks the update to decide whether or not this builder can handle the update.
- returns: True if the builder can use the update, and false if not
*/
func checkUpdate(_ update: Update) -> Bool {
if spawner(update) != nil {
return true
}
return false
}
/**
Attempts to return a session based on a given update.
- returns: A session that corresponds with the given update if the Builder can handle it,
and nil if it could not.
*/
func getSession(bot: Pelican, update: Update) -> Session? {
/// Check if our spawner gives us a non-nil value
if let id = spawner(update) {
/// Check if we can get a session/
if let session = sessions[id] {
return session
}
// If not, build one
else {
print("BUILDING SESSION - \(id)")
// If the setup function exists, use it
if setup != nil {
let tag = SessionTag(bot: bot, builder: self, id: id)
let session = setup!(bot, tag, update)
sessions[id] = session
return session
}
// If it doesn't, use the default initialiser.
else {
let tag = SessionTag(bot: bot, builder: self, id: id)
let session = self.session.init(bot: bot, tag: tag, update: update)
session.postInit()
sessions[id] = session
return session
}
}
}
return nil
}
/**
Attempts to generate or use a session with the builder using a given update object.
- parameter update: The update to use to see if a session can be built with it.
- returns: True if the update was successfully used, and false if not.
*/
func execute(bot: Pelican, update: Update) -> Bool {
if let session = getSession(bot: bot, update: update) {
session.update(update)
return true
}
return false
}
/**
Attempts to remove a Session, given the SessionTag that identifies it.
*/
func removeSession(tag: SessionTag) {
if tag.getBuilderID != self.id { return }
if let session = sessions[tag.getSessionID] {
session.close()
sessions.removeValue(forKey: tag.getSessionID)
print("SESSION REMOVED - \(tag.getSessionID)")
}
}
}
|
mit
|
0c6769671cca440bc3e271adff4f0487
| 32.27907 | 158 | 0.706324 | 3.823647 | false | false | false | false |
klaasscho1/KSPulseView
|
KSPulseView/KSPulseView.swift
|
1
|
3230
|
//
// SBPulseView.swift
// UIPro
//
// Created by Klaas Schoenmaker on 18-12-15.
// Copyright © 2015 Klaas Schoenmaker. All rights reserved.
//
import UIKit
class KSPulseView: UIView {
var radius: CGFloat!
var duration: NSTimeInterval!
var interval: NSTimeInterval!
var colors: [UIColor]!
private var pulsing = true
private var pulseTimer: NSTimer?
private var currentPulse = 0
var isPulsing: Bool {
return pulsing
}
init(_ frame: CGRect, withDuration duration: NSTimeInterval?, withPulseInterval interval: NSTimeInterval?, withColors colors: [UIColor]?) {
super.init(frame: frame)
// Set variables to user values
self.radius = (frame.size.height < frame.size.width ? frame.size.height : frame.size.width) // Smallest dimension becomes radius
self.duration = duration
self.interval = interval
self.colors = colors
self.setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
// Set variables to default values
self.radius = (frame.size.height < frame.size.width ? frame.size.height : frame.size.width) // Smallest dimension becomes radius
self.duration = 1.5
self.interval = 0.5
self.colors = [UIColor.redColor()]
self.setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
self.pulseTimer = NSTimer.scheduledTimerWithTimeInterval(self.interval, target: self, selector: Selector("pulse"), userInfo: nil, repeats: true)
}
func pulse() {
let pulseView = UIView(frame: CGRectMake(0, 0, self.radius, self.radius))
pulseView.center.x = self.frame.size.width/2
pulseView.center.y = self.frame.size.height/2
pulseView.backgroundColor = self.colors[self.currentPulse]
pulseView.layer.cornerRadius = self.radius/2
pulseView.transform = CGAffineTransformMakeScale(0.0, 0.0)
self.addSubview(pulseView)
UIView.animateWithDuration(self.duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
pulseView.transform = CGAffineTransformMakeScale(1.0, 1.0)
pulseView.alpha = 0.0
}, completion: { (value: Bool) -> Void in
pulseView.removeFromSuperview()
})
self.currentPulse = (self.currentPulse + 1) % self.colors.count
}
func stopPulsing() {
if self.isPulsing {
self.pulsing = false
self.pulseTimer?.invalidate()
} else {
print("Already stopped pulsing; can't stop anymore.")
}
}
func startPulsing() {
if !self.isPulsing {
self.pulsing = true
self.pulseTimer = NSTimer.scheduledTimerWithTimeInterval(self.interval, target: self, selector: Selector("pulse"), userInfo: nil, repeats: true)
} else {
print("Already started pulsing; can't start again.")
}
}
}
|
mit
|
461db0a3f7cde6bf4c9c121b126a09d3
| 30.970297 | 156 | 0.600496 | 4.554302 | false | false | false | false |
sebastianvarela/iOS-Swift-Helpers
|
Helpers/Helpers/NetworkRequest.swift
|
2
|
4037
|
import Foundation
public class NetworkRequest {
public let url: URL
public let requestType: RequestType
public private(set)var urlRequest: URLRequest
public init(url: URL, requestType: RequestType) {
self.url = url
self.requestType = requestType
// Request
switch requestType {
case let .soap(header, message):
var request: URLRequest = URLRequest(url: url)
request.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue(url.absoluteString, forHTTPHeaderField: "SOAPAction")
request.setValue("\(message.count)", forHTTPHeaderField: "Content-Lenght")
request.httpBody = message.data(using: .utf8)
request.httpMethod = Method.post.rawValue
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
request.allHTTPHeaderFields = header as? [String: String]
self.urlRequest = request
case let .rest(method, header, queryString, contentType):
let urlWithQueryParameters = queryString.isEmpty ? url : url.appendingQueryParameters(queryString)
var request: URLRequest = URLRequest(url: urlWithQueryParameters)
if let body = contentType.body {
request.setValue(contentType.httpHeaderValue, forHTTPHeaderField: "Content-Type")
request.httpBody = body
}
request.httpMethod = method.rawValue
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
request.allHTTPHeaderFields = header as? [String: String]
self.urlRequest = request
}
}
public func add(headers: [String: String]) {
urlRequest.allHTTPHeaderFields?.update(other: headers)
}
public enum Method: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
public enum ResponseType {
case array
case object
case none
}
public enum ContentType {
case json(body: JSON)
case formURLEncoded(body: Form)
case form(body: Form, boundary: String)
case none
}
public enum RequestType {
case soap(header: JSON, message: String)
case rest(method: Method, header: JSON, queryString: [String: String], contentType: ContentType)
}
public enum Authentication {
case none, authenticated(AuthenticationLevel)
}
public enum AuthenticationLevel {
case userLevel
case appLevel
}
}
extension NetworkRequest.ContentType {
public var httpHeaderValue: String {
switch self {
case .json:
return "application/json"
case .formURLEncoded:
return "application/x-www-form-urlencoded"
case let .form(_, boundary):
return "multipart/form-data; boundary=\(boundary)"
case .none:
return ""
}
}
public var body: Data? {
switch self {
case let .json(parameters):
if parameters.isEmpty {
return nil
}
return try? JSONSerialization.data(withJSONObject: parameters, options: [])
case let .formURLEncoded(form):
if form.isEmpty {
return nil
}
return form.map({ "\($0)=\($1)" }).joined(separator: "&").data(using: .utf8)
case let .form(form, boundary):
if form.isEmpty {
return nil
}
return MultiPartForm(form: form, boundary: boundary).body
case .none:
return nil
}
}
}
|
mit
|
b2a638a7162b504dfbfd66b91f57657a
| 30.787402 | 110 | 0.567253 | 5.249675 | false | false | false | false |
eneko/SourceDocs
|
Sources/SourceDocsLib/DocumentationGenerator/AccessLevel.swift
|
1
|
1423
|
//
// AccessLevel.swift
// SourceDocsLib
//
// Created by Eneko Alonso on 11/1/19.
//
import Foundation
public enum AccessLevel: String, CaseIterable {
case `private`
case `fileprivate`
case `internal`
case `public`
case `open`
init(accessiblityKey: String?) {
switch accessiblityKey {
case .some("source.lang.swift.accessibility.private"):
self = .private
case .some("source.lang.swift.accessibility.fileprivate"):
self = .fileprivate
case .some("source.lang.swift.accessibility.internal"):
self = .internal
case .some("source.lang.swift.accessibility.public"):
self = .public
case .some("source.lang.swift.accessibility.open"):
self = .open
default:
self = .private
}
}
var priority: Int {
switch self {
case .private:
return 0
case .fileprivate:
return 1
case .internal:
return 2
case .public:
return 3
case .open:
return 4
}
}
}
extension AccessLevel: Comparable, Equatable {
public static func < (lhs: AccessLevel, rhs: AccessLevel) -> Bool {
return lhs.priority < rhs.priority
}
public static func == (lhs: AccessLevel, rhs: AccessLevel) -> Bool {
return lhs.priority == rhs.priority
}
}
|
mit
|
250e019cbcaca611764b3888a93cdc43
| 23.534483 | 72 | 0.568517 | 4.405573 | false | false | false | false |
apple/swift
|
test/SILGen/reasync.swift
|
4
|
2532
|
// RUN: %target-swift-frontend -emit-silgen %s -enable-experimental-concurrency -disable-availability-checking | %FileCheck %s
// REQUIRES: concurrency
// CHECK-LABEL: sil hidden [ossa] @$s7reasync0A8FunctionyyyyYaXEYaF : $@convention(thin) @async (@noescape @async @callee_guaranteed () -> ()) -> () {
func reasyncFunction(_ a: () async -> ()) reasync {
await a()
}
// CHECK-LABEL: sil hidden [ossa] @$s7reasync10syncCalleryyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () {
// CHECK: [[THUNK_FN:%.*]] = function_ref @$sIg_IegH_TR : $@convention(thin) @async (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]](%0) : $@convention(thin) @async (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: [[NOESCAPE:%.*]] = convert_escape_to_noescape [not_guaranteed] [[THUNK]] : $@async @callee_guaranteed () -> () to $@noescape @async @callee_guaranteed () -> ()
// CHECK: [[FN:%.*]] = function_ref @$s7reasync0A8FunctionyyyyYaXEYaF : $@convention(thin) @async (@noescape @async @callee_guaranteed () -> ()) -> ()
// CHECK: apply [noasync] [[FN]]([[NOESCAPE]]) : $@convention(thin) @async (@noescape @async @callee_guaranteed () -> ()) -> ()
func syncCaller(_ fn: () -> ()) {
reasyncFunction(fn)
}
func asyncCaller(_ fn: () async -> ()) async {
// CHECK: [[FN:%.*]] = function_ref @$s7reasync0A8FunctionyyyyYaXEYaF : $@convention(thin) @async (@noescape @async @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[FN]](%0) : $@convention(thin) @async (@noescape @async @callee_guaranteed () -> ()) -> ()
await reasyncFunction(fn)
}
// CHECK-LABEL: sil hidden [ossa] @$s7reasync23throwingReasyncFunctionyyyyYaKXEYaKF : $@convention(thin) @async (@noescape @async @callee_guaranteed () -> @error any Error) -> @error any Error {
func throwingReasyncFunction(_ a: () async throws -> ()) reasync throws {
try await a()
}
// CHECK-LABEL: sil hidden [ossa] @$s7reasync18throwingSyncCalleryyyyXEKF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> @error any Error {
// CHECK: [[FN:%.*]] = function_ref @$s7reasync23throwingReasyncFunctionyyyyYaKXEYaKF : $@convention(thin) @async (@noescape @async @callee_guaranteed () -> @error any Error) -> @error any Error
// CHECK: try_apply [noasync] [[FN]]({{.*}}) : $@convention(thin) @async (@noescape @async @callee_guaranteed () -> @error any Error) -> @error any Error, normal bb1, error bb2
func throwingSyncCaller(_ fn: () -> ()) throws {
try throwingReasyncFunction(fn)
}
|
apache-2.0
|
da090040c848609d819b00d24cb7ee14
| 71.342857 | 194 | 0.653633 | 3.463748 | false | false | false | false |
apple/swift
|
stdlib/public/core/Mirror.swift
|
2
|
30681
|
//===--- Mirror.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
//
//===----------------------------------------------------------------------===//
// FIXME: ExistentialCollection needs to be supported before this will work
// without the ObjC Runtime.
#if SWIFT_ENABLE_REFLECTION
/// A representation of the substructure and display style of an instance of
/// any type.
///
/// A mirror describes the parts that make up a particular instance, such as
/// the instance's stored properties, collection or tuple elements, or its
/// active enumeration case. Mirrors also provide a "display style" property
/// that suggests how this mirror might be rendered.
///
/// Playgrounds and the debugger use the `Mirror` type to display
/// representations of values of any type. For example, when you pass an
/// instance to the `dump(_:_:_:_:)` function, a mirror is used to render that
/// instance's runtime contents.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(reflecting: p))
/// // Prints "▿ Point
/// // - x: 21
/// // - y: 30"
///
/// To customize the mirror representation of a custom type, add conformance to
/// the `CustomReflectable` protocol.
public struct Mirror {
/// The static type of the subject being reflected.
///
/// This type may differ from the subject's dynamic type when this mirror
/// is the `superclassMirror` of another mirror.
public let subjectType: Any.Type
/// A collection of `Child` elements describing the structure of the
/// reflected subject.
public let children: Children
/// A suggested display style for the reflected subject.
public let displayStyle: DisplayStyle?
internal let _makeSuperclassMirror: () -> Mirror?
internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation
/// Creates a mirror that reflects on the given instance.
///
/// If the dynamic type of `subject` conforms to `CustomReflectable`, the
/// resulting mirror is determined by its `customMirror` property.
/// Otherwise, the result is generated by the language.
///
/// If the dynamic type of `subject` has value semantics, subsequent
/// mutations of `subject` will not observable in `Mirror`. In general,
/// though, the observability of mutations is unspecified.
///
/// - Parameter subject: The instance for which to create a mirror.
public init(reflecting subject: Any) {
if case let customized as CustomReflectable = subject {
self = customized.customMirror
} else {
self = Mirror(internalReflecting: subject)
}
}
/// Creates a mirror representing the given subject with a specified
/// structure.
///
/// You use this initializer from within your type's `customMirror`
/// implementation to create a customized mirror.
///
/// If `subject` is a class instance, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, the
/// `customMirror` implementation of any ancestors is ignored. To prevent
/// bypassing customized ancestors, pass
/// `.customized({ super.customMirror })` as the `ancestorRepresentation`
/// parameter when implementing your type's `customMirror` property.
///
/// - Parameters:
/// - subject: The instance to represent in the new mirror.
/// - children: The structure to use for the mirror. The collection
/// traversal modeled by `children` is captured so that the resulting
/// mirror's children may be upgraded to a bidirectional or random
/// access collection later. See the `children` property for details.
/// - displayStyle: The preferred display style for the mirror when
/// presented in the debugger or in a playground. The default is `nil`.
/// - ancestorRepresentation: The means of generating the subject's
/// ancestor representation. `ancestorRepresentation` is ignored if
/// `subject` is not a class instance. The default is `.generated`.
public init<Subject, C: Collection>(
_ subject: Subject,
children: C,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) where C.Element == Child {
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
self.children = Children(children)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// Creates a mirror representing the given subject with unlabeled children.
///
/// You use this initializer from within your type's `customMirror`
/// implementation to create a customized mirror, particularly for custom
/// types that are collections. The labels of the resulting mirror's
/// `children` collection are all `nil`.
///
/// If `subject` is a class instance, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, the
/// `customMirror` implementation of any ancestors is ignored. To prevent
/// bypassing customized ancestors, pass
/// `.customized({ super.customMirror })` as the `ancestorRepresentation`
/// parameter when implementing your type's `customMirror` property.
///
/// - Parameters:
/// - subject: The instance to represent in the new mirror.
/// - unlabeledChildren: The children to use for the mirror. The collection
/// traversal modeled by `unlabeledChildren` is captured so that the
/// resulting mirror's children may be upgraded to a bidirectional or
/// random access collection later. See the `children` property for
/// details.
/// - displayStyle: The preferred display style for the mirror when
/// presented in the debugger or in a playground. The default is `nil`.
/// - ancestorRepresentation: The means of generating the subject's
/// ancestor representation. `ancestorRepresentation` is ignored if
/// `subject` is not a class instance. The default is `.generated`.
public init<Subject, C: Collection>(
_ subject: Subject,
unlabeledChildren: C,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) {
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
let lazyChildren =
unlabeledChildren.lazy.map { Child(label: nil, value: $0) }
self.children = Children(lazyChildren)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// Creates a mirror representing the given subject using a dictionary
/// literal for the structure.
///
/// You use this initializer from within your type's `customMirror`
/// implementation to create a customized mirror. Pass a dictionary literal
/// with string keys as `children`. Although an *actual* dictionary is
/// arbitrarily-ordered, when you create a mirror with a dictionary literal,
/// the ordering of the mirror's `children` will exactly match that of the
/// literal you pass.
///
/// If `subject` is a class instance, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, the
/// `customMirror` implementation of any ancestors is ignored. To prevent
/// bypassing customized ancestors, pass
/// `.customized({ super.customMirror })` as the `ancestorRepresentation`
/// parameter when implementing your type's `customMirror` property.
///
/// - Parameters:
/// - subject: The instance to represent in the new mirror.
/// - children: A dictionary literal to use as the structure for the
/// mirror. The `children` collection of the resulting mirror may be
/// upgraded to a random access collection later. See the `children`
/// property for details.
/// - displayStyle: The preferred display style for the mirror when
/// presented in the debugger or in a playground. The default is `nil`.
/// - ancestorRepresentation: The means of generating the subject's
/// ancestor representation. `ancestorRepresentation` is ignored if
/// `subject` is not a class instance. The default is `.generated`.
public init<Subject>(
_ subject: Subject,
children: KeyValuePairs<String, Any>,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) {
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) }
self.children = Children(lazyChildren)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// A mirror of the subject's superclass, if one exists.
public var superclassMirror: Mirror? {
return _makeSuperclassMirror()
}
}
extension Mirror {
/// Representation of descendant classes that don't override
/// `customMirror`.
///
/// Note that the effect of this setting goes no deeper than the
/// nearest descendant class that overrides `customMirror`, which
/// in turn can determine representation of *its* descendants.
internal enum _DefaultDescendantRepresentation {
/// Generate a default mirror for descendant classes that don't
/// override `customMirror`.
///
/// This case is the default.
case generated
/// Suppress the representation of descendant classes that don't
/// override `customMirror`.
///
/// This option may be useful at the root of a class cluster, where
/// implementation details of descendants should generally not be
/// visible to clients.
case suppressed
}
/// The representation to use for ancestor classes.
///
/// A class that conforms to the `CustomReflectable` protocol can control how
/// its mirror represents ancestor classes by initializing the mirror
/// with an `AncestorRepresentation`. This setting has no effect on mirrors
/// reflecting value type instances.
public enum AncestorRepresentation {
/// Generates a default mirror for all ancestor classes.
///
/// This case is the default when initializing a `Mirror` instance.
///
/// When you use this option, a subclass's mirror generates default mirrors
/// even for ancestor classes that conform to the `CustomReflectable`
/// protocol. To avoid dropping the customization provided by ancestor
/// classes, an override of `customMirror` should pass
/// `.customized({ super.customMirror })` as `ancestorRepresentation` when
/// initializing its mirror.
case generated
/// Uses the nearest ancestor's implementation of `customMirror` to create
/// a mirror for that ancestor.
///
/// Other classes derived from such an ancestor are given a default mirror.
/// The payload for this option should always be `{ super.customMirror }`:
///
/// var customMirror: Mirror {
/// return Mirror(
/// self,
/// children: ["someProperty": self.someProperty],
/// ancestorRepresentation: .customized({ super.customMirror })) // <==
/// }
case customized(() -> Mirror)
/// Suppresses the representation of all ancestor classes.
///
/// In a mirror created with this ancestor representation, the
/// `superclassMirror` property is `nil`.
case suppressed
}
/// An element of the reflected instance's structure.
///
/// When the `label` component in not `nil`, it may represent the name of a
/// stored property or an active `enum` case. If you pass strings to the
/// `descendant(_:_:)` method, labels are used for lookup.
public typealias Child = (label: String?, value: Any)
/// The type used to represent substructure.
///
/// When working with a mirror that reflects a bidirectional or random access
/// collection, you may find it useful to "upgrade" instances of this type
/// to `AnyBidirectionalCollection` or `AnyRandomAccessCollection`. For
/// example, to display the last twenty children of a mirror if they can be
/// accessed efficiently, you write the following code:
///
/// if let b = AnyBidirectionalCollection(someMirror.children) {
/// for element in b.suffix(20) {
/// print(element)
/// }
/// }
public typealias Children = AnyCollection<Child>
/// A suggestion of how a mirror's subject is to be interpreted.
///
/// Playgrounds and the debugger will show a representation similar
/// to the one used for instances of the kind indicated by the
/// `DisplayStyle` case name when the mirror is used for display.
public enum DisplayStyle: Sendable {
case `struct`, `class`, `enum`, tuple, optional, collection
case dictionary, `set`
}
internal static func _noSuperclassMirror() -> Mirror? { return nil }
@_semantics("optimize.sil.specialize.generic.never")
@inline(never)
internal static func _superclassIterator<Subject>(
_ subject: Subject, _ ancestorRepresentation: AncestorRepresentation
) -> () -> Mirror? {
if let subjectClass = Subject.self as? AnyClass,
let superclass = _getSuperclass(subjectClass) {
switch ancestorRepresentation {
case .generated:
return {
Mirror(internalReflecting: subject, subjectType: superclass)
}
case .customized(let makeAncestor):
return {
let ancestor = makeAncestor()
if superclass == ancestor.subjectType
|| ancestor._defaultDescendantRepresentation == .suppressed {
return ancestor
} else {
return Mirror(internalReflecting: subject,
subjectType: superclass,
customAncestor: ancestor)
}
}
case .suppressed:
break
}
}
return Mirror._noSuperclassMirror
}
}
/// A type that explicitly supplies its own mirror.
///
/// You can create a mirror for any type using the `Mirror(reflecting:)`
/// initializer, but if you are not satisfied with the mirror supplied for
/// your type by default, you can make it conform to `CustomReflectable` and
/// return a custom `Mirror` instance.
public protocol CustomReflectable {
/// The custom mirror for this instance.
///
/// If this type has value semantics, the mirror should be unaffected by
/// subsequent mutations of the instance.
var customMirror: Mirror { get }
}
/// A type that explicitly supplies its own mirror, but whose
/// descendant classes are not represented in the mirror unless they
/// also override `customMirror`.
public protocol CustomLeafReflectable: CustomReflectable {}
//===--- Addressing -------------------------------------------------------===//
/// A protocol for legitimate arguments to `Mirror`'s `descendant`
/// method.
///
/// Do not declare new conformances to this protocol; they will not
/// work as expected.
public protocol MirrorPath {
// FIXME(ABI)#49 (Sealed Protocols): this protocol should be "non-open" and
// you shouldn't be able to create conformances.
}
extension Int: MirrorPath {}
extension String: MirrorPath {}
extension Mirror {
internal struct _Dummy: CustomReflectable {
internal init(mirror: Mirror) {
self.mirror = mirror
}
internal var mirror: Mirror
internal var customMirror: Mirror { return mirror }
}
/// Returns a specific descendant of the reflected subject, or `nil` if no
/// such descendant exists.
///
/// Pass a variadic list of string and integer arguments. Each string
/// argument selects the first child with a matching label. Each integer
/// argument selects the child at that offset. For example, passing
/// `1, "two", 3` as arguments to `myMirror.descendant(_:_:)` is equivalent
/// to:
///
/// var result: Any? = nil
/// let children = myMirror.children
/// if let i0 = children.index(
/// children.startIndex, offsetBy: 1, limitedBy: children.endIndex),
/// i0 != children.endIndex
/// {
/// let grandChildren = Mirror(reflecting: children[i0].value).children
/// if let i1 = grandChildren.firstIndex(where: { $0.label == "two" }) {
/// let greatGrandChildren =
/// Mirror(reflecting: grandChildren[i1].value).children
/// if let i2 = greatGrandChildren.index(
/// greatGrandChildren.startIndex,
/// offsetBy: 3,
/// limitedBy: greatGrandChildren.endIndex),
/// i2 != greatGrandChildren.endIndex
/// {
/// // Success!
/// result = greatGrandChildren[i2].value
/// }
/// }
/// }
///
/// This function is suitable for exploring the structure of a mirror in a
/// REPL or playground, but is not intended to be efficient. The efficiency
/// of finding each element in the argument list depends on the argument
/// type and the capabilities of the each level of the mirror's `children`
/// collections. Each string argument requires a linear search, and unless
/// the underlying collection supports random-access traversal, each integer
/// argument also requires a linear operation.
///
/// - Parameters:
/// - first: The first mirror path component to access.
/// - rest: Any remaining mirror path components.
/// - Returns: The descendant of this mirror specified by the given mirror
/// path components if such a descendant exists; otherwise, `nil`.
public func descendant(
_ first: MirrorPath, _ rest: MirrorPath...
) -> Any? {
var result: Any = _Dummy(mirror: self)
for e in [first] + rest {
let children = Mirror(reflecting: result).children
let position: Children.Index
if case let label as String = e {
position = children.firstIndex { $0.label == label } ?? children.endIndex
}
else if let offset = e as? Int {
position = children.index(children.startIndex,
offsetBy: offset,
limitedBy: children.endIndex) ?? children.endIndex
}
else {
_preconditionFailure(
"Someone added a conformance to MirrorPath; that privilege is reserved to the standard library")
}
if position == children.endIndex { return nil }
result = children[position].value
}
return result
}
}
#else // SWIFT_ENABLE_REFLECTION
@available(*, unavailable)
public struct Mirror {
public enum AncestorRepresentation {
case generated
case customized(() -> Mirror)
case suppressed
}
public init(reflecting subject: Any) { Builtin.unreachable() }
public typealias Child = (label: String?, value: Any)
public typealias Children = AnyCollection<Child>
public enum DisplayStyle: Sendable {
case `struct`, `class`, `enum`, tuple, optional, collection
case dictionary, `set`
}
public init<Subject, C: Collection>(
_ subject: Subject,
children: C,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) where C.Element == Child {
Builtin.unreachable()
}
public init<Subject, C: Collection>(
_ subject: Subject,
unlabeledChildren: C,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) {
Builtin.unreachable()
}
public init<Subject>(
_ subject: Subject,
children: KeyValuePairs<String, Any>,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) {
Builtin.unreachable()
}
public let subjectType: Any.Type
public let children: Children
public let displayStyle: DisplayStyle?
public var superclassMirror: Mirror? { Builtin.unreachable() }
}
@available(*, unavailable)
public protocol CustomReflectable {
var customMirror: Mirror { get }
}
@available(*, unavailable)
public protocol CustomLeafReflectable: CustomReflectable {}
@available(*, unavailable)
public protocol MirrorPath {}
@available(*, unavailable)
extension Int: MirrorPath {}
@available(*, unavailable)
extension String: MirrorPath {}
@available(*, unavailable)
extension Mirror {
public func descendant(_ first: MirrorPath, _ rest: MirrorPath...) -> Any? {
Builtin.unreachable()
}
}
#endif // SWIFT_ENABLE_REFLECTION
//===--- General Utilities ------------------------------------------------===//
extension String {
/// Creates a string representing the given value.
///
/// Use this initializer to convert an instance of any type to its preferred
/// representation as a `String` instance. The initializer creates the
/// string representation of `instance` in one of the following ways,
/// depending on its protocol conformance:
///
/// - If `instance` conforms to the `TextOutputStreamable` protocol, the
/// result is obtained by calling `instance.write(to: s)` on an empty
/// string `s`.
/// - If `instance` conforms to the `CustomStringConvertible` protocol, the
/// result is `instance.description`.
/// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `instance.debugDescription`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(describing: p))
/// // Prints "Point(x: 21, y: 30)"
///
/// After adding `CustomStringConvertible` conformance by implementing the
/// `description` property, `Point` provides its own custom representation.
///
/// extension Point: CustomStringConvertible {
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// print(String(describing: p))
/// // Prints "(21, 30)"
public init<Subject>(describing instance: Subject) {
self.init()
_print_unlocked(instance, &self)
}
// These overloads serve as fast paths for init(describing:), but they
// also preserve source compatibility for clients which accidentally
// used init(stringInterpolationSegment:) through constructs like
// myArray.map(String.init).
/// Creates a string representing the given value.
///
/// Use this initializer to convert an instance of any type to its preferred
/// representation as a `String` instance. The initializer creates the
/// string representation of `instance` in one of the following ways,
/// depending on its protocol conformance:
///
/// - If `instance` conforms to the `TextOutputStreamable` protocol, the
/// result is obtained by calling `instance.write(to: s)` on an empty
/// string `s`.
/// - If `instance` conforms to the `CustomStringConvertible` protocol, the
/// result is `instance.description`.
/// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `instance.debugDescription`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(describing: p))
/// // Prints "Point(x: 21, y: 30)"
///
/// After adding `CustomStringConvertible` conformance by implementing the
/// `description` property, `Point` provides its own custom representation.
///
/// extension Point: CustomStringConvertible {
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// print(String(describing: p))
/// // Prints "(21, 30)"
@inlinable
public init<Subject: CustomStringConvertible>(describing instance: Subject) {
self = instance.description
}
/// Creates a string representing the given value.
///
/// Use this initializer to convert an instance of any type to its preferred
/// representation as a `String` instance. The initializer creates the
/// string representation of `instance` in one of the following ways,
/// depending on its protocol conformance:
///
/// - If `instance` conforms to the `TextOutputStreamable` protocol, the
/// result is obtained by calling `instance.write(to: s)` on an empty
/// string `s`.
/// - If `instance` conforms to the `CustomStringConvertible` protocol, the
/// result is `instance.description`.
/// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `instance.debugDescription`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(describing: p))
/// // Prints "Point(x: 21, y: 30)"
///
/// After adding `CustomStringConvertible` conformance by implementing the
/// `description` property, `Point` provides its own custom representation.
///
/// extension Point: CustomStringConvertible {
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// print(String(describing: p))
/// // Prints "(21, 30)"
@inlinable
public init<Subject: TextOutputStreamable>(describing instance: Subject) {
self.init()
instance.write(to: &self)
}
/// Creates a string representing the given value.
///
/// Use this initializer to convert an instance of any type to its preferred
/// representation as a `String` instance. The initializer creates the
/// string representation of `instance` in one of the following ways,
/// depending on its protocol conformance:
///
/// - If `instance` conforms to the `TextOutputStreamable` protocol, the
/// result is obtained by calling `instance.write(to: s)` on an empty
/// string `s`.
/// - If `instance` conforms to the `CustomStringConvertible` protocol, the
/// result is `instance.description`.
/// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `instance.debugDescription`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(describing: p))
/// // Prints "Point(x: 21, y: 30)"
///
/// After adding `CustomStringConvertible` conformance by implementing the
/// `description` property, `Point` provides its own custom representation.
///
/// extension Point: CustomStringConvertible {
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// print(String(describing: p))
/// // Prints "(21, 30)"
@inlinable
public init<Subject>(describing instance: Subject)
where Subject: CustomStringConvertible & TextOutputStreamable
{
self = instance.description
}
/// Creates a string with a detailed representation of the given value,
/// suitable for debugging.
///
/// Use this initializer to convert an instance of any type to its custom
/// debugging representation. The initializer creates the string
/// representation of `instance` in one of the following ways, depending on
/// its protocol conformance:
///
/// - If `subject` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `subject.debugDescription`.
/// - If `subject` conforms to the `CustomStringConvertible` protocol, the
/// result is `subject.description`.
/// - If `subject` conforms to the `TextOutputStreamable` protocol, the
/// result is obtained by calling `subject.write(to: s)` on an empty
/// string `s`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(reflecting: p))
/// // Prints "p: Point = {
/// // x = 21
/// // y = 30
/// // }"
///
/// After adding `CustomDebugStringConvertible` conformance by implementing
/// the `debugDescription` property, `Point` provides its own custom
/// debugging representation.
///
/// extension Point: CustomDebugStringConvertible {
/// var debugDescription: String {
/// return "Point(x: \(x), y: \(y))"
/// }
/// }
///
/// print(String(reflecting: p))
/// // Prints "Point(x: 21, y: 30)"
public init<Subject>(reflecting subject: Subject) {
self.init()
_debugPrint_unlocked(subject, &self)
}
}
#if SWIFT_ENABLE_REFLECTION
/// Reflection for `Mirror` itself.
extension Mirror: CustomStringConvertible {
public var description: String {
return "Mirror for \(self.subjectType)"
}
}
extension Mirror: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [:])
}
}
#endif // SWIFT_ENABLE_REFLECTION
|
apache-2.0
|
3cf0047559a44550da4effc116e1bd6d
| 38.081529 | 106 | 0.661364 | 4.76604 | false | false | false | false |
AsyncNinja/AsyncNinja
|
Sources/AsyncNinja/EventSource_Map.swift
|
1
|
28031
|
//
// Copyright (c) 2016-2017 Anton Mironov
//
// 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 Dispatch
// MARK: - whole channel transformations
public extension EventSource {
/// Applies transformation to the whole channel. `map` methods
/// are more convenient if you want to transform updates values only.
///
/// - Parameters:
/// - context: `ExectionContext` to apply transformation in
/// - executor: override of `ExecutionContext`s executor.
/// Keep default value of the argument unless you need to override
/// an executor provided by the context
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply
/// - strongContext: context restored from weak reference to specified context
/// - value: `ChannelValue` to transform. May be either update or completion
/// - Returns: transformed channel
func mapEvent<P, S, C: ExecutionContext>(
context: C,
executor: Executor? = nil,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (_ strongContext: C, _ event: Event) throws -> ChannelEvent<P, S>
) -> Channel<P, S> {
return makeProducer(
context: context,
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙mapEvent")
) { (context, event, producer, originalExecutor) in
let transformedEvent = try transform(context, event)
producer.value?.traceID?._asyncNinja_log("mapping from \(event)")
producer.value?.traceID?._asyncNinja_log("mapping to \(transformedEvent)")
producer.value?.post(transformedEvent, from: originalExecutor)
}
}
/// Applies transformation to the whole channel. `map` methods
/// are more convenient if you want to transform updates values only.
///
/// - Parameters:
/// - executor: to execute transform on
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply
/// - value: `ChannelValue` to transform. May be either update or completion
/// - Returns: transformed channel
func mapEvent<P, S>(
executor: Executor = .primary,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (_ event: Event) throws -> ChannelEvent<P, S>
) -> Channel<P, S> {
return makeProducer(
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙mapEvent")
) { (event, producer, originalExecutor) in
let transformedEvent = try transform(event)
producer.value?.traceID?._asyncNinja_log("mapping from \(event)")
producer.value?.traceID?._asyncNinja_log("mapping to \(transformedEvent)")
producer.value?.post(transformedEvent, from: originalExecutor)
}
}
}
// MARK: - updates only transformations
public extension EventSource {
/// Applies transformation to update values of the channel.
/// `map` methods are more convenient if you want to transform
/// both updates and completion
///
/// - Parameters:
/// - context: `ExectionContext` to apply transformation in
/// - executor: override of `ExecutionContext`s executor.
/// Keep default value of the argument unless you need to override
/// an executor provided by the context
/// - cancellationToken: `CancellationToken` to use. Keep default value
/// of the argument unless you need an extended cancellation options
/// of the returned channel
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply
/// - strongContext: context restored from weak reference to specified context
/// - update: `Update` to transform
/// - Returns: transformed channel
func map<P, C: ExecutionContext>(
context: C,
executor: Executor? = nil,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (_ strongContext: C, _ update: Update) throws -> P
) -> Channel<P, Success> {
// Test: EventSource_MapTests.testMapContextual
return makeProducer(
context: context,
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙map")
) { (context, event, producer, originalExecutor) in
switch event {
case .update(let update):
let transformedValue = try transform(context, update)
producer.value?.traceID?._asyncNinja_log("mapping from \(update)")
producer.value?.traceID?._asyncNinja_log("mapping to \(transformedValue)")
producer.value?.update(transformedValue, from: originalExecutor)
case .completion(let completion):
producer.value?.traceID?._asyncNinja_log("completion with \(completion)")
producer.value?.complete(completion, from: originalExecutor)
}
}
}
/// Applies transformation to update values of the channel.
/// `map` methods are more convenient if you want to transform
/// both updates and completion
///
/// - Parameters:
/// - executor: to execute transform on
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply
/// - update: `Update` to transform
/// - Returns: transformed channel
func map<P>(
executor: Executor = .primary,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (_ update: Update) throws -> P
) -> Channel<P, Success> {
// Test: EventSource_MapTests.testMap
traceID?._asyncNinja_log("apply mapping")
return makeProducer(
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙map")
) { (event, producer, originalExecutor) in
switch event {
case .update(let update):
let transformedValue = try transform(update)
producer.value?.traceID?._asyncNinja_log("mapping from \(update)")
producer.value?.traceID?._asyncNinja_log("mapping to \(transformedValue)")
producer.value?.update(transformedValue, from: originalExecutor)
case .completion(let completion):
producer.value?.traceID?._asyncNinja_log("completion with \(completion)")
producer.value?.complete(completion, from: originalExecutor)
}
}
}
}
// MARK: - updates only flattening transformations
public extension EventSource {
/// Applies transformation to update values of the channel.
///
/// - Parameters:
/// - context: `ExectionContext` to apply transformation in
/// - executor: override of `ExecutionContext`s executor.
/// Keep default value of the argument unless you need to override
/// an executor provided by the context
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply. Nil returned from transform will not produce update value
/// - strongContext: context restored from weak reference to specified context
/// - update: `Update` to transform
/// - Returns: transformed channel
func flatMap<P, C: ExecutionContext>(
context: C,
executor: Executor? = nil,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (_ strongContext: C, _ update: Update) throws -> P?
) -> Channel<P, Success> {
// Test: EventSource_MapTests.testFlatMapOptionalContextual
traceID?._asyncNinja_log("apply flatMapping")
return makeProducer(
context: context,
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙flatMapp")
) { (context, event, producer, originalExecutor) in
switch event {
case .update(let update):
if let transformedValue = try transform(context, update) {
producer.value?.traceID?._asyncNinja_log("flatMapping from \(update)")
producer.value?.traceID?._asyncNinja_log("flatMapping to \(transformedValue)")
producer.value?.update(transformedValue, from: originalExecutor)
}
case .completion(let completion):
producer.value?.traceID?._asyncNinja_log("completion with \(completion)")
producer.value?.complete(completion, from: originalExecutor)
}
}
}
/// Applies transformation to update values of the channel.
///
/// - Parameters:
/// - executor: to execute transform on
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply. Nil returned from transform will not produce update value
/// - update: `Update` to transform
/// - Returns: transformed channel
func flatMap<P>(
executor: Executor = .primary,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (_ update: Update) throws -> P?
) -> Channel<P, Success> {
// Test: EventSource_MapTests.testFlatMapOptional
return makeProducer(
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙flatMapp")
) { (event, producer, originalExecutor) in
switch event {
case .update(let update):
if let transformedValue = try transform(update) {
producer.value?.traceID?._asyncNinja_log("flatMapping update \(update)")
producer.value?.update(transformedValue, from: originalExecutor)
}
case .completion(let completion):
producer.value?.traceID?._asyncNinja_log("completion with \(completion)")
producer.value?.complete(completion, from: originalExecutor)
}
}
}
/// Applies transformation to update values of the channel.
///
/// - Parameters:
/// - context: `ExectionContext` to apply transformation in
/// - executor: override of `ExecutionContext`s executor.
/// Keep default value of the argument unless you need
/// to override an executor provided by the context
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply. Sequence returned from transform
/// will be treated as multiple period values
/// - strongContext: context restored from weak reference to specified context
/// - update: `Update` to transform
/// - Returns: transformed channel
func flatMap<PS: Sequence, C: ExecutionContext>(
context: C,
executor: Executor? = nil,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (_ strongContext: C, _ update: Update) throws -> PS
) -> Channel<PS.Iterator.Element, Success> {
// Test: EventSource_MapTests.testFlatMapArrayContextual
traceID?._asyncNinja_log("apply flatMapping")
return makeProducer(
context: context,
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙flatMapp")
) { (context, event, producer, originalExecutor) in
switch event {
case .update(let update):
producer.value?.traceID?._asyncNinja_log("flatMapping update \(update)")
producer.value?.update(try transform(context, update), from: originalExecutor)
case .completion(let completion):
producer.value?.traceID?._asyncNinja_log("completion with \(completion)")
producer.value?.complete(completion, from: originalExecutor)
}
}
}
/// Applies transformation to update values of the channel.
///
/// - Parameters:
/// - executor: to execute transform on
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply. Sequence returned from transform
/// will be treated as multiple period values
/// - update: `Update` to transform
/// - Returns: transformed channel
func flatMap<PS: Sequence>(
executor: Executor = .primary,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (_ update: Update) throws -> PS
) -> Channel<PS.Iterator.Element, Success> {
// Test: EventSource_MapTests.testFlatMapArray
return makeProducer(
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙flatMapp")
) { (event, producer, originalExecutor) in
switch event {
case .update(let update):
producer.value?.traceID?._asyncNinja_log("flatMapping from \(update)")
producer.value?.update(try transform(update), from: originalExecutor)
case .completion(let completion):
producer.value?.traceID?._asyncNinja_log("completion with \(completion)")
producer.value?.complete(completion, from: originalExecutor)
}
}
}
}
// MARK: - map completion
public extension EventSource {
/// Applies transformation to a completion of EventSource.
///
/// - Parameters:
/// - context: `ExectionContext` to apply transformation in
/// - executor: override of `ExecutionContext`s executor.
/// Keep default value of the argument unless you need to override
/// an executor provided by the context
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply
/// - strongContext: context restored from weak reference to specified context
/// - value: `ChannelValue` to transform. May be either update or completion
/// - Returns: transformed channel
func mapCompletion<Transformed, C: ExecutionContext>(
context: C,
executor: Executor? = nil,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (C, Fallible<Success>) throws -> Transformed
) -> Channel<Update, Transformed> {
return makeProducer(
context: context,
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙mapCompletion")
) { (context, event, producer, originalExecutor) in
switch event {
case let .update(update):
producer.value?.traceID?._asyncNinja_log("update \(update)")
producer.value?.update(update, from: originalExecutor)
case let .completion(completion):
let transformedCompletion = fallible { try transform(context, completion) }
producer.value?.traceID?._asyncNinja_log("completion \(completion)")
producer.value?.traceID?._asyncNinja_log("transformedCompletion \(transformedCompletion)")
producer.value?.complete(transformedCompletion, from: originalExecutor)
}
}
}
/// Applies transformation to a success of EventSource.
///
/// - Parameters:
/// - context: `ExectionContext` to apply transformation in
/// - executor: override of `ExecutionContext`s executor.
/// Keep default value of the argument unless you need to override
/// an executor provided by the context
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply
/// - strongContext: context restored from weak reference to specified context
/// - value: `ChannelValue` to transform. May be either update or completion
/// - Returns: transformed channel
func mapSuccess<Transformed, C: ExecutionContext>(
context: C,
executor: Executor? = nil,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (C, Success) throws -> Transformed
) -> Channel<Update, Transformed> {
return mapCompletion(
context: context,
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize
) { (context, value) -> Transformed in
let success = try value.get()
return try transform(context, success)
}
}
/// Applies transformation to a completion of EventSource.
///
/// - Parameters:
/// - executor: to execute transform on
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply
/// - value: `ChannelValue` to transform. May be either update or completion
/// - Returns: transformed channel
func mapCompletion<Transformed>(
executor: Executor = .primary,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (Fallible<Success>) throws -> Transformed
) -> Channel<Update, Transformed> {
return makeProducer(
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙mapCompletion")
) { (event, producer, originalExecutor) in
switch event {
case let .update(update):
producer.value?.update(update, from: originalExecutor)
producer.value?.traceID?._asyncNinja_log("update \(update)")
case let .completion(completion):
let transformedCompletion = fallible { try transform(completion) }
producer.value?.traceID?._asyncNinja_log("completion \(completion)")
producer.value?.traceID?._asyncNinja_log("transformedCompletion \(transformedCompletion)")
producer.value?.complete(transformedCompletion, from: originalExecutor)
}
}
}
/// Applies transformation to a success of EventSource.
///
/// - Parameters:
/// - executor: to execute transform on
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - transform: to apply
/// - value: `ChannelValue` to transform. May be either update or completion
/// - Returns: transformed channel
func mapSuccess<Transformed>(
executor: Executor = .primary,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ transform: @escaping (Success) throws -> Transformed
) -> Channel<Update, Transformed> {
return mapCompletion(
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize
) { (value) -> Transformed in
let transformedValue = try value.get()
return try transform(transformedValue)
}
}
}
// MARK: - convenient transformations
public extension EventSource {
/// Filters update values of the channel
///
/// - context: `ExectionContext` to apply predicate in
/// - executor: override of `ExecutionContext`s executor.
/// Keep default value of the argument unless you need to override
/// an executor provided by the context
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - predicate: to apply
/// - strongContext: context restored from weak reference to specified context
/// - update: `Update` to transform
/// - Returns: filtered transform
func filter<C: ExecutionContext>(
context: C,
executor: Executor? = nil,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ predicate: @escaping (_ strongContext: C, _ update: Update) throws -> Bool
) -> Channel<Update, Success> {
// Test: EventSource_MapTests.testFilterContextual
traceID?._asyncNinja_log("apply filtering")
return makeProducer(
context: context,
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙filter")
) { (context, event, producer, originalExecutor) in
switch event {
case .update(let update):
do {
if try predicate(context, update) {
producer.value?.traceID?._asyncNinja_log("update \(update)")
producer.value?.update(update, from: originalExecutor)
} else {
producer.value?.traceID?._asyncNinja_log("skipping update \(update)")
}
} catch { producer.value?.fail(error, from: originalExecutor) }
case .completion(let completion):
producer.value?.traceID?._asyncNinja_log("completion \(completion)")
producer.value?.complete(completion, from: originalExecutor)
}
}
}
/// Filters update values of the channel
///
/// - executor: to execute transform on
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - predicate: to apply
/// - update: `Update` to transform
/// - Returns: filtered transform
func filter(
executor: Executor = .primary,
pure: Bool = true,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
_ predicate: @escaping (_ update: Update) throws -> Bool
) -> Channel<Update, Success> {
// Test: EventSource_MapTests.testFilter
traceID?._asyncNinja_log("apply filtering")
return makeProducer(
executor: executor,
pure: pure,
cancellationToken: cancellationToken,
bufferSize: bufferSize,
traceID: traceID?.appending("∙filter")
) { (event, producer, originalExecutor) in
switch event {
case .update(let update):
do {
if try predicate(update) {
producer.value?.traceID?._asyncNinja_log("update \(update)")
producer.value?.update(update, from: originalExecutor)
} else {
producer.value?.traceID?._asyncNinja_log("skipping update \(update)")
}
} catch { producer.value?.fail(error, from: originalExecutor) }
case .completion(let completion):
producer.value?.traceID?._asyncNinja_log("completion \(completion)")
producer.value?.complete(completion, from: originalExecutor)
}
}
}
}
public extension EventSource where Update: _Fallible {
/// makes channel of unsafely unwrapped optional Updates
var unsafelyUnwrapped: Channel<Update.Success, Success> {
return map(executor: .immediate) { $0.maybeSuccess! }
}
/// makes channel of unsafely unwrapped optional Updates
var unwrapped: Channel<Update.Success, Success> {
func transform(update: Update) throws -> Update.Success {
return try update.get()
}
return map(executor: .immediate, transform)
}
}
|
mit
|
242a5c339c3dd7881c487d56fe77a261
| 40.430473 | 98 | 0.68033 | 4.711018 | false | false | false | false |
exponent/exponent
|
packages/expo-dev-menu/ios/UITests/UIView+DevMenuExtension.swift
|
2
|
182
|
import UIKit
extension UIView {
func isVisible() -> Bool {
return isHidden == false && window != nil && bounds.isEmpty == false && bounds.width > 0 && bounds.height > 0
}
}
|
bsd-3-clause
|
47cb6e1aac4b0984800a60332cc79187
| 25 | 113 | 0.626374 | 3.956522 | false | false | false | false |
Valine/mr-inspiration
|
ProjectChartSwift/SongView.swift
|
2
|
1074
|
//
// SongView.swift
// Mr. Inspiration
//
// Created by Lukas Valine on 12/1/15.
// Copyright © 2015 Lukas Valine. All rights reserved.
//
import UIKit
class SongView: UIView { required init?(coder aDecoder: NSCoder) { fatalError("songList error") }
let songData: UILabel = UILabel()
var measures: Array<MeasureView> = [MeasureView]()
var scrollView = UIScrollView()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.lightGrayColor()
songData.frame = CenteredRect.centerFrame(frame.width - 50, height: 100, y: 50)
songData.numberOfLines = 5
songData.textColor = UIColor.blackColor()
songData.font = songData.font.fontWithSize(20)
scrollView.addSubview(songData)
scrollView.scrollIndicatorInsets = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
scrollView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
self.addSubview(scrollView)
}
}
|
gpl-2.0
|
d6780353f4e0d0fa6c6f676848e27e1b
| 25.825 | 97 | 0.628145 | 4.111111 | false | false | false | false |
roberthein/TinyConstraints
|
Example/TinyConstraints/Sources/MetricView.swift
|
1
|
2619
|
import Foundation
import UIKit
import TinyConstraints
class MetricView: UIView {
var arrowColor: UIColor = .white {
didSet {
subviews.forEach {
$0.tintColor = arrowColor
$0.layer.sublayers?.compactMap { $0 as? CAShapeLayer }.forEach {
$0.strokeColor = arrowColor.cgColor
}
}
label.textColor = arrowColor
setNeedsDisplay()
}
}
lazy var label: UILabel = {
let view = UILabel()
view.textColor = arrowColor
view.font = UIFont.systemFont(ofSize: 20, weight: .bold)
return view
}()
let imageSize = CGSize(width: 8, height: 10)
required init() {
super.init(frame: .zero)
let rightArrow = UIImageView(image: UIImage(named: "arrow_right")?.withRenderingMode(.alwaysTemplate))
rightArrow.tintColor = arrowColor
let leftArrow = UIImageView(image: UIImage(named: "arrow_left")?.withRenderingMode(.alwaysTemplate))
leftArrow.tintColor = arrowColor
let lineLeft = UIView()
lineLeft.layer.drawLine(from: CGPoint(x: 0, y: imageSize.height / 2), to: CGPoint(x: 2000, y: imageSize.height / 2), color: arrowColor, dashed: true)
lineLeft.clipsToBounds = true
let lineRight = UIView()
lineRight.layer.drawLine(from: CGPoint(x: 0, y: imageSize.height / 2), to: CGPoint(x: 2000, y: imageSize.height / 2), color: arrowColor, dashed: true)
lineRight.clipsToBounds = true
addSubview(rightArrow)
addSubview(leftArrow)
addSubview(lineLeft)
addSubview(lineRight)
addSubview(label)
rightArrow.size(imageSize)
rightArrow.rightToSuperview(offset: -2)
rightArrow.centerYToSuperview()
leftArrow.size(imageSize)
leftArrow.leftToSuperview(offset: 2)
leftArrow.centerYToSuperview()
lineLeft.leftToRight(of: leftArrow)
lineLeft.rightToLeft(of: label, offset: -2)
lineLeft.height(imageSize.height)
lineLeft.centerYToSuperview()
lineRight.leftToRight(of: label, offset: 2)
lineRight.rightToLeft(of: rightArrow)
lineRight.height(imageSize.height)
lineRight.centerYToSuperview()
label.topToSuperview()
label.bottomToSuperview()
label.centerXToSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
cf31b155d008f78dbe8e7685f12d1db1
| 31.7375 | 158 | 0.600229 | 4.779197 | false | false | false | false |
atl009/WordPress-iOS
|
WordPressKit/WordPressKit/RemotePublicizeConnection.swift
|
2
|
706
|
import Foundation
@objc open class RemotePublicizeConnection: NSObject {
open var connectionID: NSNumber = 0
open var dateIssued = Date()
open var dateExpires: Date? = nil
open var externalID = ""
open var externalName = ""
open var externalDisplay = ""
open var externalProfilePicture = ""
open var externalProfileURL = ""
open var externalFollowerCount: NSNumber = 0
open var keyringConnectionID: NSNumber = 0
open var keyringConnectionUserID: NSNumber = 0
open var label = ""
open var refreshURL = ""
open var service = ""
open var shared = false
open var status = ""
open var siteID: NSNumber = 0
open var userID: NSNumber = 0
}
|
gpl-2.0
|
fb1b60a17536e37d903510c130dfc22d
| 31.090909 | 54 | 0.675637 | 4.468354 | false | false | false | false |
zerozheng/zhibo
|
Source/Network/StringExtension.swift
|
1
|
1942
|
//
// StringExtension.swift
// zhiboApp
//
// Created by zero on 17/2/23.
// Copyright © 2017年 zero. All rights reserved.
//
import Foundation
extension String {
var url: URL? {
return URL(string: self)
}
var scheme: String? {
return url?.scheme
}
var host: String? {
return url?.host
}
var port: Int? {
return url?.port
}
var app: String? {
guard var path = url?.path else {
return nil
}
if path.hasPrefix("/") {
path = path.substring(from: index(after: path.startIndex))
}
return path.components(separatedBy: "/").first
}
var playPath: String? {
/*
guard var path = url?.path else {
return nil
}
if path.hasPrefix("/") {
path = path.substring(from: index(after: path.startIndex))
}
var components = path.components(separatedBy: "/")
guard components.count > 1 else {
return nil
}
return components[1]
*/
guard let path = url?.path, let appName = app else {
return nil
}
let appPath = "/\(appName)/"
if path.hasPrefix(appPath) {
return path.substring(from: appPath.endIndex)
}else{
return nil
}
}
func rtmpLink() throws -> String {
var connectUrl: String = ""
connectUrl += (self.scheme ?? "rtmp")
if let host = self.host {
connectUrl += "://\(host)"
} else {
throw RTMPError.urlPathError(reason: .hostNotExists)
}
if let port = self.port, port > 0 {
connectUrl += ":\(port)"
}
if let appName = self.app {
connectUrl += "/\(appName)"
}
return connectUrl
}
}
|
mit
|
8309b60cf06e3f7589e611b4839ddc74
| 21.287356 | 70 | 0.479113 | 4.488426 | false | false | false | false |
wujianguo/YouPlay-iOS
|
YouPlay-iOS/PhotoOperations.swift
|
1
|
2001
|
//
// PhotoOperations.swift
// YouPlay-iOS
//
// Created by wujianguo on 16/1/5.
// Copyright © 2016年 wujianguo. All rights reserved.
//
import UIKit
class PendingOperations {
lazy var downloadsInProgress = [NSIndexPath: NSOperation]()
lazy var downloadQueue: NSOperationQueue = {
var queue = NSOperationQueue()
queue.name = "Download queue"
// queue.maxConcurrentOperationCount = 1
return queue
}()
lazy var filtrationsInProgress = [NSIndexPath: NSOperation]()
lazy var filtrationQueue: NSOperationQueue = {
var queue = NSOperationQueue()
queue.name = "Image Filtration queue"
// queue.maxConcurrentOperationCount = 1
return queue
}()
}
class PhotoRecord {
let url: NSURL
let bounds: CGRect
var image: UIImage?
var color: UIColor?
init(bounds: CGRect, url: NSURL) {
self.bounds = bounds
self.url = url
}
}
class ImageDownloader: NSOperation {
let photoRecord: PhotoRecord
init(photoRecord: PhotoRecord) {
self.photoRecord = photoRecord
}
override func main() {
guard !cancelled else { return }
if let img = Util.imageCache.objectForKey(photoRecord.url) as? UIImage {
photoRecord.image = img
return
}
let imageData = NSData(contentsOfURL: photoRecord.url)
guard !cancelled && imageData?.length > 0 else { return }
if let img = UIImage(data: imageData!) {
Util.imageCache.setObject(img, forKey: photoRecord.url)
photoRecord.image = img
}
}
}
class ImageFiltration: NSOperation {
let photoRecord: PhotoRecord
init(photoRecord: PhotoRecord) {
self.photoRecord = photoRecord
}
override func main () {
guard !cancelled else { return }
if let image = photoRecord.image {
photoRecord.color = image.darkEffectColor(photoRecord.bounds)
}
}
}
|
gpl-2.0
|
1990d27211cc1f9bd3395e1b6c0ac370
| 23.975 | 80 | 0.622122 | 4.430155 | false | false | false | false |
Darr758/Swift-Algorithms-and-Data-Structures
|
Algorithms/FindCommonAncestorInBinTree.playground/Contents.swift
|
1
|
1001
|
//Fnd the first common ancestor of two nodes in a binary tree
class TreeNode<T>{
var value:T
init(_ value:T){
self.value = value
}
var left:TreeNode?
var right:TreeNode?
}
func findAncestor<T>(root:TreeNode<T>, nodeOne:TreeNode<T>, nodeTwo:TreeNode<T>) -> TreeNode<T>{
if let left = root.left{
if belowNode(root:left, node:nodeOne) && belowNode(root:left, node:nodeTwo){
return findAncestor(root:left, nodeOne:nodeOne, nodeTwo:nodeTwo)
}
}
if let right = root.right{
if belowNode(root:right, node:nodeOne) && belowNode(root:right, node:nodeTwo){
return findAncestor(root:right, nodeOne:nodeOne, nodeTwo:nodeTwo)
}
}
return root
}
func belowNode<T>(root:TreeNode<T>?, node:TreeNode<T>) -> Bool{
guard let root = root else {return false}
if root === node{
return true
}
return belowNode(root:root.left, node:node) || belowNode(root:root.right, node:node)
}
|
mit
|
c3bb57a4d7519fcfc9eeb46869db7376
| 27.6 | 96 | 0.629371 | 3.428082 | false | false | false | false |
DanielCech/Vapor-Catalogue
|
Sources/App/Models/Artist.swift
|
1
|
1039
|
//
// Artist.swift
// Catalog
//
// Created by Dan on 18.01.17.
//
//
import Foundation
import Vapor
import HTTP
final class Artist: Model {
var id: Node?
var exists: Bool = false
var name: String
init(name: String) {
self.id = nil
self.name = name
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
name = try node.extract("name")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"name": name
])
}
static func prepare(_ database: Database) throws {
try database.create("artists") { artists in
artists.id()
artists.string("name")
}
}
static func revert(_ database: Database) throws {
try database.delete("artists")
}
}
extension Artist {
func albums() throws -> [Album] {
return try children(nil, Album.self).all()
}
}
|
mit
|
3a1dbbfe75e37b54cc7a6fe6a1f877ff
| 16.913793 | 54 | 0.517806 | 4.090551 | false | false | false | false |
pietrocaselani/Trakt-Swift
|
Trakt/Models/Sync/SyncItems.swift
|
1
|
1247
|
public struct SyncItems: Codable {
public let movies: [SyncMovie]?
public let shows: [SyncShow]?
public let episodes: [SyncEpisode]?
public let ids: [Int]?
private enum CodingKeys: String, CodingKey {
case movies, shows, episodes, ids
}
public init(movies: [SyncMovie]? = nil, shows: [SyncShow]? = nil, episodes: [SyncEpisode]? = nil, ids: [Int]? = nil) {
self.movies = movies
self.shows = shows
self.episodes = episodes
self.ids = ids
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.movies = try container.decodeIfPresent([SyncMovie].self, forKey: .movies)
self.shows = try container.decodeIfPresent([SyncShow].self, forKey: .shows)
self.episodes = try container.decodeIfPresent([SyncEpisode].self, forKey: .episodes)
self.ids = try container.decodeIfPresent([Int].self, forKey: .ids)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(movies, forKey: .movies)
try container.encodeIfPresent(shows, forKey: .shows)
try container.encodeIfPresent(episodes, forKey: .episodes)
try container.encodeIfPresent(ids, forKey: .ids)
}
}
|
unlicense
|
0c6d0b14c6717e2f726d4dd08c52ca29
| 33.638889 | 120 | 0.723336 | 3.71131 | false | false | false | false |
adamhartford/SwiftR
|
SwiftR iOS Demo/DemoViewController.swift
|
1
|
5098
|
//
// DemoViewController.swift
// SwiftR
//
// Created by Adam Hartford on 5/26/16.
// Copyright © 2016 Adam Hartford. All rights reserved.
//
import UIKit
import SwiftR
class DemoViewController: UIViewController {
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var chatTextView: UITextView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var startButton: UIBarButtonItem!
var chatHub: Hub!
var connection: SignalR!
var name: String!
override func viewDidLoad() {
super.viewDidLoad()
connection = SignalR("http://swiftr.azurewebsites.net")
connection.useWKWebView = true
connection.signalRVersion = .v2_2_0
chatHub = Hub("chatHub")
chatHub.on("broadcastMessage") { [weak self] args in
if let name = args?[0] as? String, let message = args?[1] as? String, let text = self?.chatTextView.text {
self?.chatTextView.text = "\(text)\n\n\(name): \(message)"
}
}
connection.addHub(chatHub)
// SignalR events
connection.starting = { [weak self] in
self?.statusLabel.text = "Starting..."
self?.startButton.isEnabled = false
self?.sendButton.isEnabled = false
}
connection.reconnecting = { [weak self] in
self?.statusLabel.text = "Reconnecting..."
self?.startButton.isEnabled = false
self?.sendButton.isEnabled = false
}
connection.connected = { [weak self] in
print("Connection ID: \(self!.connection.connectionID!)")
self?.statusLabel.text = "Connected"
self?.startButton.isEnabled = true
self?.startButton.title = "Stop"
self?.sendButton.isEnabled = true
}
connection.reconnected = { [weak self] in
self?.statusLabel.text = "Reconnected. Connection ID: \(self!.connection.connectionID!)"
self?.startButton.isEnabled = true
self?.startButton.title = "Stop"
self?.sendButton.isEnabled = true
}
connection.disconnected = { [weak self] in
self?.statusLabel.text = "Disconnected"
self?.startButton.isEnabled = true
self?.startButton.title = "Start"
self?.sendButton.isEnabled = false
}
connection.connectionSlow = { print("Connection slow...") }
connection.error = { [weak self] error in
print("Error: \(String(describing: error))")
// Here's an example of how to automatically reconnect after a timeout.
//
// For example, on the device, if the app is in the background long enough
// for the SignalR connection to time out, you'll get disconnected/error
// notifications when the app becomes active again.
if let source = error?["source"] as? String, source == "TimeoutException" {
print("Connection timed out. Restarting...")
self?.connection.start()
}
}
connection.start()
}
override func viewDidAppear(_ animated: Bool) {
let alertController = UIAlertController(title: "Name", message: "Please enter your name", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { [weak self] _ in
self?.name = alertController.textFields?.first?.text
if let name = self?.name , name.isEmpty {
self?.name = "Anonymous"
}
alertController.textFields?.first?.resignFirstResponder()
}
alertController.addTextField { textField in
textField.placeholder = "Your Name"
}
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func send(_ sender: AnyObject?) {
if let hub = chatHub, let message = messageTextField.text {
do {
try hub.invoke("send", arguments: [name, message])
} catch {
print(error)
}
}
messageTextField.resignFirstResponder()
}
@IBAction func startStop(_ sender: AnyObject?) {
if startButton.title == "Start" {
connection.start()
} else {
connection.stop()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
ae1e49e5ba53ca3eef9f754e4f13125b
| 32.98 | 121 | 0.584265 | 5.071642 | false | false | false | false |
SemperIdem/SwiftMarkdownParser
|
Pod/Classes/UIWebView+Markdown.swift
|
1
|
1851
|
//
// UIWebView+Markdown.swift
// SwiftMarkdownParserExamples
//
// Created by Semper_Idem on 16/3/21.
// Copyright © 2016年 星夜暮晨. All rights reserved.
//
import UIKit
public extension UIWebView {
/// Load Markdown HTML String
public func loadMarkdownString(markdown: String, atBaseURL baseURL: NSURL? = nil, withStyleSheet sheet: String? = nil) {
let URL = baseURL ?? NSURL(fileURLWithPath: NSBundle.mainBundle().bundlePath)
let html = MarkdownParse.convertMarkdownString(markdown)
let fullHTMLPage: String
if let sheet = sheet {
fullHTMLPage = "<html><head><meta name=\"viewport\" content=\"width=device-width\"><style type=\"text/css\">\(sheet)</style></head><body>\(html)</body></html>"
} else {
fullHTMLPage = "<html><head><meta name=\"viewport\" content=\"width=device-width\"><style type=\"text/css\">body { font-family:sans-serif; font-size:10pt; }</style></head><body>\(html)</body></html>"
}
loadHTMLString(fullHTMLPage, baseURL: URL)
}
/// Load Markdown HTML String
public func loadMarkdownString(markdown: String, atBaseURL baseURL: NSURL? = nil, withStylesheetFile filename: String, andSurroundedByHTML surround: String? = nil) {
let URL = baseURL ?? NSURL(fileURLWithPath: NSBundle.mainBundle().bundlePath)
let html = MarkdownParse.convertMarkdownString(markdown)
let fullHTMLPage: String
if let surround = surround {
fullHTMLPage = surround + filename + html
} else {
fullHTMLPage = "<html><head><meta name=\"viewport\" content=\"width=device-width\"><link rel=\"stylesheet\" href=\"\(filename)\" /></head><body>\(html)</body></html>"
}
loadHTMLString(fullHTMLPage, baseURL: URL)
}
}
|
mit
|
eea676a3eb43139a3bda01140fc430a3
| 40.818182 | 211 | 0.638587 | 4.269142 | false | false | false | false |
artemkalinovsky/JSQCoreDataKit
|
JSQCoreDataKit/JSQCoreDataKit/CoreDataModel.swift
|
1
|
4977
|
//
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://www.jessesquires.com/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright (c) 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
import CoreData
/// An instance of `CoreDataModel` represents a Core Data model.
/// It provides the model and store URLs as well as functions for interacting with the store.
public struct CoreDataModel: Printable {
// MARK: Properties
/// The name of the Core Data model resource.
public let name: String
/// The bundle in which the model is located.
public let bundle: NSBundle
/// The file URL specifying the directory in which the store is located.
public let storeDirectoryURL: NSURL
/// The file URL specifying the full path to the store.
public var storeURL: NSURL {
get {
return storeDirectoryURL.URLByAppendingPathComponent(databaseFileName)
}
}
/// The file URL specifying the model file in the bundle specified by `bundle`.
public var modelURL: NSURL {
get {
let url = bundle.URLForResource(name, withExtension: "momd")
assert(url != nil, "*** Error loading resource for model named \(name) at url: \(url)")
return url!
}
}
/// The database file name for the store.
public var databaseFileName: String {
get {
return name + ".sqlite"
}
}
/// The managed object model for the model specified by `name`.
public var managedObjectModel: NSManagedObjectModel {
get {
let model = NSManagedObjectModel(contentsOfURL: modelURL)
assert(model != nil, "*** Error loading managed object model at url: \(modelURL)")
return model!
}
}
/// Queries the meta data for the persistent store specified by the receiver and returns whether or not a migration is needed.
/// Returns `true` if the store requires a migration, `false` otherwise.
public var modelStoreNeedsMigration: Bool {
get {
var error: NSError?
if let sourceMetaData = NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(nil, URL: storeURL, error: &error) {
return !managedObjectModel.isConfiguration(nil, compatibleWithStoreMetadata: sourceMetaData)
}
println("*** \(toString(CoreDataModel.self)) ERROR: [\(__LINE__)] \(__FUNCTION__) Failure checking persistent store coordinator meta data: \(error)")
return false
}
}
// MARK: Initialization
/// Constructs new `CoreDataModel` instance with the specified name and bundle.
///
/// :param: name The name of the Core Data model.
/// :param: bundle The bundle in which the model is located. The default parameter value is `NSBundle.mainBundle()`.
/// :param: storeDirectoryURL The directory in which the model is located. The default parameter value is the user's documents directory.
///
/// :returns: A new `CoreDataModel` instance.
public init(name: String, bundle: NSBundle = NSBundle.mainBundle(), storeDirectoryURL: NSURL = documentsDirectoryURL()) {
self.name = name
self.bundle = bundle
self.storeDirectoryURL = storeDirectoryURL
}
// MARK: Methods
/// Removes the existing model store specfied by the receiver.
///
/// :returns: A tuple value containing a boolean to indicate success and an error object if an error occurred.
public func removeExistingModelStore() -> (success:Bool, error:NSError?) {
var error: NSError?
let fileManager = NSFileManager.defaultManager()
if let storePath = storeURL.path {
if fileManager.fileExistsAtPath(storePath) {
let success = fileManager.removeItemAtURL(storeURL, error: &error)
if !success {
println("*** \(toString(CoreDataModel.self)) ERROR: [\(__LINE__)] \(__FUNCTION__) Could not remove model store at url: \(error)")
}
return (success, error)
}
}
return (false, nil)
}
// MARK: Printable
/// :nodoc:
public var description: String {
get {
return "<\(toString(CoreDataModel.self)): name=\(name), needsMigration=\(modelStoreNeedsMigration), databaseFileName=\(databaseFileName), modelURL=\(modelURL), storeURL=\(storeURL)>"
}
}
}
// MARK: Private
private func documentsDirectoryURL() -> NSURL {
var error: NSError?
let url = NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true, error: &error)
assert(url != nil, "*** Error finding documents directory: \(error)")
return url!
}
|
mit
|
69317de72201ffd61485998a5f904ede
| 34.805755 | 194 | 0.641551 | 4.85561 | false | false | false | false |
benlangmuir/swift
|
test/Interop/Cxx/enum/anonymous-with-swift-name-module-interface.swift
|
5
|
4885
|
// RUN: %target-swift-ide-test -print-module -module-to-print=AnonymousWithSwiftName -I %S/Inputs -source-filename=x -enable-experimental-cxx-interop | %FileCheck %s
// CHECK: @available(*, unavailable, message: "Not available in Swift")
// CHECK: typealias SOColorMask = UInt32
// CHECK: struct SOColorMask : OptionSet, @unchecked Sendable {
// CHECK: init(rawValue: UInt32)
// CHECK: let rawValue: UInt32
// CHECK: typealias RawValue = UInt32
// CHECK: typealias Element = SOColorMask
// CHECK: typealias ArrayLiteralElement = SOColorMask
// CHECK: static var red: SOColorMask { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "red")
// CHECK: static var Red: SOColorMask { get }
// CHECK: static var green: SOColorMask { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "green")
// CHECK: static var Green: SOColorMask { get }
// CHECK: static var blue: SOColorMask { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "blue")
// CHECK: static var Blue: SOColorMask { get }
// CHECK: static var all: SOColorMask { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "all")
// CHECK: static var All: SOColorMask { get }
// CHECK: }
// CHECK: @available(*, unavailable, message: "Not available in Swift")
// CHECK: typealias CFColorMask = UInt32
// CHECK: struct CFColorMask : OptionSet {
// CHECK: init(rawValue: UInt32)
// CHECK: let rawValue: UInt32
// CHECK: typealias RawValue = UInt32
// CHECK: typealias Element = CFColorMask
// CHECK: typealias ArrayLiteralElement = CFColorMask
// CHECK: static var red: CFColorMask { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "red")
// CHECK: static var Red: CFColorMask { get }
// CHECK: static var green: CFColorMask { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "green")
// CHECK: static var Green: CFColorMask { get }
// CHECK: static var blue: CFColorMask { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "blue")
// CHECK: static var Blue: CFColorMask { get }
// CHECK: static var all: CFColorMask { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "all")
// CHECK: static var All: CFColorMask { get }
// CHECK: }
// CHECK: func useSOColorMask(_ mask: SOColorMask) -> SOColorMask
// CHECK: func useCFColorMask(_ mask: CFColorMask) -> CFColorMask
// Test rename with "swift_name" attr:
// CHECK: struct ParentStruct
// CHECK: @available(swift, obsoleted: 3, renamed: "ParentStruct.childFn(self:)")
// CHECK: func renameCFColorMask(_ parent: ParentStruct) -> CFColorMask
// CHECK: extension ParentStruct {
// CHECK: func childFn() -> CFColorMask
// CHECK: @available(*, unavailable, message: "Not available in Swift")
// CHECK: typealias NewName = UInt32
// CHECK: struct NewName : OptionSet, @unchecked Sendable {
// CHECK: init(rawValue: UInt32)
// CHECK: let rawValue: UInt32
// CHECK: typealias RawValue = UInt32
// CHECK: typealias Element = ParentStruct.NewName
// CHECK: typealias ArrayLiteralElement = ParentStruct.NewName
// CHECK: static var one: ParentStruct.NewName { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "one")
// CHECK: static var One: ParentStruct.NewName { get }
// CHECK: static var two: ParentStruct.NewName { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "two")
// CHECK: static var Two: ParentStruct.NewName { get }
// CHECK: }
// CHECK: }
// CHECK: @available(swift, obsoleted: 3, renamed: "ParentStruct.NewName")
// CHECK: @available(*, unavailable, message: "Not available in Swift")
// CHECK: typealias OldName = ParentStruct.NewName
// CHECK: @available(swift, obsoleted: 3, renamed: "ParentStruct.NewName")
// CHECK: typealias OldName = ParentStruct.NewName
// CHECK: @available(*, unavailable, message: "Not available in Swift")
// CHECK: typealias GlobalNewName = UInt32
// CHECK: @available(swift, obsoleted: 3, renamed: "GlobalNewName")
// CHECK: @available(*, unavailable, message: "Not available in Swift")
// CHECK: typealias GlobalOldName = GlobalNewName
// CHECK: struct GlobalNewName : OptionSet, @unchecked Sendable {
// CHECK: init(rawValue: UInt32)
// CHECK: let rawValue: UInt32
// CHECK: typealias RawValue = UInt32
// CHECK: typealias Element = GlobalNewName
// CHECK: typealias ArrayLiteralElement = GlobalNewName
// CHECK: static var one: GlobalNewName { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "one")
// CHECK: static var One: GlobalNewName { get }
// CHECK: static var two: GlobalNewName { get }
// CHECK: @available(swift, obsoleted: 3, renamed: "two")
// CHECK: static var Two: GlobalNewName { get }
// CHECK: }
// CHECK: @available(swift, obsoleted: 3, renamed: "GlobalNewName")
// CHECK: typealias GlobalOldName = GlobalNewName
|
apache-2.0
|
ebd166667fae3da5a91afd851e26496e
| 43.409091 | 165 | 0.680246 | 3.626578 | false | false | false | false |
bnotified/motified-iOS
|
motified/NSDateExtension.swift
|
1
|
1224
|
//
// NSDateExtension.swift
// motified
//
// Created by Giancarlo Anemone on 3/25/15.
// Copyright (c) 2015 Giancarlo Anemone. All rights reserved.
//
import Foundation
extension NSDate {
func isOnSameDayAs(date: NSDate) -> Bool {
return NSDate.areDatesSameDay(self, dateTwo: date)
}
class func areDatesSameDay(dateOne:NSDate,dateTwo:NSDate) -> Bool {
let calender = NSCalendar.currentCalendar()
let flags: NSCalendarUnit = [NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year ]
let compOne: NSDateComponents = calender.components(flags, fromDate: dateOne)
let compTwo: NSDateComponents = calender.components(flags, fromDate: dateTwo);
return (compOne.day == compTwo.day && compOne.month == compTwo.month && compOne.year == compTwo.year);
}
func toLocalTime() -> NSDate {
let tz = NSTimeZone.defaultTimeZone()
let seconds = Double(tz.secondsFromGMT)
return self.dateByAddingTimeInterval(seconds)
}
func toGlobalTime() -> NSDate {
let tz = NSTimeZone.defaultTimeZone()
let seconds = -Double(tz.secondsFromGMT)
return self.dateByAddingTimeInterval(seconds)
}
}
|
mit
|
36602a9abb495dccb1ee4dc1ba070f3a
| 33.027778 | 110 | 0.674837 | 4.27972 | false | false | false | false |
mrdepth/Neocom
|
Legacy/Neocom/Neocom/MailPageInteractor.swift
|
2
|
2403
|
//
// MailPageInteractor.swift
// Neocom
//
// Created by Artem Shimanski on 11/2/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import Futures
import CloudData
import EVEAPI
class MailPageInteractor: TreeInteractor {
typealias Presenter = MailPagePresenter
typealias Content = ESI.Result<Value>
weak var presenter: Presenter?
struct Value {
var headers: [ESI.Mail.Header]
var contacts: [Int64: Contact]
}
required init(presenter: Presenter) {
self.presenter = presenter
}
var api = Services.api.current
func load(cachePolicy: URLRequest.CachePolicy) -> Future<Content> {
return load(from: nil, cachePolicy: cachePolicy)
}
func load(from lastMailID: Int64?, cachePolicy: URLRequest.CachePolicy) -> Future<Content> {
guard let input = presenter?.view?.input, let labelID = input.labelID else { return .init(.failure(NCError.invalidInput(type: type(of: self))))}
let headers = api.mailHeaders(lastMailID: lastMailID, labels: [Int64(labelID)], cachePolicy: cachePolicy)
return headers.then(on: .main) { mails -> Future<Content> in
return self.contacts(for: mails.value).then(on: .main) { contacts -> Content in
return mails.map { Value(headers: $0, contacts: contacts) }
}
}
}
func contacts(for mails: [ESI.Mail.Header]) -> Future<[Int64: Contact]> {
var ids = Set(mails.compactMap { mail in mail.recipients?.map{Int64($0.recipientID)} }.joined())
ids.formUnion(mails.compactMap {$0.from.map{Int64($0)}})
guard !ids.isEmpty else {return .init([:])}
return api.contacts(with: ids)
}
private var didChangeAccountObserver: NotificationObserver?
func configure() {
didChangeAccountObserver = NotificationCenter.default.addNotificationObserver(forName: .didChangeAccount, object: nil, queue: .main) { [weak self] _ in
self?.api = Services.api.current
_ = self?.presenter?.reload(cachePolicy: .useProtocolCachePolicy).then(on: .main) { presentation in
self?.presenter?.view?.present(presentation, animated: true)
}
}
}
func delete(_ mail: ESI.Mail.Header) -> Future<Void> {
guard let mailID = mail.mailID else { return .init(.failure(NCError.invalidArgument(type: type(of: self), function: #function, argument: "mail", value: mail)))}
return api.delete(mailID: Int64(mailID)).then { _ -> Void in}
}
func markRead(_ mail: ESI.Mail.Header) {
_ = api.markRead(mail: mail)
}
}
|
lgpl-2.1
|
e226832778c507dd1a972aafd148eaea
| 33.811594 | 162 | 0.714821 | 3.411932 | false | false | false | false |
dfsilva/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Views/AAMapPinPointView.swift
|
4
|
3261
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
open class AAMapPinPointView: UIView {
let pinView = UIImageView()
let pinPointView = UIImageView()
let pinShadowView = UIImageView()
public init() {
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
pinShadowView.frame = CGRect(x: 43, y: 47, width: 32, height: 39)
pinShadowView.alpha = 0.9
pinShadowView.image = UIImage.bundled("LocationPinShadow.png")
addSubview(pinShadowView)
pinPointView.frame = CGRect(x: 100 / 2 - 2, y: 100 - 18.5, width: 3.5, height: 1.5)
pinPointView.image = UIImage.bundled("LocationPinPoint.png")
addSubview(pinPointView)
pinView.frame = CGRect(x: 100 / 2 - 7, y: 47, width: 13.5, height: 36)
pinView.image = UIImage.bundled("LocationPin.png")
addSubview(pinView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func risePin(_ rised: Bool, animated: Bool) {
self.pinShadowView.layer.removeAllAnimations()
self.pinView.layer.removeAllAnimations()
if animated {
if rised {
UIView.animate(withDuration: 0.2, delay: 0.0, options: .beginFromCurrentState, animations: { () -> Void in
self.pinView.frame = CGRect(x: 100 / 2 - 7, y: 7, width: 13.5, height: 36)
self.pinShadowView.frame = CGRect(x: 87, y: -33, width: 32, height: 39)
}, completion: nil)
} else {
UIView.animate(withDuration: 0.2, delay: 0.0, options: .beginFromCurrentState, animations: { () -> Void in
self.pinView.frame = CGRect(x: 100 / 2 - 7, y: 47, width: 13.5, height: 36)
self.pinShadowView.frame = CGRect(x: 43, y: 47, width: 32, height: 39)
}, completion: { finished in
if !finished {
return
}
UIView.animate(withDuration: 0.1, delay: 0.0, options: .beginFromCurrentState, animations: { () -> Void in
self.pinView.frame = CGRect(x: 100 / 2 - 7, y: 47 + 2, width: 13.5, height: 36 - 2)
}, completion: { (finished) -> Void in
if !finished {
return
}
UIView.animate(withDuration: 0.1, delay: 0.0, options: .beginFromCurrentState, animations: { () -> Void in
self.pinView.frame = CGRect(x: 100 / 2 - 7, y: 47, width: 13.5, height: 36)
}, completion: nil)
})
})
}
} else {
if rised {
self.pinView.frame = CGRect(x: 100 / 2 - 7, y: 7, width: 13.5, height: 36)
self.pinShadowView.frame = CGRect(x: 87, y: -33, width: 32, height: 39)
} else {
self.pinView.frame = CGRect(x: 100 / 2 - 7, y: 47, width: 13.5, height: 36)
self.pinShadowView.frame = CGRect(x: 43, y: 47, width: 32, height: 39)
}
}
}
}
|
agpl-3.0
|
3a6a878780fef192b4e515dcbb84d5e9
| 42.48 | 130 | 0.517633 | 4.020962 | false | false | false | false |
davefoxy/SwiftBomb
|
SwiftBomb/Classes/Networking/SwiftBombRequest.swift
|
1
|
3491
|
//
// SwiftBombRequest.swift
// SwiftBomb
//
// Created by David Fox on 18/04/2016.
// Copyright © 2016 David Fox. All rights reserved.
//
import Foundation
struct SwiftBombRequest {
enum Method: String {
case post = "POST"
case get = "GET"
}
enum ResponseFormat {
case json
case xml
}
enum BaseURLType {
case api
case site
}
let configuration: SwiftBombConfig
let path: String
let method: Method
var responseFormat = ResponseFormat.json
var baseURLType: BaseURLType = .api
fileprivate (set) var urlParameters: [String: AnyObject] = [:]
fileprivate (set) var headers: [String: String] = [:]
fileprivate (set) var body: Data?
init(configuration: SwiftBombConfig, path: String, method: Method, pagination: PaginationDefinition? = nil, sort: SortDefinition? = nil, fields: [String]? = nil) {
self.configuration = configuration
self.path = path
self.method = method
// Add the content type for all requests
headers["Content-Type"] = "application/json"
// Optional pagination
if let pagination = pagination {
addURLParameter("offset", value: "\(pagination.offset)")
addURLParameter("limit", value: "\(pagination.limit)")
}
// Optional sorting
if let sort = sort {
addURLParameter("sort", value: sort.urlParameter())
}
// Optional fields
addFields(fields)
}
mutating func addURLParameter(_ key: String, value: String) {
urlParameters[key] = value as AnyObject
}
mutating func addFields(_ fields: [String]?) {
if let fields = fields {
var fieldsString = fields.joined(separator: ",")
if fieldsString.range(of: "id") == nil {
fieldsString += ",id"
}
urlParameters["field_list"] = fieldsString as AnyObject?
}
}
/// Returns the appropriate NSURLRequest for use in the networking manager
func urlRequest() -> URLRequest {
// Build base URL components
var components = URLComponents()
let baseURL = baseURLType == .api ? configuration.baseAPIURL : configuration.baseSiteURL
components.scheme = baseURL.scheme
components.host = baseURL.host
components.path = "\(baseURL.path)/\(path)"
// Query string
var query = responseFormat == .json ? "format=json&" : "format=xml&"
for (key, value) in urlParameters {
query += "\(key)=\(value)&"
}
query = query.trimmingCharacters(in: CharacterSet(charactersIn: "&"))
components.query = query
// Generate the URL
let url = components.url
// Create the URL request
let urlRequest = NSMutableURLRequest(url: url!)
urlRequest.httpMethod = method.rawValue
// Headers
urlRequest.allHTTPHeaderFields = headers
// User agent (optional)
if let userAgent = configuration.userAgentIdentifier {
urlRequest.setValue(userAgent, forHTTPHeaderField: "User-Agent")
}
// Body
if let body = body {
urlRequest.httpBody = body
}
return urlRequest as URLRequest
}
}
|
mit
|
5579b58e019b687d28001c45818169fc
| 28.327731 | 167 | 0.569054 | 5.036075 | false | true | false | false |
stone-payments/onestap-sdk-ios
|
OnestapSDK/User/API/Entities/ApiPublicProfile.swift
|
1
|
879
|
//
// ApiPublicProfile.swift
// OnestapSDK
//
// Created by Munir Wanis on 29/08/17.
// Copyright © 2017 Stone Payments. All rights reserved.
//
import Foundation
struct ApiPublicProfile: InitializableWithData, InitializableWithJson {
var name: String?
var pictureUrl: String?
init(data: Data?) throws {
guard let data = data,
let jsonObject = try? JSONSerialization.jsonObject(with: data),
let json = jsonObject as? JSON else {
throw NSError.createParseError()
}
try self.init(json: json)
}
init(json: JSON) throws {
self.name = json["name"] as? String
self.pictureUrl = json["pictureUrl"] as? String
}
}
extension ApiPublicProfile {
var publicProfile: PublicProfile {
return PublicProfile(name: self.name, pictureUrl: self.pictureUrl)
}
}
|
apache-2.0
|
05160e7e03065769e13b2494838e86f6
| 24.823529 | 75 | 0.636674 | 4.141509 | false | false | false | false |
Johnykutty/SwiftLint
|
Source/SwiftLintFramework/Rules/ValidDocsRule.swift
|
1
|
12237
|
//
// ValidDocsRule.swift
// SwiftLint
//
// Created by JP Simard on 11/21/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
extension File {
fileprivate func invalidDocOffsets(in dictionary: [String: SourceKitRepresentable]) -> [Int] {
let substructure = dictionary.substructure
let substructureOffsets = substructure.flatMap(invalidDocOffsets)
guard let kind = (dictionary.kind).flatMap(SwiftDeclarationKind.init),
kind != .varParameter,
let offset = dictionary.offset,
let bodyOffset = dictionary.bodyOffset,
let comment = parseDocumentationCommentBody(dictionary, syntaxMap: syntaxMap),
!comment.contains(":nodoc:") else {
return substructureOffsets
}
let declaration = contents.bridge()
.substringWithByteRange(start: offset, length: bodyOffset - offset)!
let hasViolation = missingReturnDocumentation(declaration, comment: comment) ||
superfluousReturnDocumentation(declaration, comment: comment, kind: kind) ||
superfluousOrMissingThrowsDocumentation(declaration, comment: comment) ||
superfluousOrMissingParameterDocumentation(declaration, substructure: substructure,
offset: offset, bodyOffset: bodyOffset,
comment: comment)
return substructureOffsets + (hasViolation ? [offset] : [])
}
}
func superfluousOrMissingThrowsDocumentation(_ declaration: String, comment: String) -> Bool {
guard let outsideBracesMatch = matchOutsideBraces(declaration) else {
return false == !comment.lowercased().contains("- throws:")
}
return outsideBracesMatch.contains(" throws ") ==
!comment.lowercased().contains("- throws:")
}
func declarationReturns(_ declaration: String, kind: SwiftDeclarationKind? = nil) -> Bool {
if let kind = kind, SwiftDeclarationKind.variableKinds().contains(kind) {
return true
}
guard let outsideBracesMatch = matchOutsideBraces(declaration) else {
return false
}
return outsideBracesMatch.contains("->")
}
func matchOutsideBraces(_ declaration: String) -> NSString? {
guard let outsideBracesMatch =
regex("(?:\\)(\\s*\\w*\\s*)*((\\s*->\\s*)(\\(.*\\))*(?!.*->)[^()]*(\\(.*\\))*)?\\s*\\{)")
.matches(in: declaration, options: [],
range: NSRange(location: 0, length: declaration.bridge().length)).first else {
return nil
}
return declaration.bridge().substring(with: outsideBracesMatch.range).bridge()
}
func declarationIsInitializer(_ declaration: String) -> Bool {
let range = NSRange(location: 0, length: declaration.bridge().length)
return !regex("^((.+)?\\s+)?init\\?*\\(.*\\)")
.matches(in: declaration, options: [], range: range).isEmpty
}
func commentHasBatchedParameters(_ comment: String) -> Bool {
return comment.lowercased().contains("- parameters:")
}
func commentReturns(_ comment: String) -> Bool {
return comment.lowercased().contains("- returns:") ||
comment.range(of: "Returns")?.lowerBound == comment.startIndex
}
func missingReturnDocumentation(_ declaration: String, comment: String) -> Bool {
guard !declarationIsInitializer(declaration) else {
return false
}
return declarationReturns(declaration) && !commentReturns(comment)
}
func superfluousReturnDocumentation(_ declaration: String, comment: String,
kind: SwiftDeclarationKind) -> Bool {
guard !declarationIsInitializer(declaration) else {
return false
}
return !declarationReturns(declaration, kind: kind) && commentReturns(comment)
}
func superfluousOrMissingParameterDocumentation(_ declaration: String,
substructure: [[String: SourceKitRepresentable]],
offset: Int, bodyOffset: Int,
comment: String) -> Bool {
// This function doesn't handle batched parameters, so skip those.
if commentHasBatchedParameters(comment) { return false }
let parameterNames = substructure.filter {
($0.kind).flatMap(SwiftDeclarationKind.init) == .varParameter
}.filter { subDict in
return subDict.offset.map({ $0 < bodyOffset }) ?? false
}.flatMap {
$0.name
}
let labelsAndParams = parameterNames.map { parameter -> (label: String, parameter: String) in
let fullRange = NSRange(location: 0, length: declaration.utf16.count)
let firstMatch = regex("([^,\\s(]+)\\s+\(parameter)\\s*:")
.firstMatch(in: declaration, options: [], range: fullRange)
if let match = firstMatch {
let label = declaration.bridge().substring(with: match.rangeAt(1))
return (label, parameter)
}
return (parameter, parameter)
}
let optionallyDocumentedParameterCount = labelsAndParams.filter({ $0.0 == "_" }).count
let commentRange = NSRange(location: 0, length: comment.utf16.count)
let commentParameterMatches = regex("- [p|P]arameter ([^:]+)")
.matches(in: comment, options: [], range: commentRange)
let commentParameters = commentParameterMatches.map { match in
return comment.bridge().substring(with: match.rangeAt(1))
}
if commentParameters.count > labelsAndParams.count ||
labelsAndParams.count - commentParameters.count > optionallyDocumentedParameterCount {
return true
}
return !zip(commentParameters, labelsAndParams).filter {
![$1.label, $1.parameter].contains($0)
}.isEmpty
}
public struct ValidDocsRule: ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "valid_docs",
name: "Valid Docs",
description: "Documented declarations should be valid.",
nonTriggeringExamples: [
"/// docs\npublic func a() {}\n",
"/// docs\n/// - parameter param: this is void\npublic func a(param: Void) {}\n",
"/// docs\n/// - parameter label: this is void\npublic func a(label param: Void) {}",
"/// docs\n/// - parameter param: this is void\npublic func a(label param: Void) {}",
"/// docs\n/// - Parameter param: this is void\npublic func a(label param: Void) {}",
"/// docs\n/// - returns: false\npublic func no() -> Bool { return false }",
"/// docs\n/// - Returns: false\npublic func no() -> Bool { return false }",
"/// Returns false\npublic func no() -> Bool { return false }",
"/// Returns false\nvar no: Bool { return false }",
"/// docs\nvar no: Bool { return false }",
"/// docs\n/// - throws: NSError\nfunc a() throws {}",
"/// docs\n/// - Throws: NSError\nfunc a() throws {}",
"/// docs\n/// - parameter param: this is void\n/// - returns: false" +
"\npublic func no(param: (Void -> Void)?) -> Bool { return false }",
"/// docs\n/// - parameter param: this is void" +
"\n///- parameter param2: this is void too\n/// - returns: false",
"\npublic func no(param: (Void -> Void)?, param2: String->Void) -> Bool " +
"{return false}",
"/// docs\n/// - parameter param: this is void" +
"\npublic func no(param: (Void -> Void)?) {}",
"/// docs\n/// - parameter param: this is void" +
"\n///- parameter param2: this is void too" +
"\npublic func no(param: (Void -> Void)?, param2: String->Void) {}",
"/// docs👨👩👧👧\n/// - returns: false\npublic func no() -> Bool { return false }",
"/// docs\n/// - returns: tuple\npublic func no() -> (Int, Int) {return (1, 2)}",
"/// docs\n/// - returns: closure\npublic func no() -> (Void->Void) {}",
"/// docs\n/// - parameter param: this is void" +
"\n/// - parameter param2: this is void too" +
"\nfunc no(param: (Void) -> Void, onError param2: ((NSError) -> Void)? = nil) {}",
"/// docs\n/// - parameter param: this is a void closure" +
"\n/// - parameter param2: this is a void closure too" +
"\n/// - parameter param3: this is a void closure too" +
"\nfunc a(param: () -> Void, param2: (parameter: Int) -> Void, " +
"param3: (parameter: Int) -> Void) {}",
"/// docs\n/// - parameter param: this is a void closure" +
"\n/// - Parameter param2: this is a void closure too" +
"\n/// - Parameter param3: this is a void closure too" +
"\nfunc a(param: () -> Void, param2: (parameter: Int) -> Void, " +
"param3: (parameter: Int) -> Void) {}",
"/// docs\n/// - parameter param: this is a void closure" +
"\n/// - returns: Foo<Void>" +
"\nfunc a(param: () -> Void) -> Foo<Void> {return Foo<Void>}",
"/// docs\n/// - parameter param: this is a void closure" +
"\n/// - returns: Foo<Void>" +
"\nfunc a(param: () -> Void) -> Foo<[Int]> {return Foo<[Int]>}",
"/// docs\n/// - throws: NSError\n/// - returns: false" +
"\nfunc a() throws -> Bool { return true }",
"/// docs\n/// - parameter param: this is a closure\n/// - returns: Bool" +
"\nfunc a(param: (Void throws -> Bool)) -> Bool { return true }"
],
triggeringExamples: [
"/// docs\npublic ↓func a(param: Void) {}\n",
"/// docs\n/// - parameter invalid: this is void\npublic ↓func a(param: Void) {}",
"/// docs\n/// - parameter invalid: this is void\npublic ↓func a(label param: Void) {}",
"/// docs\n/// - parameter invalid: this is void\npublic ↓func a() {}",
"/// docs\npublic ↓func no() -> Bool { return false }",
"/// Returns false\npublic ↓func a() {}",
"/// docs\n/// - throws: NSError\n↓func a() {}",
"/// docs\n↓func a() throws {}",
"/// docs\n/// - parameter param: this is void" +
"\npublic ↓func no(param: (Void -> Void)?) -> Bool { return false }",
"/// docs\n/// - parameter param: this is void" +
"\n///- parameter param2: this is void too" +
"\npublic ↓func no(param: (Void -> Void)?, param2: String->Void) -> " +
"Bool {return false}",
"/// docs\n/// - parameter param: this is void\n/// - returns: false" +
"\npublic ↓func no(param: (Void -> Void)?) {}",
"/// docs\n/// - parameter param: this is void" +
"\n///- parameter param2: this is void too\n/// - returns: false" +
"\npublic ↓func no(param: (Void -> Void)?, param2: String->Void) {}",
"/// docs\npublic func no() -> (Int, Int) {return (1, 2)}",
"/// docs\n/// - parameter param: this is void" +
"\n///- parameter param2: this is void too\n///- returns: closure" +
"\nfunc no(param: (Void) -> Void, onError param2: ((NSError) -> Void)? = nil) {}",
"/// docs\n/// - parameter param: this is a void closure" +
"\nfunc a(param: () -> Void) -> Foo<Void> {return Foo<Void>}",
"/// docs\n/// - parameter param: this is a void closure" +
"\nfunc a(param: () -> Void) -> Foo<[Int]> {return Foo<[Int]>}",
"/// docs\nfunc a() throws -> Bool { return true }"
]
)
public func validate(file: File) -> [StyleViolation] {
return file.invalidDocOffsets(in: file.structure.dictionary).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: $0))
}
}
}
|
mit
|
40e7c02c4ea42096600a6b6b3f52d12f
| 50.669492 | 100 | 0.563966 | 4.355 | false | false | false | false |
Johennes/firefox-ios
|
Client/Frontend/AuthenticationManager/AuthenticationSettingsViewController.swift
|
1
|
13872
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Shared
import SwiftKeychainWrapper
import LocalAuthentication
private let logger = Logger.browserLogger
private func presentNavAsFormSheet(presented: UINavigationController, presenter: UINavigationController?, settings: AuthenticationSettingsViewController?) {
presented.modalPresentationStyle = .FormSheet
presenter?.presentViewController(presented, animated: true, completion: {
if let selectedRow = settings?.tableView.indexPathForSelectedRow {
settings?.tableView.deselectRowAtIndexPath(selectedRow, animated: false)
}
})
}
class TurnPasscodeOnSetting: Setting {
weak var settings: AuthenticationSettingsViewController?
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) {
self.settings = settings as? AuthenticationSettingsViewController
super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOnPasscode),
delegate: delegate)
}
override func onClick(navigationController: UINavigationController?) {
presentNavAsFormSheet(UINavigationController(rootViewController: SetupPasscodeViewController()),
presenter: navigationController,
settings: settings)
}
}
class TurnPasscodeOffSetting: Setting {
weak var settings: AuthenticationSettingsViewController?
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) {
self.settings = settings as? AuthenticationSettingsViewController
super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOffPasscode),
delegate: delegate)
}
override func onClick(navigationController: UINavigationController?) {
presentNavAsFormSheet(UINavigationController(rootViewController: RemovePasscodeViewController()),
presenter: navigationController,
settings: settings)
}
}
class ChangePasscodeSetting: Setting {
weak var settings: AuthenticationSettingsViewController?
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool) {
self.settings = settings as? AuthenticationSettingsViewController
let attributedTitle: NSAttributedString = (enabled ?? false) ?
NSAttributedString.tableRowTitle(AuthenticationStrings.changePasscode) :
NSAttributedString.disabledTableRowTitle(AuthenticationStrings.changePasscode)
super.init(title: attributedTitle,
delegate: delegate,
enabled: enabled)
}
override func onClick(navigationController: UINavigationController?) {
presentNavAsFormSheet(UINavigationController(rootViewController: ChangePasscodeViewController()),
presenter: navigationController,
settings: settings)
}
}
class RequirePasscodeSetting: Setting {
weak var settings: AuthenticationSettingsViewController?
private weak var navigationController: UINavigationController?
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var style: UITableViewCellStyle { return .Value1 }
override var status: NSAttributedString {
// Only show the interval if we are enabled and have an interval set.
let authenticationInterval = KeychainWrapper.defaultKeychainWrapper().authenticationInfo()
if let interval = authenticationInterval?.requiredPasscodeInterval where enabled {
return NSAttributedString.disabledTableRowTitle(interval.settingTitle)
}
return NSAttributedString(string: "")
}
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) {
self.navigationController = settings.navigationController
self.settings = settings as? AuthenticationSettingsViewController
let title = AuthenticationStrings.requirePasscode
let attributedTitle = (enabled ?? true) ? NSAttributedString.tableRowTitle(title) : NSAttributedString.disabledTableRowTitle(title)
super.init(title: attributedTitle,
delegate: delegate,
enabled: enabled)
}
func deselectRow () {
if let selectedRow = self.settings?.tableView.indexPathForSelectedRow {
self.settings?.tableView.deselectRowAtIndexPath(selectedRow, animated: true)
}
}
override func onClick(_: UINavigationController?) {
guard let authInfo = KeychainWrapper.defaultKeychainWrapper().authenticationInfo() else {
navigateToRequireInterval()
return
}
if authInfo.requiresValidation() {
AppAuthenticator.presentAuthenticationUsingInfo(authInfo,
touchIDReason: AuthenticationStrings.requirePasscodeTouchReason,
success: {
self.navigateToRequireInterval()
},
cancel: nil,
fallback: {
AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self)
self.deselectRow()
})
} else {
self.navigateToRequireInterval()
}
}
private func navigateToRequireInterval() {
navigationController?.pushViewController(RequirePasscodeIntervalViewController(), animated: true)
}
}
extension RequirePasscodeSetting: PasscodeEntryDelegate {
@objc func passcodeValidationDidSucceed() {
navigationController?.dismissViewControllerAnimated(true) {
self.navigateToRequireInterval()
}
}
}
class TouchIDSetting: Setting {
private let authInfo: AuthenticationKeychainInfo?
private weak var navigationController: UINavigationController?
private weak var switchControl: UISwitch?
private var touchIDSuccess: (() -> Void)? = nil
private var touchIDFallback: (() -> Void)? = nil
init(
title: NSAttributedString?,
navigationController: UINavigationController? = nil,
delegate: SettingsDelegate? = nil,
enabled: Bool? = nil,
touchIDSuccess: (() -> Void)? = nil,
touchIDFallback: (() -> Void)? = nil) {
self.touchIDSuccess = touchIDSuccess
self.touchIDFallback = touchIDFallback
self.navigationController = navigationController
self.authInfo = KeychainWrapper.defaultKeychainWrapper().authenticationInfo()
super.init(title: title, delegate: delegate, enabled: enabled)
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.selectionStyle = .None
// In order for us to recognize a tap gesture without toggling the switch,
// the switch is wrapped in a UIView which has a tap gesture recognizer. This way
// we can disable interaction of the switch and still handle tap events.
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.on = authInfo?.useTouchID ?? false
control.userInteractionEnabled = false
switchControl = control
let accessoryContainer = UIView(frame: control.frame)
accessoryContainer.addSubview(control)
let gesture = UITapGestureRecognizer(target: self, action: #selector(TouchIDSetting.switchTapped))
accessoryContainer.addGestureRecognizer(gesture)
cell.accessoryView = accessoryContainer
}
@objc private func switchTapped() {
guard let authInfo = authInfo else {
logger.error("Authentication info should always be present when modifying Touch ID preference.")
return
}
if authInfo.useTouchID {
AppAuthenticator.presentAuthenticationUsingInfo(
authInfo,
touchIDReason: AuthenticationStrings.disableTouchReason,
success: self.touchIDSuccess,
cancel: nil,
fallback: self.touchIDFallback
)
} else {
toggleTouchID(enabled: true)
}
}
func toggleTouchID(enabled enabled: Bool) {
authInfo?.useTouchID = enabled
KeychainWrapper.defaultKeychainWrapper().setAuthenticationInfo(authInfo)
switchControl?.setOn(enabled, animated: true)
}
}
class AuthenticationSettingsViewController: SettingsTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
updateTitleForTouchIDState()
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: NotificationPasscodeDidRemove, object: nil)
notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: NotificationPasscodeDidCreate, object: nil)
notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: UIApplicationDidBecomeActiveNotification, object: nil)
tableView.accessibilityIdentifier = "AuthenticationManager.settingsTableView"
}
deinit {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self, name: NotificationPasscodeDidRemove, object: nil)
notificationCenter.removeObserver(self, name: NotificationPasscodeDidCreate, object: nil)
notificationCenter.removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
}
override func generateSettings() -> [SettingSection] {
if let _ = KeychainWrapper.defaultKeychainWrapper().authenticationInfo() {
return passcodeEnabledSettings()
} else {
return passcodeDisabledSettings()
}
}
private func updateTitleForTouchIDState() {
if LAContext().canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) {
navigationItem.title = AuthenticationStrings.touchIDPasscodeSetting
} else {
navigationItem.title = AuthenticationStrings.passcode
}
}
private func passcodeEnabledSettings() -> [SettingSection] {
var settings = [SettingSection]()
let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode)
let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [
TurnPasscodeOffSetting(settings: self),
ChangePasscodeSetting(settings: self, delegate: nil, enabled: true)
])
var requirePasscodeSectionChildren: [Setting] = [RequirePasscodeSetting(settings: self)]
let localAuthContext = LAContext()
if localAuthContext.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) {
requirePasscodeSectionChildren.append(
TouchIDSetting(
title: NSAttributedString.tableRowTitle(
NSLocalizedString("Use Touch ID", tableName: "AuthenticationManager", comment: "List section title for when to use Touch ID")
),
navigationController: self.navigationController,
delegate: nil,
enabled: true,
touchIDSuccess: { [unowned self] in
self.touchIDAuthenticationSucceeded()
},
touchIDFallback: { [unowned self] in
self.fallbackOnTouchIDFailure()
}
)
)
}
let requirePasscodeSection = SettingSection(title: nil, children: requirePasscodeSectionChildren)
settings += [
passcodeSection,
requirePasscodeSection,
]
return settings
}
private func passcodeDisabledSettings() -> [SettingSection] {
var settings = [SettingSection]()
let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode)
let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [
TurnPasscodeOnSetting(settings: self),
ChangePasscodeSetting(settings: self, delegate: nil, enabled: false)
])
let requirePasscodeSection = SettingSection(title: nil, children: [
RequirePasscodeSetting(settings: self, delegate: nil, enabled: false),
])
settings += [
passcodeSection,
requirePasscodeSection,
]
return settings
}
}
extension AuthenticationSettingsViewController {
func refreshSettings(notification: NSNotification) {
updateTitleForTouchIDState()
settings = generateSettings()
tableView.reloadData()
}
}
extension AuthenticationSettingsViewController: PasscodeEntryDelegate {
private func getTouchIDSetting() -> TouchIDSetting? {
guard settings.count >= 2 && settings[1].count >= 2 else {
return nil
}
return settings[1][1] as? TouchIDSetting
}
func touchIDAuthenticationSucceeded() {
getTouchIDSetting()?.toggleTouchID(enabled: false)
}
func fallbackOnTouchIDFailure() {
AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self)
}
@objc func passcodeValidationDidSucceed() {
getTouchIDSetting()?.toggleTouchID(enabled: false)
navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
}
|
mpl-2.0
|
7ca509a9f83a8d6922b7599147a0c5b5
| 39.561404 | 184 | 0.686202 | 6.226212 | false | false | false | false |
rsmoz/swift-package-manager
|
Sources/dep/Package.swift
|
1
|
4441
|
/*
This source file is part of the Swift.org open source project
Copyright 2015 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import struct PackageDescription.Version
import POSIX
import sys
/**
A collection of sources that can be built into products.
For our purposes we always have a local path for the
package because we cannot interpret anything about it
without having cloned and read its manifest first.
In order to get the list of packages that this package
depends on you need to map them from the `manifest`.
*/
public struct Package {
/// the local clone
public let path: String
public let manifest: Manifest
/// the semantic version of this package
public let version: Version
/**
- Returns: The Package or if this doesn’t seem to be a Package, nil.
- Note: Throws if the Package manifest will not parse.
*/
public init?(path: String) throws {
// Packages are git clones
guard let repo = Git.Repo(root: path) else { return nil }
// Packages have origins
guard let origin = repo.origin else { return nil }
// Packages have dirnames of the form foo-X.Y.Z
let parts = path.basename.characters.reduce([""]){ memo, c in
switch c {
case "-", "+":
return memo + [""]
default:
var memo = memo
let foo = memo.removeLast()
return memo + [foo + String(c)]
}
}
guard parts.count >= 2 else { return nil }
func findVersion() -> String {
// support:
// foo-1.2.3
// foo-bar-1.2.3
// foo-bar-1.2.3-beta1
next: for x in 1..<parts.count {
for c in parts[x].characters {
switch c {
case "0","1","2","3","4","5","6","7","8","9",".":
break
default:
continue next
}
}
return parts.dropFirst(x).joinWithSeparator("-")
}
return ""
}
guard let version = Version(findVersion()) else { return nil }
self.version = version
self.manifest = try Manifest(path: Path.join(path, Manifest.filename), baseURL: origin)
self.path = try path.abspath()
}
/// where we came from
public var url: String {
return Git.Repo(root: path)!.origin!
}
/**
The targets of this package, computed using our convention-layout rules
and mapping the result over the Manifest specifications.
*/
public func targets() throws -> [Target] {
if type == .ModuleMap { return [] } //TODO P.O.P.
let computedTargets = try determineTargets(packageName: name, prefix: path)
return try manifest.configureTargets(computedTargets)
}
/// The package’s name; either computed from the url or provided by the Manifest.
public var name: String {
return manifest.package.name ?? Package.name(forURL: url)
}
/// - Returns: The name that would be determined from the provided URL.
static func name(forURL url: String) -> String {
let base = url.basename
switch URL.scheme(url) ?? "" {
case "http", "https", "git", "ssh":
if url.hasSuffix(".git") {
let a = base.startIndex
let b = base.endIndex.advancedBy(-4)
return base[a..<b]
} else {
fallthrough
}
default:
return base
}
}
/// - Returns: The name that would be determined from the provided URL and version.
static func name(forURL url: String, version: Version) -> String {
return "\(name(forURL: url))-\(version)"
}
public enum PackageType {
case Module
case ModuleMap
}
public var type: PackageType {
if Path.join(path, "module.modulemap").isFile {
return .ModuleMap
} else {
return .Module
}
}
}
extension Package: CustomStringConvertible {
public var description: String {
return "Package(\(url) \(version))"
}
}
|
apache-2.0
|
ef553dfa4ef1abb3c860819cdaf76339
| 28.97973 | 95 | 0.570205 | 4.602697 | false | false | false | false |
summer-wu/WordPress-iOS
|
WordPress/Classes/ViewRelated/Notifications/Views/NoteTableHeaderView.swift
|
1
|
2736
|
import Foundation
/**
* @class NoteTableHeaderView
* @brief This class renders a view with top and bottom separators, meant to be used as UITableView
* section header in NotificationsViewController.
*/
@objc public class NoteTableHeaderView : UIView
{
// MARK: - Public Properties
public var title: String? {
set {
// For layout reasons, we need to ensure that the titleLabel uses an exact Paragraph Height!
let unwrappedTitle = newValue?.uppercaseStringWithLocale(NSLocale.currentLocale()) ?? String()
let attributes = Style.sectionHeaderRegularStyle
titleLabel.attributedText = NSAttributedString(string: unwrappedTitle, attributes: attributes)
setNeedsLayout()
}
get {
return titleLabel.text
}
}
public var separatorColor: UIColor? {
set {
layoutView.bottomColor = newValue ?? UIColor.clearColor()
layoutView.topColor = newValue ?? UIColor.clearColor()
}
get {
return layoutView.bottomColor
}
}
// MARK: - Convenience Initializers
public convenience init() {
self.init(frame: CGRectZero)
}
required override public init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
// MARK - Private Helpers
private func setupView() {
NSBundle.mainBundle().loadNibNamed("NoteTableHeaderView", owner: self, options: nil)
addSubview(contentView)
// Make sure the Outlets are loaded
assert(contentView != nil)
assert(layoutView != nil)
assert(imageView != nil)
assert(titleLabel != nil)
// Layout
contentView.setTranslatesAutoresizingMaskIntoConstraints(false)
pinSubviewToAllEdges(contentView)
// Background + Separators
backgroundColor = UIColor.clearColor()
layoutView.backgroundColor = Style.sectionHeaderBackgroundColor
layoutView.bottomVisible = true
layoutView.topVisible = true
}
// MARK: - Aliases
typealias Style = WPStyleGuide.Notifications
// MARK: - Static Properties
public static let headerHeight = CGFloat(26)
// MARK: - Outlets
@IBOutlet private var contentView: UIView!
@IBOutlet private var layoutView: NoteSeparatorsView!
@IBOutlet private var imageView: UIImageView!
@IBOutlet private var titleLabel: UILabel!
}
|
gpl-2.0
|
b6a8a2b15230ec5635798705dc6f5cc3
| 28.73913 | 106 | 0.610746 | 5.527273 | false | false | false | false |
GreenCom-Networks/ios-charts
|
Charts/Classes/Renderers/HorizontalBarChartRenderer.swift
|
1
|
20016
|
//
// 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
#if !os(OSX)
import UIKit
#endif
public class HorizontalBarChartRenderer: BarChartRenderer
{
public override init(dataProvider: BarChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(dataProvider: dataProvider, animator: animator, viewPortHandler: viewPortHandler)
}
public override func drawDataSet(context context: CGContext, dataSet: IBarChartDataSet, index: Int)
{
guard let
dataProvider = dataProvider,
barData = dataProvider.barData,
animator = animator
else { return }
CGContextSaveGState(context)
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let drawBarShadowEnabled: Bool = dataProvider.isDrawBarShadowEnabled
let dataSetOffset = (barData.dataSetCount - 1)
let groupSpace = barData.groupSpace
let groupSpaceHalf = groupSpace / 2.0
let barSpace = dataSet.barSpace
let barSpaceHalf = barSpace / 2.0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(dataSet.axisDependency)
let barWidth: CGFloat = 0.5
let phaseY = animator.phaseY
var barRect = CGRect()
var barShadow = CGRect()
var y: Double
// do the drawing
for j in 0 ..< Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
// calculate the x-position, depending on datasetcount
let x = CGFloat(e.xIndex + e.xIndex * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(e.xIndex) + groupSpaceHalf
let values = e.values
if (!containsStacks || values == nil)
{
y = e.value
let bottom = x - barWidth + barSpaceHalf
let 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
{
let vals = values!
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value
let bottom = x - barWidth + barSpaceHalf
let 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 k in 0 ..< vals.count
{
let value = vals[k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let bottom = x - barWidth + barSpaceHalf
let top = x + barWidth - barSpaceHalf
var right: CGFloat, left: CGFloat
if isInverted
{
left = y >= yStart ? CGFloat(y) : CGFloat(yStart)
right = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
else
{
right = y >= yStart ? CGFloat(y) : CGFloat(yStart)
left = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
// multiply the height of the rect with the phase
right *= phaseY
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.isInBoundsTop(barRect.origin.y + barRect.size.height))
{
// Skip to next bar
break
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsBottom(barRect.origin.y))
{
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)
}
public override func prepareBarHighlight(x x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect, barWidth:CGFloat)
{
let top = x - barWidth + barspacehalf
let bottom = x + barWidth - barspacehalf
let left = CGFloat(y1)
let right = CGFloat(y2)
rect.origin.x = left
rect.origin.y = top
rect.size.width = right - left
rect.size.height = bottom - top
trans.rectValueToPixelHorizontal(&rect, phaseY: animator?.phaseY ?? 1.0)
}
public override func drawValues(context context: CGContext)
{
// if values are drawn
if (passesCheck())
{
guard let
dataProvider = dataProvider,
barData = dataProvider.barData,
animator = animator
else { return }
var dataSets = barData.dataSets
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
let textAlign = NSTextAlignment.Left
let valueOffsetPlus: CGFloat = 5.0
var posOffset: CGFloat
var negOffset: CGFloat
for dataSetIndex in 0 ..< barData.dataSetCount
{
guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue }
if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0
{
continue
}
let isInverted = dataProvider.isInverted(dataSet.axisDependency)
let valueFont = dataSet.valueFont
let yOffset = -valueFont.lineHeight / 2.0
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let phaseY = animator.phaseY
let dataSetCount = barData.dataSetCount
let groupSpace = barData.groupSpace
// if only single values are drawn (sum)
if (!dataSet.isStacked)
{
for j in 0 ..< Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let valuePoint = trans.getTransformedValueHorizontalBarChart(entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace)
if (!viewPortHandler.isInBoundsTop(valuePoint.y))
{
break
}
if (!viewPortHandler.isInBoundsX(valuePoint.x))
{
continue
}
if (!viewPortHandler.isInBoundsBottom(valuePoint.y))
{
continue
}
let val = e.value
let valueText = formatter.stringFromNumber(val)!
// calculate the correct offset depending on the draw position of the value
let 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: valuePoint.x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoint.y + yOffset,
font: valueFont,
align: textAlign,
color: dataSet.valueTextColorAt(j))
}
}
else
{
// if each value of a potential stack should be drawn
for j in 0 ..< Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let valuePoint = trans.getTransformedValueHorizontalBarChart(entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace)
let values = e.values
// we still draw stacked bars, but there is one non-stacked in between
if (values == nil)
{
if (!viewPortHandler.isInBoundsTop(valuePoint.y))
{
break
}
if (!viewPortHandler.isInBoundsX(valuePoint.x))
{
continue
}
if (!viewPortHandler.isInBoundsBottom(valuePoint.y))
{
continue
}
let val = e.value
let valueText = formatter.stringFromNumber(val)!
// calculate the correct offset depending on the draw position of the value
let 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: valuePoint.x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoint.y + yOffset,
font: valueFont,
align: textAlign,
color: dataSet.valueTextColorAt(j))
}
else
{
let vals = values!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for k in 0 ..< vals.count
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: CGFloat(y) * animator.phaseY, y: 0.0))
}
trans.pointValuesToPixel(&transformed)
for k in 0 ..< transformed.count
{
let val = vals[k]
let valueText = formatter.stringFromNumber(val)!
// calculate the correct offset depending on the draw position of the value
let valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus))
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus)
if (isInverted)
{
posOffset = -posOffset - valueTextWidth
negOffset = -negOffset - valueTextWidth
}
let x = transformed[k].x + (val >= 0 ? posOffset : negOffset)
let y = valuePoint.y
if (!viewPortHandler.isInBoundsTop(y))
{
break
}
if (!viewPortHandler.isInBoundsX(x))
{
continue
}
if (!viewPortHandler.isInBoundsBottom(y))
{
continue
}
drawValue(context: context,
value: valueText,
xPos: x,
yPos: y + yOffset,
font: valueFont,
align: textAlign,
color: dataSet.valueTextColorAt(j))
}
}
}
}
}
}
}
internal override func passesCheck() -> Bool
{
guard let dataProvider = dataProvider, barData = dataProvider.barData else { return false }
return CGFloat(barData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleY
}
}
|
apache-2.0
|
02dfe5814d697408d2f8e69984c7b3bb
| 41.771368 | 208 | 0.415168 | 7.125667 | false | false | false | false |
victorchee/NavigationController
|
NavigationAppearance/NavigationAppearance/AppearanceApplyingStrategy.swift
|
1
|
1425
|
//
// AppearanceApplyingStrategy.swift
// NavigationAppearance
//
// Created by qihaijun on 12/2/15.
// Copyright © 2015 VictorChee. All rights reserved.
//
import UIKit
public class AppearanceApplyingStrategy {
public func apply(appearance: Appearance?, toNavigationController navigationiController: UINavigationController, animated: Bool) {
guard let appearance = appearance else {
return
}
let navigationBar = navigationiController.navigationBar
let toolbar = navigationiController.toolbar
if !navigationiController.isNavigationBarHidden {
navigationBar.setBackgroundImage(ImageRenderer.rederImageOfColor(color: appearance.navigationBar.backgroundColor), for: .default)
navigationBar.tintColor = appearance.navigationBar.tintColor
navigationBar.barTintColor = appearance.navigationBar.barTintColor
navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: appearance.navigationBar.tintColor]
}
if !navigationiController.isToolbarHidden {
toolbar?.setBackgroundImage(ImageRenderer.rederImageOfColor(color: appearance.toolBar.backgroundColor), forToolbarPosition: .any, barMetrics: .default)
toolbar?.tintColor = appearance.toolBar.tintColor
toolbar?.barTintColor = appearance.toolBar.barTintColor
}
}
}
|
mit
|
b53792330e7ceb7d366472a00f75d418
| 42.151515 | 163 | 0.724017 | 5.741935 | false | false | false | false |
sodascourse/swift-introduction
|
Swift-Introduction.playground/Pages/Optionals.xcplaygroundpage/Contents.swift
|
1
|
5581
|
/*:
# Optionals
You use **optionals** in situations where a value may be _absent_.
An optional represents two possibilities:
- Either there is a value, and you can unwrap the optional to access that value
- or there isn’t a value at all
We put _a question mark_ (`?`) after the type to indicate that this variable has
an optional value.
*/
/*:
Take following lines as example, converting strings into numbers may fail when
the string is not composed by digits.
*/
let possibleNumber1 = "123"
let convertedNumber1 = Int(possibleNumber1)
let possibleNumber2 = "ABC1"
let convertedNumber2 = Int(possibleNumber2)
//: > Use `option+click` to see the type of `convertedNumber2`.
/*:
## `nil`
We use `nil` to denote that the value is absent.
*/
var concreteNumber: Int = 42
var optionalNumber: Int? = 42
optionalNumber = nil
//concreteNumber = nil // Try to uncomment this line to see what Xcode yields.
func divide(_ dividend: Int, by divisor: Int) -> (quotient: Int, remainder: Int)? {
// We cannot perform division when the `divisor` is '0',
// So we have to check whether divisor is not zero, and returns `nil` when it's zero
// The result is absent because we cannot perform task with given arguments.
guard divisor != 0 else { return nil }
return (dividend/divisor, dividend%divisor)
}
//: --------------------------------------------------------------------------------------------------------------------
/*:
## Unwrapping optional values
We have to unwrap the value from optionals before using it.
### Forced unwrapping
Use `if` statement to check whether it's `nil` or not, and then put a
_exclamation mark_ (`!`) after optionals to force unwrapping it.
We called this way, using the `!` mark, as "forced unwrapping".
*/
func convertToNumber(from input: String, default defaultValue: Int = 0) -> Int {
let convertedOptionalNumber = Int(input)
if convertedOptionalNumber != nil {
// Use the `!` mark to force unwrapping an optional to get its value
// It's like telling Swift: I have checked this value, open the box of optional for me
return convertedOptionalNumber!
} else {
return defaultValue
}
}
convertToNumber(from: "1")
convertToNumber(from: "A")
convertToNumber(from: "A", default: -1)
/*:
You should always check whether the value is nil or not before force unwrapping an optional.
*/
let answerString = "42"
let forcedUnwrappingNumber1 = Int(answerString)!
let helloWorldString = "Hello World!"
//let forcedUnwrappingNumber2 = Int(helloWorldString)!
// Try to uncomment the above line to see what happened.
/*:
### Optional binding
You use optional binding to find out whether an optional contains a value,
and if so, to make that value available as a temporary constant or variable.
Optional binding can be used with `if`, `guard`, and `while` statements to
check for a value inside an optional, and to extract that value into a constant
or variable, as part of a single action.
*/
func parseInt1(_ string: String) -> (isInteger: Bool, value: Int) {
let possibleNumber = Int(string)
if possibleNumber != nil {
let actualNumber = possibleNumber!
return (true, actualNumber)
} else {
return (false, 0)
}
}
/*:
The two lines for checking nil and unwrapping could be merged as one line by
**optional binding**, like:
*/
func parseInt(_ string: String) -> (isInteger: Bool, value: Int) {
let possibleNumber = Int(string)
if let actualNumber = possibleNumber {
return (true, actualNumber)
} else {
return (false, 0)
}
}
parseInt("12")
parseInt("XD")
/*:
The `if` statement in `parseInt(_:)` could be read as
“If the optional Int returned by `Int(possibleNumber)` contains a value,
set a new constant called `actualNumber` to the value contained in the optional.”
> Try to "option+click" on `possibleNumber` and `actualNumber` to see their types.
Also, we use `guard` for optional binding too:
*/
func squareFloat(_ string: String) -> String? {
guard let floatNumber = Float(string) else {
return nil
}
return "\(floatNumber * floatNumber)"
}
squareFloat("16.0")
squareFloat("A")
/*:
The `optional binding` could be chained together, like:
*/
func getAnswer(_ optionalInput: String?) -> String? {
if let concreteString = optionalInput, let answer = Int(concreteString) {
return "The answer is \(answer)."
} else {
return nil
}
}
let optionalString: String? = "42"
getAnswer(optionalString)
func stringPower(base: String, exponent exp: String) -> String? {
guard let baseNumber = Int(base), let expNumber = Int(exp) else {
return nil
}
var result = 1
for _ in 0..<expNumber {
result *= baseNumber
}
return String(result)
}
stringPower(base: "2", exponent: "5")
stringPower(base: "2", exponent: "B")
/*:
### Nil-Coalescing Operator
The _nil-coalescing operator_ (`a ?? b`) unwraps an optional a if it contains a value,
or returns a default value b if a is nil.
The expression `a` is always of an optional type. The expression `b` must match the type
that is stored inside `a`.
*/
let someString1 = "XD"
let someString2 = "42"
let whateverNumber1 = Int(someString1) ?? -1
let whateverNumber2 = Int(someString1) ?? 0
let whateverNumber3 = Int(someString2) ?? -1
//: > Try to "option+click" on `whateverNumber1` and `whateverNumber2` to see their types.
//: ---
//:
//: [<- Previous](@previous) | [Next ->](@next)
//:
|
apache-2.0
|
5b5e4e17b98e62f97fbaa869a9ea1cf8
| 26.736318 | 120 | 0.666906 | 4.028179 | false | false | false | false |
iOS-Connect/HackathonFeb2017
|
PinVid/PinVid/CoreDataManager.swift
|
1
|
1938
|
import Foundation
import UIKit
import CoreData
class CoreDataManager {
static let sharedInstance = CoreDataManager()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "PinVid")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func addClip(startTime: Double, endTime: Double) {
let managedContext = persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "ClipData", in: managedContext)
let clip = NSManagedObject(entity: entity!, insertInto: managedContext)
clip.setValue(startTime, forKey: "start_time")
clip.setValue(endTime, forKey: "end_time")
clip.setValue("TgqiSBxvdws", forKey: "thumbnail_url")
}
///Featch all video when app opens
func fetchClip() -> [NSManagedObject] {
let managedContext = persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "ClipData")
do {
return try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch \(error)")
}
return [NSManagedObject]()
}
}
|
mit
|
08e18317065a7669336a5582bf5c6818
| 28.363636 | 94 | 0.595975 | 5.7 | false | false | false | false |
brentdax/swift
|
test/stdlib/IntegerCompatibility.swift
|
4
|
1729
|
// RUN: %target-build-swift %s -swift-version 4 -typecheck
func byteswap_n(_ a: UInt64) -> UInt64 {
return ((a & 0x00000000000000FF) &<< 56) |
((a & 0x000000000000FF00) &<< 40) |
((a & 0x0000000000FF0000) &<< 24) |
((a & 0x00000000FF000000) &<< 8) |
((a & 0x000000FF00000000) &>> 8) |
((a & 0x0000FF0000000000) &>> 24) |
((a & 0x00FF000000000000) &>> 40) |
((a & 0xFF00000000000000) &>> 56)
}
// expression should not be too complex
func radar31845712(_ i: Int, _ buffer: [UInt8]) {
_ = UInt64(buffer[i])
| (UInt64(buffer[i + 1]) &<< 8)
| (UInt64(buffer[i + 2]) &<< 16)
| (UInt64(buffer[i + 3]) &<< 24)
| (UInt64(buffer[i + 4]) &<< 32)
| (UInt64(buffer[i + 5]) &<< 40)
| (UInt64(buffer[i + 6]) &<< 48)
| (UInt64(buffer[i + 7]) &<< 56)
}
// expression should not be too complex
func radar32149641() {
func from(bigEndian input: UInt32) -> UInt32 {
var val: UInt32 = input
return withUnsafePointer(to: &val) { (ptr: UnsafePointer<UInt32>) -> UInt32 in
return ptr.withMemoryRebound(to: UInt8.self, capacity: 4) { data in
return (UInt32(data[3]) &<< 0) |
(UInt32(data[2]) &<< 8) |
(UInt32(data[1]) &<< 16) |
(UInt32(data[0]) &<< 24)
}
}
}
}
func homogeneousLookingShiftAndAMask(_ i64: Int64) {
_ = (i64 >> 8) & 0xFF
}
func negativeShift(_ u8: UInt8) {
_ = (u8 << -1)
}
func sr5176(description: String = "unambiguous Int32.init(bitPattern:)") {
_ = Int32(bitPattern: 0) // should compile without ambiguity
}
func sr6634(x: UnsafeBufferPointer<UInt8>) -> Int {
return x.lazy.filter { $0 > 127 || $0 == 0 }.count // should be unambiguous
}
|
apache-2.0
|
a6a08741c3b22485a7da06cc7d4dd605
| 29.333333 | 82 | 0.553499 | 3.012195 | false | false | false | false |
auth0/Lock.swift
|
LockTests/StyleSpec.swift
|
1
|
5721
|
// StyleSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Quick
import Nimble
@testable import Lock
class StyleSpec: QuickSpec {
override func spec() {
describe("style Auth0") {
let style = Style.Auth0
it("should have primary color") {
expect(style.primaryColor) == UIColor.a0_orange
}
it("should have background color") {
expect(style.backgroundColor) == UIColor.white
}
it("should not hide title") {
expect(style.hideTitle) == false
}
it("should not hide button title") {
expect(style.hideButtonTitle) == false
}
it("should have text color") {
expect(style.textColor) == UIColor.black
}
it("should have logo") {
expect(style.logo) == UIImage(named: "ic_auth0", in: Lock.bundle)
}
it("should have social seperator text color") {
expect(style.seperatorTextColor) == UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.54)
}
it("should have input field text color") {
expect(style.inputTextColor) == UIColor.black
}
it("should have input field placeholder text color") {
expect(style.inputPlaceholderTextColor) == UIColor(red: 0.780, green: 0.780, blue: 0.804, alpha: 1.00)
}
it("should have input field border color default") {
expect(style.inputBorderColor) == UIColor(red: 0.9333, green: 0.9333, blue: 0.9333, alpha: 1.0)
}
it("should have input field border color invalid") {
expect(style.inputBorderColorError) == UIColor.red
}
it("should have input field background color") {
expect(style.inputBackgroundColor) == UIColor.white
}
it("should have input field icon background color") {
expect(style.inputIconBackgroundColor) == UIColor(red: 0.9333, green: 0.9333, blue: 0.9333, alpha: 1.0)
}
it("should have input field icon color") {
expect(style.inputIconColor) == UIColor(red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0 )
}
it("should have secondary button color") {
expect(style.secondaryButtonColor) == UIColor.black
}
it("should have terms button color") {
expect(style.termsButtonColor) == UIColor(red: 0.9333, green: 0.9333, blue: 0.9333, alpha: 1.0)
}
it("should have terms title color") {
expect(style.termsButtonTitleColor) == UIColor.black
}
it("should have database login tab text color") {
expect(style.tabTextColor) == UIColor(red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0)
}
it("should have database login tab text color") {
expect(style.selectedTabTextColor) == UIColor.black
}
it("should have database login tab tint color") {
expect(style.tabTintColor) == UIColor.black
}
it("should have lock controller status bar update animation") {
expect(style.statusBarUpdateAnimation.rawValue) == 0
}
it("should have lock controller status bar hidden") {
expect(style.statusBarHidden) == false
}
it("should have lock controller status bar style") {
expect(style.statusBarStyle.rawValue) == 0
}
it("should have search status bar style") {
expect(style.searchBarStyle.rawValue) == 0
}
it("should have header close button image") {
expect(style.headerCloseIcon) == UIImage(named: "ic_close", in: Lock.bundle)
}
it("should have header back button image") {
expect(style.headerBackIcon) == UIImage(named: "ic_back", in: Lock.bundle)
}
it("should have modal popup true") {
expect(style.modalPopup) == true
}
}
describe("custom style") {
var style: Style!
beforeEach {
style = Style.Auth0
}
it("should show button title when header title is hidden") {
style.hideTitle = true
expect(style.hideButtonTitle) == false
}
}
}
}
|
mit
|
2ddacbcc56e6262a8fbbb14d22059613
| 34.534161 | 119 | 0.575424 | 4.662592 | false | false | false | false |
savelii/BSON
|
Sources/Decimal.swift
|
1
|
1227
|
import Foundation
public struct Decimal128: BSONPrimitive {
public var typeIdentifier: UInt8 {
return 0x13
}
public typealias Raw = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
fileprivate var _storage = [UInt8]()
public var raw: Raw {
get {
return (_storage[0], _storage[1], _storage[2], _storage[3], _storage[4], _storage[5], _storage[6], _storage[7], _storage[8], _storage[9], _storage[10], _storage[11], _storage[12], _storage[13], _storage[14], _storage[15])
}
set {
self._storage = [
newValue.0, newValue.1, newValue.2, newValue.3, newValue.4, newValue.5, newValue.6, newValue.7, newValue.8, newValue.9, newValue.10, newValue.11, newValue.12, newValue.13, newValue.14, newValue.15
]
}
}
internal init?(slice: ArraySlice<UInt8>) {
self._storage = Array(slice)
guard self._storage.count == 16 else {
return nil
}
}
public init(raw: Raw) {
self.raw = raw
}
public func makeBSONBinary() -> [UInt8] {
return self._storage
}
}
|
mit
|
536f4639d2951efd0ec242eb0a079693
| 31.289474 | 233 | 0.567237 | 3.577259 | false | false | false | false |
miracle-as/BasicComponents
|
BasicComponents/CoreDataManager.swift
|
1
|
10029
|
//
// CoreDataManager.swift
// Ejendomspriser
//
// Created by Lasse Løvdahl on 21/12/2015.
// Copyright © 2015 Miracle A/S. All rights reserved.
//
import Foundation
import CoreData
import Sugar
open class CoreDataManager {
open static let sharedInstance = CoreDataManager()
fileprivate init() {}
public enum DataChanges {
case deleted([NSManagedObject])
case updated([NSManagedObject])
case created([NSManagedObject])
}
open class func onDataChanges(_ block: @escaping (DataChanges) -> Void) -> NSObjectProtocol {
return NotificationCenter.default.addObserver(
forName: NSNotification.Name.NSManagedObjectContextObjectsDidChange,
object: CoreDataManager.managedObjectContext,
queue: OperationQueue.main) { note in
if let updated = (note as NSNotification).userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject> , updated.count > 0 {
block(.updated(Array(updated)))
}
if let deleted = (note as NSNotification).userInfo?[NSDeletedObjectsKey] as? Set<NSManagedObject> , deleted.count > 0 {
block(.deleted(Array(deleted)))
}
if let inserted = (note as NSNotification).userInfo?[NSInsertedObjectsKey] as? Set<NSManagedObject> , inserted.count > 0 {
block(.created(Array(inserted)))
}
}
}
fileprivate lazy var applicationDocumentsDirectory: URL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
fileprivate lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: Application.executable, withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
fileprivate lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
var coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let storeOptions = [NSMigratePersistentStoresAutomaticallyOption : true]
let url = self.applicationDocumentsDirectory.appendingPathComponent("\(Application.executable).sqlite")
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: storeOptions)
} catch {
print("CoreData ERROR, There was an error creating or loading the application's saved data.")
do {
try FileManager.default.removeItem(at: url)
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: storeOptions)
} catch {
fatalError("CoreData ERROR, There was an error creating or loading the application's saved data.")
}
}
return coordinator
}()
fileprivate lazy var managedObjectContext: NSManagedObjectContext = {
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
return managedObjectContext
}()
fileprivate lazy var childObjectContext: NSManagedObjectContext = {
let childObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childObjectContext.parent = self.managedObjectContext
// childObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return childObjectContext
}()
fileprivate func saveContext (_ context: NSManagedObjectContext = CoreDataManager.managedObjectContext) {
// print("saving: \(context) hasChanges: \(context.hasChanges)")
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unable to save data. Error \(nserror)") //FIXME this is properly a little rough
}
}
}
open class var managedObjectContext: NSManagedObjectContext {
return sharedInstance.managedObjectContext
}
}
public extension NSManagedObjectContext {
func saveIfChanged() {
if hasChanges {
do {
try save()
} catch {
let nserror = error as NSError
print("Unable to save data. Error \(nserror)") //FIXME this is properly a little rough
}
}
}
}
public extension CoreDataManager {
public static func saveInMainContext(_ block: (_ context: NSManagedObjectContext) -> Void) {
saveInMainContext(inContext: block, compleated: .none)
}
public static func saveInMainContext(
inContext block: (_ context: NSManagedObjectContext) -> Void, compleated: (() -> Void)?) {
block(CoreDataManager.managedObjectContext)
sharedInstance.saveContext()
if let compleated = compleated {
compleated()
}
}
public static func saveInBackgroundContext(inContext block:@escaping (_ context: NSManagedObjectContext) -> Void, compleated: @escaping () -> Void) {
var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
func registerBackgroundTask() {
backgroundTask = UIApplication.shared.beginBackgroundTask {
// print("Killing bgtask \(backgroundTask)")
endBackgroundTask()
}
// print("Register bgtask \(backgroundTask)")
}
func endBackgroundTask() {
// print("Background task ended.")
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
let context = sharedInstance.childObjectContext
context.perform {
registerBackgroundTask()
block(context)
sharedInstance.saveContext(context)
context.reset()
dispatch {
sharedInstance.saveContext()
compleated()
endBackgroundTask()
}
}
}
}
public extension NSManagedObject {
class var entityName: String {
get {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
}
public class func removeAllAndWait(_ inContext: NSManagedObjectContext) {
if let entities = (try? inContext.fetch(NSFetchRequest<NSManagedObject>(entityName: entityName))) {
entities.forEach(inContext.delete(_:))
}
}
public class func removeAll(_ whenDone:(() -> Void)? = .none) {
CoreDataManager.saveInBackgroundContext(
inContext: { context in
if let entities = (try? context.fetch(NSFetchRequest<NSManagedObject>(entityName: entityName))) {
entities.forEach(context.delete(_:))
}},
compleated: {
if let whenDone = whenDone {
whenDone()
}
}
)
}
public func saveNow(_ completed: (()->())? = .none) {
if let context = managedObjectContext {
if context.concurrencyType == .mainQueueConcurrencyType {
context.saveIfChanged()
completed?()
} else {
CoreDataManager.saveInBackgroundContext(
inContext: { context in
context.saveIfChanged()
},
compleated: {
completed?()
}
)
}
}
}
public static func createEntity(_ inContext: NSManagedObjectContext = CoreDataManager.managedObjectContext) -> Self {
return createEntityHelper(inContext)
}
fileprivate class func createEntityHelper<T: NSManagedObject>(_ inContext: NSManagedObjectContext) -> T {
return NSEntityDescription.insertNewObject(forEntityName: entityName, into: inContext) as! T // swiftlint:disable:this force_cast
}
public class func findOrCreate<T: NSManagedObject>(
whereProperty: String,
hasValue: CVarArg,
inContext: NSManagedObjectContext = CoreDataManager.managedObjectContext,
block:((_ entity: T, _ exists: Bool) -> Void)?) -> T {
let fetchRequest = NSFetchRequest<T>(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: "%K == %@", whereProperty, hasValue)
let entities = (try? inContext.fetch(fetchRequest)) ?? []
let entity = entities.first
if let entity = entity {
if let block = block {
block(entity, true)
}
return entity
} else {
let entity = createEntity(inContext) as! T // swiftlint:disable:this force_cast
entity.setValue(hasValue, forKeyPath: whereProperty)
if let block = block {
block(entity, false)
}
return entity
}
}
public class func countEntities(
_ predicate: NSPredicate? = .none,
inContext: NSManagedObjectContext = CoreDataManager.managedObjectContext
) -> Int {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
fetchRequest.predicate = predicate
return (try? inContext.count(for: fetchRequest)) ?? 0
}
public class func findWhere<T: NSManagedObject>(
_ predicate: NSPredicate? = .none,
inContext: NSManagedObjectContext = CoreDataManager.managedObjectContext
) -> [T] {
let fetchRequest = NSFetchRequest<T>(entityName: entityName)
fetchRequest.predicate = predicate
return (try? inContext.fetch(fetchRequest)) ?? []
}
public class func findWhere<T: NSManagedObject>(
_ predicate: String,
inContext: NSManagedObjectContext = CoreDataManager.managedObjectContext
) -> [T] {
let fetchRequest = NSFetchRequest<T>(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: predicate)
return (try? inContext.fetch(fetchRequest)) ?? []
}
public class func all<T: NSManagedObject>(_ inContext: NSManagedObjectContext = CoreDataManager.managedObjectContext) -> [T] {
return findWhere(inContext: inContext)
}
public class func fetchedResultsController<T: NSManagedObject> (
_ predicate: NSPredicate? = .none,
orderBy: [NSSortDescriptor],
sectionNameKeyPath: String? = .none,
inContext: NSManagedObjectContext = CoreDataManager.managedObjectContext
) -> NSFetchedResultsController<T> {
let fetchRequest = NSFetchRequest<T>(entityName: entityName)
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = orderBy
return NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: inContext,
sectionNameKeyPath: sectionNameKeyPath,
cacheName: .none)
}
}
public extension String {
public var ascending: NSSortDescriptor {
return NSSortDescriptor(key: self, ascending: true)
}
public var descending: NSSortDescriptor {
return NSSortDescriptor(key: self, ascending: false)
}
}
|
mit
|
74869d40029e5909b8caaf70c93c5c75
| 28.842262 | 150 | 0.717263 | 4.786158 | false | false | false | false |
coolster01/PokerTouch
|
PokerTouch/HandsViewController.swift
|
1
|
4946
|
//
// HandsViewController.swift
// PokerTouch
//
// Created by Subhi Sbahi on 6/1/17.
// Copyright © 2017 Rami Sbahi. All rights reserved.
//
import UIKit
class HandsViewController: UIViewController {
@IBOutlet weak var Card1: UIImageView!
@IBOutlet weak var Card2: UIImageView!
@IBOutlet weak var Card3: UIImageView!
@IBOutlet weak var Card4: UIImageView!
@IBOutlet weak var Card5: UIImageView!
@IBOutlet weak var Player1: UILabel!
@IBOutlet weak var Label1: UILabel!
@IBOutlet weak var Player2: UILabel!
@IBOutlet weak var Label2: UILabel!
@IBOutlet weak var Player3: UILabel!
@IBOutlet weak var Label3: UILabel!
@IBOutlet weak var Player4: UILabel!
@IBOutlet weak var Label4: UILabel!
@IBOutlet weak var Player5: UILabel!
@IBOutlet weak var Label5: UILabel!
@IBOutlet weak var Player6: UILabel!
@IBOutlet weak var Label6: UILabel!
/*
@IBOutlet weak var Player7: UILabel!
@IBOutlet weak var Label7: UILabel!
@IBOutlet weak var Player8: UILabel!
@IBOutlet weak var Label8: UILabel!
@IBOutlet weak var Player9: UILabel!
@IBOutlet weak var Label9: UILabel!
*/
@IBOutlet weak var P1C1: UIImageView!
@IBOutlet weak var P1C2: UIImageView!
@IBOutlet weak var P2C1: UIImageView!
@IBOutlet weak var P2C2: UIImageView!
@IBOutlet weak var P3C1: UIImageView!
@IBOutlet weak var P3C2: UIImageView!
@IBOutlet weak var P4C1: UIImageView!
@IBOutlet weak var P4C2: UIImageView!
@IBOutlet weak var P5C1: UIImageView!
@IBOutlet weak var P5C2: UIImageView!
@IBOutlet weak var P6C1: UIImageView!
@IBOutlet weak var P6C2: UIImageView!
/*
@IBOutlet weak var P7C1: UIImageView!
@IBOutlet weak var P7C2: UIImageView!
@IBOutlet weak var P8C1: UIImageView!
@IBOutlet weak var P8C2: UIImageView!
@IBOutlet weak var P9C1: UIImageView!
@IBOutlet weak var P9C2: UIImageView!
*/
static let handNames = ["None", "One Pair", "Two Pair", "Three of a Kind", "Straight", "Flush", "Full House", "Four of a Kind", "Straight Flush", "Royal Flush"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(false)
let communityLabels = [Card1, Card2, Card3, Card4, Card5]
let playerLabels = [Player1, Player2, Player3, Player4, Player5, Player6]
let handLabels = [Label1, Label2, Label3, Label4, Label5, Label6]
let firstCards = [P1C1, P2C1, P3C1, P4C1, P5C1, P6C1]
let secondCards = [P1C2, P2C2, P3C2, P4C2, P5C2, P6C2]
for i in 0..<5
{
communityLabels[i]?.image = UIImage(named: GameViewController.myRunner.myDeck.communityCards[i].getImage())
}
for j in 0..<9
{
if(j < GameViewController.myRunner.myPlayers.count)
{
firstCards[j]?.isHidden = false
secondCards[j]?.isHidden = false
if(GameViewController.myRunner.myPlayers[j].isBetting)
{
var myLabelText = ""
if((!GameViewController.myRunner.wasTie && j == GameViewController.myRunner.recentWinner) || (GameViewController.myRunner.wasTie && GameViewController.myRunner.recentWinners.contains(j)))
{
myLabelText = GameViewController.myRunner.myPlayers[j].myName + " - Winner!"
}
else
{
myLabelText = GameViewController.myRunner.myPlayers[j].myName
}
playerLabels[j]?.text = myLabelText
handLabels[j]?.text = HandsViewController.handNames[GameViewController.myRunner.getHand(index: j).score]
firstCards[j]?.image = UIImage(named: GameViewController.myRunner.myPlayers[j].card1.getImage())
secondCards[j]?.image = UIImage(named: GameViewController.myRunner.myPlayers[j].card2.getImage())
}
else
{
playerLabels[j]?.text = GameViewController.myRunner.myPlayers[j].myName
handLabels[j]?.text = "Folded"
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
31247e21232c19f88022112f4e89e145
| 35.902985 | 207 | 0.617998 | 4.172996 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/RemoteNotifications/Sources/RemoteNotificationsKitMock/MockGuidSharedKeyRepositoryAPI.swift
|
1
|
835
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import FeatureAuthenticationDomain
class MockGuidSharedKeyRepositoryAPI: GuidRepositoryAPI, SharedKeyRepositoryAPI {
var expectedGuid: String? = "123-abc-456-def-789-ghi"
var expectedSharedKey: String? = "0123456789"
var guid: AnyPublisher<String?, Never> {
.just(expectedGuid)
}
var hasGuid: AnyPublisher<Bool, Never> {
guid.map { $0 != nil }.eraseToAnyPublisher()
}
var sharedKey: AnyPublisher<String?, Never> {
.just(expectedSharedKey)
}
func set(guid: String) -> AnyPublisher<Void, Never> {
expectedGuid = guid
return .just(())
}
func set(sharedKey: String) -> AnyPublisher<Void, Never> {
expectedSharedKey = sharedKey
return .just(())
}
}
|
lgpl-3.0
|
097cfe698dfb5233452648797a6efe68
| 25.0625 | 81 | 0.658273 | 4.276923 | false | false | false | false |
dflax/amazeballs
|
AmazeBalls/Models/Ball.swift
|
1
|
8862
|
//
// Ball.swift
// amazeballs
//
// Created by Daniel Flax on 3/28/20.
// Copyright © 2020 Daniel Flax. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
import SpriteKit
class Ball: SKSpriteNode {
// Displacement between finger touch point and center of clown
var moveTransalation: CGPoint = CGPoint(x: 0, y: 0)
// Vectors to track momentum
var currentPointVector: CGVector = CGVector(dx: 0.0, dy: 0.0)
var pointVector1: CGVector = CGVector(dx: 0.0, dy: 0.0)
var pointVector2: CGVector = CGVector(dx: 0.0, dy: 0.0)
var pointVector3: CGVector = CGVector(dx: 0.0, dy: 0.0)
var throwVector: CGVector = CGVector(dx: 0.0, dy: 0.0)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init() {
let emptyTexture = SKTexture(imageNamed: "ball-amazeball")
super.init(texture: emptyTexture, color: SKColor.clear, size: emptyTexture.size())
}
init(location: CGPoint, ballType: Int, bouncyness: CGFloat) {
let emptyTexture = SKTexture(imageNamed: "ball-amazeball")
super.init(texture: emptyTexture, color: SKColor.clear, size: emptyTexture.size())
var ballNameString = ""
var ballLookup = ballType
// If a random ball is selected, select the random ball from the first 7 of the options
//
// Peformance problems with the new, more complicated shapes. Need to figure out how to
// speed up performance. Most likely using the SKTexture preload technique.
if (ballLookup == 2007) {
ballLookup = randomNumber(minX: 2000, maxX: 2006)
}
switch (ballLookup) {
case 2000:
ballNameString = "ball-amazeball"
break
case 2001:
ballNameString = "ball-baseball1"
break
case 2002:
ballNameString = "ball-basketball1"
break
case 2003:
ballNameString = "ball-football1"
break
case 2004:
ballNameString = "ball-pumpkin1"
break
case 2005:
ballNameString = "ball-soccer1"
break
case 2006:
ballNameString = "ball-soccer2"
break
case 2007:
ballNameString = "ball-apple1"
break
case 2008:
ballNameString = "ball-banana1"
break
case 2009:
ballNameString = "ball-banana2"
break
case 2010:
ballNameString = "ball-banana3"
break
case 2011:
ballNameString = "ball-baseball2"
break
case 2012:
ballNameString = "ball-baseball3"
break
case 2013:
ballNameString = "ball-basketball2"
break
case 2014:
ballNameString = "ball-basketball3"
break
case 2015:
ballNameString = "ball-bowling1"
break
case 2016:
ballNameString = "ball-bowling2"
break
case 2017:
ballNameString = "ball-bowling3"
break
case 2018:
ballNameString = "ball-bowling4"
break
case 2019:
ballNameString = "ball-bowlingpin1"
break
case 2020:
ballNameString = "ball-bowlingpins2"
break
case 2021:
ballNameString = "ball-cherries1"
break
case 2022:
ballNameString = "ball-cherries2"
break
case 2023:
ballNameString = "ball-christmasball1"
break
case 2024:
ballNameString = "ball-cookie1"
break
case 2025:
ballNameString = "ball-discoball1"
break
case 2026:
ballNameString = "ball-discoball2"
break
case 2027:
ballNameString = "ball-egg1"
break
case 2028:
ballNameString = "ball-eightball1"
break
case 2029:
ballNameString = "ball-football2"
break
case 2030:
ballNameString = "ball-football3"
break
case 2031:
ballNameString = "ball-football4"
break
case 2032:
ballNameString = "ball-glassball1"
break
case 2033:
ballNameString = "ball-golf1"
break
case 2034:
ballNameString = "ball-golf2"
break
case 2035:
ballNameString = "ball-golf3"
break
case 2036:
ballNameString = "ball-hockeypuck1"
break
case 2037:
ballNameString = "ball-olive1"
break
case 2038:
ballNameString = "ball-peace1"
break
case 2039:
ballNameString = "ball-peace2"
break
case 2040:
ballNameString = "ball-soccer3"
break
case 2041:
ballNameString = "ball-soccer4"
break
case 2042:
ballNameString = "ball-soccer5"
break
case 2043:
ballNameString = "ball-soccer6"
break
case 2044:
ballNameString = "ball-tennis1"
break
case 2045:
ballNameString = "ball-tennis2"
break
case 2046:
ballNameString = "ball-tennis3"
break
case 2047:
ballNameString = "ball-tennis4"
break
case 2048:
ballNameString = "ball-tennis5"
break
case 2049:
ballNameString = "ball-volleyball1"
break
case 2050:
ballNameString = "ball-volleyball2"
break
default:
break
}
let texture = SKTexture(imageNamed: ballNameString)
self.texture = texture
size = CGSize(width: 75.0, height: 75.0)
position = location
physicsBody = SKPhysicsBody(texture: self.texture!,size:self.size)
// physicsBody = SKPhysicsBody(circleOfRadius: 75.0, center: location)
physicsBody?.isDynamic = true
physicsBody?.usesPreciseCollisionDetection = false
physicsBody?.allowsRotation = true
isUserInteractionEnabled = true
physicsBody?.affectedByGravity = true
physicsBody?.restitution = bouncyness
physicsBody?.friction = 0.5
physicsBody?.linearDamping = 0.0
physicsBody?.categoryBitMask = CollisionCategories.Ball
physicsBody?.contactTestBitMask = CollisionCategories.EdgeBody | CollisionCategories.Ball
}
// MARK: - Touch Handling
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
moveTransalation = CGPoint(x: location.x - self.anchorPoint.x, y: location.y - self.anchorPoint.y)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// var nodeTouched = SKNode()
// var currentNodeTouched = SKNode()
for touch in touches {
let location = touch.location(in: self.scene!)
let previousLocation = touch.previousLocation(in: self.scene!)
// Calculate an update to the throwing vector
// Move the last three down the stack
pointVector3 = pointVector2
pointVector2 = pointVector1
pointVector1 = currentPointVector
// Calculate the current vector
currentPointVector = CGVector(dx: location.x - previousLocation.x, dy: location.y - previousLocation.y)
let newPosition = CGPoint(x: location.x + moveTransalation.x, y: location.y + moveTransalation.y)
self.position = newPosition
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// var nodeTouched = SKNode()
for touch in (touches as! Set<UITouch>) {
let location = touch.location(in: self.scene!)
let previousLocation = touch.previousLocation(in: self.scene!)
// Calculate an update to the throwing vector
// Move the last three down the stack
pointVector3 = pointVector2
pointVector2 = pointVector1
pointVector1 = currentPointVector
// Calculate the current vector
currentPointVector = CGVector(dx: location.x - previousLocation.x, dy: location.y - previousLocation.y)
// Calculate the final throwVector
throwVector = CGVector(dx: pointVector1.dx + pointVector2.dx + pointVector3.dx + currentPointVector.dx, dy: pointVector1.dy + pointVector2.dy + pointVector3.dy + currentPointVector.dy)
let momentumVector = CGVector(dx: location.x - previousLocation.x, dy: location.y - previousLocation.y)
self.physicsBody?.applyImpulse(throwVector)
}
}
}
extension Ball {
override func copy() -> Any {
let copy = Ball()
copy.moveTransalation = self.moveTransalation
copy.currentPointVector = self.currentPointVector
copy.pointVector1 = self.pointVector1
copy.pointVector2 = self.pointVector2
copy.pointVector3 = self.pointVector3
copy.throwVector = self.throwVector
copy.texture = self.texture
copy.physicsBody = self.physicsBody
return copy
}
}
|
mit
|
247b7121786c8f2d6a5695b4300dd52e
| 26.604361 | 187 | 0.712109 | 3.426527 | false | false | false | false |
hooman/swift
|
test/Distributed/Inputs/dynamic_replacement_da_decl.swift
|
2
|
570
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import _Distributed
distributed actor DA {
distributed func hello(other: DA) {}
}
|
apache-2.0
|
d6d1b59247fd193987ea47a999cf5076
| 27.5 | 80 | 0.521053 | 5.181818 | false | false | false | false |
ymsheng/mqttswift
|
MNMqttSwift/MqttSwift/MQTTEncoder.swift
|
1
|
5141
|
//
// MQTTEncoder.swift
// BossSwift
//
// Created by mosn on 12/31/15.
// Copyright © 2015 com.hpbr.111. All rights reserved.
//
import Foundation
public enum MQTTEncoderEvent {
case MQTTEncoderEventReady
case MQTTEncoderEventErrorOccurred
}
public enum MQTTEncoderStatus {
case MQTTEncoderStatusInitializing
case MQTTEncoderStatusReady
case MQTTEncoderStatusSending
case MQTTEncoderStatusEndEncountered
case MQTTEncoderStatusError
}
protocol MQTTEncoderDelegate {
func encoderHandleEvent(sender:MQTTEncoder, eventCode:MQTTEncoderEvent)
}
class MQTTEncoder : NSObject,NSStreamDelegate{
var status:MQTTEncoderStatus
var stream:NSOutputStream?
var runLoop:NSRunLoop
var runLoopMode:String
var buffer:NSMutableData?
var byteIndex:Int
var delegate:MQTTEncoderDelegate?
init(stream:NSOutputStream, runLoop:NSRunLoop, mode:String) {
self.status = .MQTTEncoderStatusInitializing
self.stream = stream
self.runLoop = runLoop
self.runLoopMode = mode
self.byteIndex = 0
}
func open() {
self.stream?.delegate = self
self.stream?.scheduleInRunLoop(self.runLoop, forMode: self.runLoopMode)
self.stream?.open()
}
func close() {
self.stream?.close()
self.stream?.removeFromRunLoop(self.runLoop, forMode: self.runLoopMode)
self.stream?.delegate = nil
}
internal func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if self.stream == nil || aStream != self.stream {
return
}
switch eventCode {
case NSStreamEvent.OpenCompleted:
break
case NSStreamEvent.HasSpaceAvailable:
if self.status == .MQTTEncoderStatusInitializing {
self.status = .MQTTEncoderStatusReady
self.delegate?.encoderHandleEvent(self, eventCode: .MQTTEncoderEventReady)
}
else if self.status == .MQTTEncoderStatusReady {
self.delegate?.encoderHandleEvent(self, eventCode: .MQTTEncoderEventReady)
}
else if self.status == .MQTTEncoderStatusSending {
//
var ptr:UnsafePointer<Void>
var n:Int = 0
var length:Int = 0
ptr = self.buffer!.bytes.advancedBy(self.byteIndex)
length = self.buffer!.length - self.byteIndex
n = self.stream!.write(UnsafePointer<UInt8>(ptr), maxLength: length)
if n == -1 {
self.status = .MQTTEncoderStatusError
self.delegate?.encoderHandleEvent(self, eventCode: .MQTTEncoderEventErrorOccurred)
}
else if n < length {
self.byteIndex += n
}
else {
self.buffer = nil
self.byteIndex = 0
self.status = .MQTTEncoderStatusReady
}
}
case NSStreamEvent.EndEncountered, NSStreamEvent.ErrorOccurred:
if self.status != .MQTTEncoderStatusError {
self.status = .MQTTEncoderStatusError
self.delegate?.encoderHandleEvent(self, eventCode: .MQTTEncoderEventErrorOccurred)
}
default:break
}
}
func encodeMessage(msg:MQTTMessage) {
var header:UInt8 = 0
var n:Int = 0
var length:Int = 0
if self.status != .MQTTEncoderStatusReady || self.stream == nil || self.stream?.streamStatus != NSStreamStatus.Open {
return
}
if self.buffer != nil {
return
}
if self.byteIndex != 0 {
return
}
self.buffer = NSMutableData()
header = (msg.type & 0x0f) << 4
if msg.isDuplicate {
header |= 0x08
}
header |= (msg.qos & 0x03) << 1
if msg.retainFlag {
header |= 0x01
}
self.buffer!.appendBytes(&header, length: 1)
if let data = msg.data {
length = data.length
}
repeat {
var digit:Int = length % 128
length /= 128
if length > 0 {
digit |= 0x08
}
self.buffer!.appendBytes(&digit, length: 1)
} while (length > 0)
if let data = msg.data {
self.buffer!.appendData(data)
}
if self.stream!.hasSpaceAvailable {
n = self.stream!.write(UnsafePointer<UInt8>(self.buffer!.bytes), maxLength: self.buffer!.length)
}
if n == -1 {
self.status = .MQTTEncoderStatusError
self.delegate?.encoderHandleEvent(self, eventCode: .MQTTEncoderEventErrorOccurred)
}
else if n < self.buffer?.length {
self.byteIndex += n
self.status = .MQTTEncoderStatusSending
}
else {
self.buffer = nil
}
}
}
|
apache-2.0
|
26e1beba0c7bc7c74d127b7483a5dbdf
| 29.60119 | 125 | 0.55856 | 4.835372 | false | false | false | false |
vector-im/vector-ios
|
Riot/Modules/Settings/KeyBackup/SettingsKeyBackupViewModel.swift
|
2
|
5433
|
/*
Copyright 2019 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 UIKit
final class SettingsKeyBackupViewModel: SettingsKeyBackupViewModelType {
// MARK: - Properties
weak var viewDelegate: SettingsKeyBackupViewModelViewDelegate?
// MARK: Private
private let keyBackup: MXKeyBackup
init(keyBackup: MXKeyBackup) {
self.keyBackup = keyBackup
self.registerKeyBackupVersionDidChangeStateNotification()
}
private func registerKeyBackupVersionDidChangeStateNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(keyBackupDidStateChange), name: NSNotification.Name.mxKeyBackupDidStateChange, object: self.keyBackup)
}
@objc private func keyBackupDidStateChange() {
self.checkKeyBackupState()
}
func process(viewAction: SettingsKeyBackupViewAction) {
guard let viewDelegate = self.viewDelegate else {
return
}
switch viewAction {
case .load:
viewDelegate.settingsKeyBackupViewModel(self, didUpdateViewState: .checkingBackup)
self.checkKeyBackupState()
case .create:
viewDelegate.settingsKeyBackupViewModelShowKeyBackupSetup(self)
case .restore(let keyBackupVersion):
viewDelegate.settingsKeyBackup(self, showKeyBackupRecover: keyBackupVersion)
case .confirmDelete(let keyBackupVersion):
viewDelegate.settingsKeyBackup(self, showKeyBackupDeleteConfirm: keyBackupVersion)
case .delete(let keyBackupVersion):
self.deleteKeyBackupVersion(keyBackupVersion)
}
}
// MARK: - Private
private func checkKeyBackupState() {
// Check homeserver update in background
self.keyBackup.forceRefresh(nil, failure: nil)
if let keyBackupVersion = self.keyBackup.keyBackupVersion {
self.keyBackup.trust(for: keyBackupVersion, onComplete: { [weak self] (keyBackupVersionTrust) in
guard let sself = self else {
return
}
sself.computeState(withBackupVersionTrust: keyBackupVersionTrust)
})
} else {
computeState()
}
}
private func computeState(withBackupVersionTrust keyBackupVersionTrust: MXKeyBackupVersionTrust? = nil) {
var viewState: SettingsKeyBackupViewState?
switch self.keyBackup.state {
case MXKeyBackupStateUnknown,
MXKeyBackupStateCheckingBackUpOnHomeserver:
viewState = .checkingBackup
case MXKeyBackupStateDisabled, MXKeyBackupStateEnabling:
viewState = .noBackup
case MXKeyBackupStateNotTrusted:
guard let keyBackupVersion = self.keyBackup.keyBackupVersion, let keyBackupVersionTrust = keyBackupVersionTrust else {
return
}
viewState = .backupNotTrusted(keyBackupVersion, keyBackupVersionTrust)
case MXKeyBackupStateReadyToBackUp:
guard let keyBackupVersion = self.keyBackup.keyBackupVersion, let keyBackupVersionTrust = keyBackupVersionTrust else {
return
}
viewState = .backup(keyBackupVersion, keyBackupVersionTrust)
case MXKeyBackupStateWillBackUp, MXKeyBackupStateBackingUp:
guard let keyBackupVersion = self.keyBackup.keyBackupVersion, let keyBackupVersionTrust = keyBackupVersionTrust else {
return
}
// Get the backup progress before updating the state
self.keyBackup.backupProgress { [weak self] (progress) in
guard let sself = self else {
return
}
sself.viewDelegate?.settingsKeyBackupViewModel(sself, didUpdateViewState: .backupAndRunning(keyBackupVersion, keyBackupVersionTrust, progress))
}
default:
break
}
if let vviewState = viewState {
self.viewDelegate?.settingsKeyBackupViewModel(self, didUpdateViewState: vviewState)
}
}
private func deleteKeyBackupVersion(_ keyBackupVersion: MXKeyBackupVersion) {
guard let keyBackupVersionVersion = keyBackupVersion.version else {
return
}
self.viewDelegate?.settingsKeyBackupViewModel(self, didUpdateNetworkRequestViewState: .loading)
self.keyBackup.deleteVersion(keyBackupVersionVersion, success: { [weak self] () in
guard let sself = self else {
return
}
sself.viewDelegate?.settingsKeyBackupViewModel(sself, didUpdateNetworkRequestViewState: .loaded)
}, failure: { [weak self] error in
guard let sself = self else {
return
}
sself.viewDelegate?.settingsKeyBackupViewModel(sself, didUpdateNetworkRequestViewState: .error(error))
})
}
}
|
apache-2.0
|
f2ad9160a2e0f1debca464f7110f0c0a
| 35.709459 | 175 | 0.674029 | 5.521341 | false | false | false | false |
liuche/FirefoxAccounts-ios
|
Sync/Records/CleartextPayloadJSON.swift
|
1
|
1568
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SwiftyJSON
open class BasePayloadJSON {
var json: JSON
required public init(_ jsonString: String) {
self.json = JSON(parseJSON: jsonString)
}
public init(_ json: JSON) {
self.json = json
}
// Override me.
fileprivate func isValid() -> Bool {
return self.json.type != .unknown &&
self.json.error == nil
}
subscript(key: String) -> JSON {
get {
return json[key]
}
set {
json[key] = newValue
}
}
}
/**
* http://docs.services.mozilla.com/sync/objectformats.html
* "In addition to these custom collection object structures, the
* Encrypted DataObject adds fields like id and deleted."
*/
open class CleartextPayloadJSON: BasePayloadJSON {
// Override me.
override open func isValid() -> Bool {
return super.isValid() && self["id"].isString()
}
open var id: String {
return self["id"].string!
}
open var deleted: Bool {
let d = self["deleted"]
if let bool = d.bool {
return bool
} else {
return false
}
}
// Override me.
// Doesn't check id. Should it?
open func equalPayloads (_ obj: CleartextPayloadJSON) -> Bool {
return self.deleted == obj.deleted
}
}
|
mpl-2.0
|
f79fc09cb58378352bad07354d2ea3ad
| 23.123077 | 70 | 0.586735 | 4.237838 | false | false | false | false |
apple/swift-corelibs-foundation
|
Tests/Tools/GenerateTestFixtures/Utilities.swift
|
1
|
1008
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 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
// This is the same as the XCTUnwrap() method used in TestFoundation, but does not require XCTest.
enum TestError: Error {
case unexpectedNil
}
// Same signature as the original.
func XCTUnwrap<T>(_ expression: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) throws -> T {
if let value = try expression() {
return value
} else {
throw TestError.unexpectedNil
}
}
func swiftVersionString() -> String {
#if compiler(>=5.0) && compiler(<5.1)
return "5.0" // We support 5.0 or later.
#elseif compiler(>=5.1)
return "5.1"
#endif
}
|
apache-2.0
|
56c4d441095b096ef55032ef1ec4a313
| 32.6 | 166 | 0.668651 | 3.891892 | false | true | false | false |
Brightify/ReactantUI
|
Tests/Tokenizer/ConstraintConditionTests.swift
|
1
|
12654
|
//
// ConstraintConditionTests.swift
// LiveUI-iOSTests
//
// Created by Robin Krenecky on 27/04/2018.
//
//
//import XCTest
//@testable import ReactantLiveUI
//
//class ConstraintConditionTests: XCTestCase {
//
// lazy var interfaceState1: InterfaceState = {
// return InterfaceState(interfaceIdiom: .phone, horizontalSizeClass: .compact, verticalSizeClass: .regular, deviceOrientation: .landscape)
// }()
//
// lazy var interfaceState2: InterfaceState = {
// return InterfaceState(interfaceIdiom: .pad, horizontalSizeClass: .regular, verticalSizeClass: .compact, deviceOrientation: .portrait)
// }()
//
// lazy var interfaceState3: InterfaceState = {
// return InterfaceState(interfaceIdiom: .phone, horizontalSizeClass: .compact, verticalSizeClass: .compact, deviceOrientation: .portrait)
// }()
//
// var allInterfaceStates: [InterfaceState] {
// return [interfaceState1, interfaceState2, interfaceState3]
// }
//
// private func parseInput(_ input: String) throws -> Condition? {
// return try ConstraintParser(tokens: Lexer.tokenize(input: "\(input) super inset"), layoutAttribute: LayoutAttribute.above).parseSingle().condition
// }
//
// func testSimpleStatements() throws {
// let input1 = "[iphone != true]"
// let input2 = "[ipad == true]"
// let input3 = "[ipad == false]"
// let input4 = "[!ipad]"
// let input5 = "[vertical == compact]"
// let input6 = "[vertical == compact == false]"
// let input7 = "[landscape]"
// let input8 = "[vertical != compact]"
// let input9 = "[vertical != regular == false]"
// let input10 = "[!(vertical != regular) != false]"
//
//
// if let result1 = try parseInput(input1),
// let result2 = try parseInput(input2),
// let result3 = try parseInput(input3),
// let result4 = try parseInput(input4),
// let result5 = try parseInput(input5),
// let result6 = try parseInput(input6),
// let result7 = try parseInput(input7),
// let result8 = try parseInput(input8),
// let result9 = try parseInput(input9),
// let result10 = try parseInput(input10) {
//
// XCTAssertFalse(result1.evaluate(from: interfaceState1))
// XCTAssertTrue(result1.evaluate(from: interfaceState2))
// XCTAssertFalse(result1.evaluate(from: interfaceState3))
//
// XCTAssertFalse(result2.evaluate(from: interfaceState1))
// XCTAssertTrue(result2.evaluate(from: interfaceState2))
// XCTAssertFalse(result2.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result3.evaluate(from: interfaceState1))
// XCTAssertFalse(result3.evaluate(from: interfaceState2))
// XCTAssertTrue(result3.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result4.evaluate(from: interfaceState1))
// XCTAssertFalse(result4.evaluate(from: interfaceState2))
// XCTAssertTrue(result4.evaluate(from: interfaceState3))
//
// XCTAssertFalse(result5.evaluate(from: interfaceState1))
// XCTAssertTrue(result5.evaluate(from: interfaceState2))
// XCTAssertTrue(result5.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result6.evaluate(from: interfaceState1))
// XCTAssertFalse(result6.evaluate(from: interfaceState2))
// XCTAssertFalse(result6.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result7.evaluate(from: interfaceState1))
// XCTAssertFalse(result7.evaluate(from: interfaceState2))
// XCTAssertFalse(result7.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result8.evaluate(from: interfaceState1))
// XCTAssertFalse(result8.evaluate(from: interfaceState2))
// XCTAssertFalse(result8.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result9.evaluate(from: interfaceState1))
// XCTAssertFalse(result9.evaluate(from: interfaceState2))
// XCTAssertFalse(result9.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result10.evaluate(from: interfaceState1))
// XCTAssertFalse(result10.evaluate(from: interfaceState2))
// XCTAssertFalse(result10.evaluate(from: interfaceState3))
// }
// }
//
// func testSimpleConjunctions() throws {
// let input1 = "[ipad and landscape]"
// let input2 = "[iphone and portrait]"
// let input3 = "[!ipad and vertical == compact]"
// let input4 = "[horizontal == compact and vertical == regular]"
// let input5 = "[horizontal == regular and vertical == compact and ipad and !landscape]"
// let input6 = "[horizontal != regular and vertical == compact and !ipad and !landscape]"
//
// if let result1 = try parseInput(input1),
// let result2 = try parseInput(input2),
// let result3 = try parseInput(input3),
// let result4 = try parseInput(input4),
// let result5 = try parseInput(input5),
// let result6 = try parseInput(input6) {
//
// XCTAssertFalse(result1.evaluate(from: interfaceState1))
// XCTAssertFalse(result1.evaluate(from: interfaceState2))
// XCTAssertFalse(result1.evaluate(from: interfaceState3))
//
// XCTAssertFalse(result2.evaluate(from: interfaceState1))
// XCTAssertFalse(result2.evaluate(from: interfaceState2))
// XCTAssertTrue(result2.evaluate(from: interfaceState3))
//
// XCTAssertFalse(result3.evaluate(from: interfaceState1))
// XCTAssertFalse(result3.evaluate(from: interfaceState2))
// XCTAssertTrue(result3.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result4.evaluate(from: interfaceState1))
// XCTAssertFalse(result4.evaluate(from: interfaceState2))
// XCTAssertFalse(result4.evaluate(from: interfaceState3))
//
// XCTAssertFalse(result5.evaluate(from: interfaceState1))
// XCTAssertTrue(result5.evaluate(from: interfaceState2))
// XCTAssertFalse(result5.evaluate(from: interfaceState3))
//
// XCTAssertFalse(result6.evaluate(from: interfaceState1))
// XCTAssertFalse(result6.evaluate(from: interfaceState2))
// XCTAssertTrue(result6.evaluate(from: interfaceState3))
// }
// }
//
// func testSimpleDisjunctions() throws {
// let input1 = "[ipad or landscape]"
// let input2 = "[!ipad or vertical == compact]"
// let input3 = "[horizontal == regular or vertical == regular]"
// let input4 = "[horizontal == regular or vertical == compact or ipad]"
// let input5 = "[horizontal != regular or vertical == compact or !ipad]"
//
// if let result1 = try parseInput(input1),
// let result2 = try parseInput(input2),
// let result3 = try parseInput(input3),
// let result4 = try parseInput(input4),
// let result5 = try parseInput(input5) {
//
// XCTAssertTrue(result1.evaluate(from: interfaceState1))
// XCTAssertTrue(result1.evaluate(from: interfaceState2))
// XCTAssertFalse(result1.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result2.evaluate(from: interfaceState1))
// XCTAssertTrue(result2.evaluate(from: interfaceState2))
// XCTAssertTrue(result2.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result3.evaluate(from: interfaceState1))
// XCTAssertTrue(result3.evaluate(from: interfaceState2))
// XCTAssertFalse(result3.evaluate(from: interfaceState3))
//
// XCTAssertFalse(result4.evaluate(from: interfaceState1))
// XCTAssertTrue(result4.evaluate(from: interfaceState2))
// XCTAssertTrue(result4.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result5.evaluate(from: interfaceState1))
// XCTAssertTrue(result5.evaluate(from: interfaceState2))
// XCTAssertTrue(result5.evaluate(from: interfaceState3))
// }
// }
//
// func testComplexConditions() throws {
// let input1 = "[ipad and landscape or vertical == regular]"
// let input2 = "[iphone and portrait or ipad and landscape or vertical == regular]"
// let input3 = "[ipad or landscape and vertical == regular or !ipad and portrait != false]"
// let input4 = "[vertical != regular or portrait and !iphone and horizontal == regular]"
// let input5 = "[(iphone or landscape) and vertical == regular]"
// let input6 = "[(vertical == regular and horizontal == compact) or (ipad and portrait)]"
// let input7 = "[!(ipad and portrait) and !(horizontal == regular)]"
// let input8 = "[(!(vertical == regular) or !(horizontal == compact and landscape)) and iphone]"
// let input9 = "[(!(iphone == false and landscape) and horizontal == compact) and vertical != compact]"
//
// if let result1 = try parseInput(input1),
// let result2 = try parseInput(input2),
// let result3 = try parseInput(input3),
// let result4 = try parseInput(input4),
// let result5 = try parseInput(input5),
// let result6 = try parseInput(input6),
// let result7 = try parseInput(input7),
// let result8 = try parseInput(input8),
// let result9 = try parseInput(input9) {
//
// XCTAssertTrue(result1.evaluate(from: interfaceState1))
// XCTAssertFalse(result1.evaluate(from: interfaceState2))
// XCTAssertFalse(result1.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result2.evaluate(from: interfaceState1))
// XCTAssertFalse(result2.evaluate(from: interfaceState2))
// XCTAssertTrue(result2.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result3.evaluate(from: interfaceState1))
// XCTAssertTrue(result3.evaluate(from: interfaceState2))
// XCTAssertTrue(result3.evaluate(from: interfaceState3))
//
// XCTAssertFalse(result4.evaluate(from: interfaceState1))
// XCTAssertTrue(result4.evaluate(from: interfaceState2))
// XCTAssertTrue(result4.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result5.evaluate(from: interfaceState1))
// XCTAssertFalse(result5.evaluate(from: interfaceState2))
// XCTAssertFalse(result5.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result6.evaluate(from: interfaceState1))
// XCTAssertTrue(result6.evaluate(from: interfaceState2))
// XCTAssertFalse(result6.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result7.evaluate(from: interfaceState1))
// XCTAssertFalse(result7.evaluate(from: interfaceState2))
// XCTAssertTrue(result7.evaluate(from: interfaceState3))
//
// XCTAssertFalse(result8.evaluate(from: interfaceState1))
// XCTAssertFalse(result8.evaluate(from: interfaceState2))
// XCTAssertTrue(result8.evaluate(from: interfaceState3))
//
// XCTAssertTrue(result9.evaluate(from: interfaceState1))
// XCTAssertFalse(result9.evaluate(from: interfaceState2))
// XCTAssertFalse(result9.evaluate(from: interfaceState3))
// }
// }
//
// func testMoreConditions() throws {
// let input = [
// "[vertical == regular or (horizontal == compact or vertical == compact and pad)]",
// "[vertical == regular or (horizontal == compact and vertical == compact and pad)]",
// "[vertical == regular and (horizontal == compact and vertical == compact or phone)]",
// ]
//
// let verifiers = [
// [true, true, true],
// [true, false, false],
// [true, false, false],
// ]
//
// guard verifiers.index(where: { $0.count != allInterfaceStates.count }) == nil else {
// XCTFail("Some verifiers don't match the interface state count.")
// return
// }
//
// let results = try input.flatMap { try parseInput($0) }.map { parsedInput in
// allInterfaceStates.map { parsedInput.evaluate(from: $0) }
// }
//
// for (outerIndex, (result, verifier)) in zip(results, verifiers).enumerated() {
// for innerIndex in 0..<result.count {
// XCTAssertEqual(result[innerIndex], verifier[innerIndex], "element at indices [\(outerIndex)][\(innerIndex)]")
// }
// }
// }
//}
|
mit
|
17293b36dd7d4d8f53a9acf1ed936285
| 47.29771 | 156 | 0.629682 | 4.116461 | false | false | false | false |
brentsimmons/Frontier
|
BeforeTheRename/FrontierVerbs/FrontierVerbs/VerbTables/HTMLVerbs.swift
|
1
|
5495
|
//
// HTMLVerbs.swift
// FrontierVerbs
//
// Created by Brent Simmons on 4/15/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
struct HTMLVerbs: VerbTable {
private enum Verb: String {
case processMacros = "processmacros"
case urlDecode = "urldecode"
case urlEncode = "urlEncode"
case parseHTTPArgs = "parseHTTPArgs"
case iso8859Encode = "iso8859encode"
case getGIFHeightWidth = "getgifheightwidth"
case getJPEGHeightWidth = "getjpegheightwidth"
case buildPageTable = "buildpagetable"
case refGlossary = "refglossary"
case getPref = "getpref"
case getOneDirective = "getonedirective"
case runDirective = "rundirective"
case runDirectives = "rundirectives"
case runOutlineDirectives = "runoutlinedirectives"
case cleanForExport = "cleanforexport"
case normalizeName = "normalizename"
case glossaryPatcher = "glossarypatcher"
case expandURLs = "expandurls"
case traversalSkip = "traversalskip"
case getPageTableAddress = "getpagetableaddress"
case neuterMacros = "neutermacros"
case neuterTags = "neutertags"
case drawCalendar = "drawcalendar"
}
static func evaluate(_ lowerVerbName: String, _ params: VerbParams, _ verbAppDelegate: VerbAppDelegate) throws -> Value {
guard let verb = Verb(rawValue: lowerVerbName) else {
throw LangError(.verbNotFound)
}
do {
switch verb {
case .processMacros:
return try processMacros(params)
case .urlDecode:
return try urlDecode(params)
case .urlEncode:
return try urlEncode(params)
case .parseHTTPArgs:
return try parseHTTPArgs(params)
case .iso8859Encode:
return try iso8859Encode(params)
case .getGIFHeightWidth:
return try getGIFHeightWidth(params)
case .getJPEGHeightWidth:
return try getJPEGHeightWidth(params)
case .buildPageTable:
return try buildPageTable(params)
case .refGlossary:
return try refGlossary(params)
case .getPref:
return try getPref(params)
case .getOneDirective:
return try getOneDirective(params)
case .runDirective:
return try runDirective(params)
case .runDirectives:
return try runDirectives(params)
case .runOutlineDirectives:
return try runOutlineDirectives(params)
case .cleanForExport:
return try cleanForExport(params)
case .normalizeName:
return try normalizeName(params)
case .glossaryPatcher:
return try glossaryPatcher(params)
case .expandURLs:
return try expandURLs(params)
case .traversalSkip:
return try traversalSkip(params)
case .getPageTableAddress:
return try getPageTableAddress(params)
case .neuterMacros:
return try neuterMacros(params)
case .neuterTags:
return try neuterTags(params)
case .drawCalendar:
return try drawCalendar(params)
}
}
catch { throw error }
}
}
private extension HTMLVerbs {
static func processMacros(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func urlDecode(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func urlEncode(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func parseHTTPArgs(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func iso8859Encode(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getGIFHeightWidth(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getJPEGHeightWidth(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func buildPageTable(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func refGlossary(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getPref(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getOneDirective(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func runDirective(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func runDirectives(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func runOutlineDirectives(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func cleanForExport(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func normalizeName(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func glossaryPatcher(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func expandURLs(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func traversalSkip(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getPageTableAddress(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func neuterMacros(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func neuterTags(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func drawCalendar(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
}
|
gpl-2.0
|
5fba767c488d3b660128d41e1e218490
| 24.201835 | 122 | 0.727339 | 3.802076 | false | false | false | false |
honghaoz/CrackingTheCodingInterview
|
Swift/LeetCode/Binary Search/33_Search in Rotated Sorted Array.swift
|
1
|
5076
|
// 33_Search in Rotated Sorted Array
// https://leetcode.com/problems/search-in-rotated-sorted-array/
//
// Created by Honghao Zhang on 9/16/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
//
//(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
//
//You are given a target value to search. If found in the array return its index, otherwise return -1.
//
//You may assume no duplicate exists in the array.
//
//Your algorithm's runtime complexity must be in the order of O(log n).
//
//Example 1:
//
//Input: nums = [4,5,6,7,0,1,2], target = 0
//Output: 4
//Example 2:
//
//Input: nums = [4,5,6,7,0,1,2], target = 3
//Output: -1
//
// 在一个rotated sorted array中找数字
import Foundation
class Num33 {
// MARK: - Binary search
// 切除可以确认丢掉的那半边
func search2(_ nums: [Int], _ target: Int) -> Int {
guard nums.count > 0 else { return -1 }
var start = 0
var end = nums.count - 1
while start + 1 < end {
let mid = start + (end - start) / 2
if nums[mid] == target {
return mid
}
// Cut first part
if nums[start] < nums[mid] {
if nums[start] <= target && target <= nums[mid] {
// 可以确保target在左区间
end = mid
}
else {
// 剩下的情况不细分
start = mid
}
}
// Cut second part
else {
if nums[mid] <= target && target <= nums[end] {
start = mid
}
else {
end = mid
}
}
}
if nums[start] == target {
return start
}
if nums[end] == target {
return end
}
return -1
}
// Binary search
func search(_ nums: [Int], _ target: Int) -> Int {
guard nums.count > 0 else { return -1 }
var start = 0
var end = nums.count - 1
if nums[0] < nums[nums.count - 1] {
// normal sorted array
while start + 1 < end {
let mid = start + (end - start) / 2
if nums[mid] < target {
start = mid
}
else if nums[mid] > target {
end = mid
}
else {
return mid
}
}
if nums[start] == target {
return start
}
else if nums[end] == target {
return end
}
else {
return -1
}
}
else if nums[0] > nums[nums.count - 1] {
// rotated sorted array
if target >= nums[0] {
// target is on the left part
while start + 1 < end {
let mid = start + (end - start) / 2
if nums[mid] < nums[start] {
// mid is on the right part, should move end
end = mid
}
else {
// mid is on the left part, should compare with the target
if nums[mid] < target {
start = mid
}
else if nums[mid] > target {
end = mid
}
else {
return mid
}
}
}
if nums[start] == target {
return start
}
else if nums[end] == target {
return end
}
else {
return -1
}
}
else {
// target is on the right part
while start + 1 < end {
let mid = start + (end - start) / 2
if nums[mid] > nums[end] {
// mid is on the left part, should move start
start = mid
}
else {
// mid is on the right part, compare with the target
if nums[mid] < target {
start = mid
}
else if nums[mid] > target {
end = mid
}
else {
return mid
}
}
}
if nums[start] == target {
return start
}
else if nums[end] == target {
return end
}
else {
return -1
}
}
}
// only 1 element
if nums[0] == target {
return 0
} else {
return -1
}
}
/// From the old file:
// [ )
// func search(_ nums: [Int], _ target: Int) -> Int {
// guard nums.count > 0 else { return -1 }
// var start = 0
// var end = nums.count
// while start != end {
// var mid = start + (end - start) / 2
// if nums[mid] == target {
// return mid
// }
// if nums[start] <= nums[mid] {
// if nums[start] <= target && target < nums[mid] {
// end = mid
// }
// else {
// start = mid + 1
// }
// }
// else {
// if nums[mid] < target && target <= nums[end - 1] {
// start = mid + 1
// }
// else {
// end = mid
// }
// }
// }
// return -1
// }
// [ ]
}
|
mit
|
f80caa7d34db86de2bd8045236d746be
| 22.27907 | 102 | 0.437363 | 3.79742 | false | false | false | false |
yanniks/DHBW-MDG-Shared-Crossplatform
|
Classes/DHTableViewCell.swift
|
1
|
937
|
//
// DHTableViewCell.swift
// DHBW Stuttgart
//
// Created by Yannik Ehlert on 08.11.16.
// Copyright © 2016 Yannik Ehlert. All rights reserved.
//
#if os(iOS)
import UIKit
public typealias DHTableViewCellStyle = UITableViewCellStyle
public typealias DHTableViewCell = UITableViewCell
#elseif os(macOS)
import Cocoa
public enum DHTableViewCellStyle { case `default`, value1, value2, subtitle }
public class DHTableViewCell: NSTableCellView {
var cellTitle : String! = nil
var cellDescription : String! = nil
var cellImage : NSImage! = nil
var customContents = [String : String]()
init(style: DHTableViewCellStyle, reuseIdentifier: String?) {
super.init(frame: NSRect(x: 0, y: 0, width: 50, height: 50))
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
}
}
#endif
|
apache-2.0
|
2399ae4de165dd37c303ab62fb5bdd55
| 27.363636 | 81 | 0.630342 | 4.353488 | false | false | false | false |
rock-n-code/Kashmir
|
Kashmir/Shared/Features/Data Stack/Managers/DataStack.swift
|
1
|
7820
|
//
// DataStack.swift
// Kashmir
//
// Created by Javier Cicchelli on 06/08/16.
// Copyright © 2016 Rock & Code. All rights reserved.
//
import CoreData
/**
This class simplifies the creation and management of multiple Core Data stack by handling the creation of the `NSPersistentContainer` instances.
*/
public class DataStack {
// MARK: Constants
/// Returns a singleton instance of the `DataStack` class.
public static let manager = DataStack()
// MARK: Properties
/// Dictionary which uses model names as keys and initialized containers as values.
var containers: [String : NSPersistentContainer]
// MARK: Initializations
/**
Default initializer.
- returns: A `DataStack` instance with an empty containers dictionary.
*/
init() {
containers = [:]
}
// MARK: Functions
/**
Checks if a container associated with a model has been initialized.
- parameter model: The model name of the container to check.
- returns: A `Bool` instance which represents whether the container is initialized or not.
*/
public func isInitialized(_ model: String) -> Bool {
return containers.keys.contains(model)
}
/**
Add a container to its dictionary.
- parameters:
- model: The model name in which a container will be initialized.
- type: The store type in which a container will be initialized.
- throws: A `DataStackError` type error in case during the execution of this method.
*/
public func add(_ model: String,
of type: DataStack.Store = .sql) throws {
try validate(model,
for: [.modelNameIsNotEmpty])
guard let url = Bundle.url(for: model,
with: "momd") else {
throw DataStackError.objectModelNotFound
}
guard let objectModel = NSManagedObjectModel(contentsOf: url) else {
throw DataStackError.objectModelNotCreated
}
try validate(model,
for: [.containerNotExists])
let container = NSPersistentContainer(name: model,
managedObjectModel: objectModel)
let defaultDescription = makeDescription(for: model,
with: type)
container.persistentStoreDescriptions = [defaultDescription]
container.loadPersistentStores { storeDescription, error in
if let error = error as NSError? {
// TODO: Throw the error back to the caller.
fatalError("Unresolved error \(error), \(error.userInfo)")
}
else {
self.containers[model] = container
}
}
}
/**
Remove a container from its dictionary.
- parameter model: The model name in which a container has been initialized.
- throws: A `DataStackError` type error in case during the execution of this method.
*/
public func remove(_ model: String) throws {
try validate(model,
for: [.modelNameIsNotEmpty,
.containerExists])
guard let container = containers[model] else {
throw DataStackError.containerNotFound
}
let coordinator = container.persistentStoreCoordinator
for store in coordinator.persistentStores {
guard let url = store.url else {
throw DataStackError.storeUrlNotFound
}
try coordinator.remove(store)
if store.type != NSInMemoryStoreType {
var urls = [url.path]
if store.type == NSSQLiteStoreType {
urls += ["\(url.path)-shm", "\(url.path)-wal"]
}
try urls.forEach {
try FileManager.default.removeItem(atPath: $0)
}
}
}
containers[model] = nil
}
/**
Get the managed object context associated with the main queue from a given container.
- parameter model: The model name in which a container has been initialized.
- throws: A `DataStackError` type error in case during the execution of this method.
- returns: The managed object context from the requested container.
*/
public func foreContext(of model: String) throws -> NSManagedObjectContext {
try validate(model,
for: [.modelNameIsNotEmpty,
.containerExists])
guard let context = containers[model]?.viewContext else {
throw DataStackError.contextNotFound
}
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
context.undoManager = nil
context.shouldDeleteInaccessibleFaults = true
context.automaticallyMergesChangesFromParent = true
return context
}
/**
Get a new private managed object context associated with the concurrent queue from a given container.
- parameter model: The model name in which a container has been initialized.
- throws: A `DataStackError` type error in case during the execution of this method.
- returns: A managed object context from the requested container.
*/
public func backContext(of model: String) throws -> NSManagedObjectContext {
try validate(model,
for: [.modelNameIsNotEmpty,
.containerExists])
guard let context = containers[model]?.newBackgroundContext() else {
throw DataStackError.contextNotCreated
}
context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
context.undoManager = nil
context.shouldDeleteInaccessibleFaults = true
context.automaticallyMergesChangesFromParent = true
return context
}
/**
Attemps to commit unsaved changes registered on the managed object context associated with the main queue for each and every container in the dictionary.
- throws: A `DataStackError` type error in case during the execution of this method.
*/
public func save() throws {
try containers.forEach { name, container in
let context = container.viewContext
if context.hasChanges {
try context.save()
}
}
}
// MARK: Helpers
/**
Makes a default persistent store description tailored to a given model and its respective store type.
- parameters:
- model: The model name in which a container has been initialized.
- type: The store type in which a container will be initialized.
- returns: A persistent store description with all the relevant configuration to initialize a container.
*/
fileprivate func makeDescription(for model: String,
with type: DataStack.Store) -> NSPersistentStoreDescription {
let description = NSPersistentStoreDescription()
description.configuration = "Default"
description.type = type.rawValue
description.isReadOnly = false
description.shouldAddStoreAsynchronously = false
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
if type != .inMemory {
let directory = NSPersistentContainer.defaultDirectoryURL()
description.url = directory.appendingPathComponent("\(model.lowercased()).\(type.extensionValue)")
}
return description
}
/**
Validates a model and/or its container based on a provided list of validation options.
- parameters:
- model: The model name in which a container has been initialized.
- validations: A list of validation options to validate.
- throws: A `DataStackError` type error in case in case any of the requested validation checks fails.
*/
fileprivate func validate(_ model: String,
for validations: [DataStack.Validation]) throws {
try validations.forEach {
switch $0 {
case .modelNameIsNotEmpty where model.isEmpty:
throw DataStackError.containerNameIsEmpty
case .containerExists where !containers.keys.contains(model):
throw DataStackError.containerNameNotExists
case .containerNotExists where containers.keys.contains(model):
throw DataStackError.containerNameExists
default:
return
}
}
}
}
|
mit
|
5b50de64e9d15841c20042baf326fafa
| 30.401606 | 154 | 0.688195 | 4.735918 | false | false | false | false |
sicardf/MyRide
|
MyRide/UI/SideMenu/SideMenuViewController.swift
|
1
|
2839
|
//
// SideMenuViewController.swift
// MyRide
//
// Created by Flavien SICARD on 24/05/2017.
// Copyright © 2017 sicardf. All rights reserved.
//
import UIKit
import CoreData
class SideMenuViewController: UIViewController, MenuDelegate {
private var menuView: MenuView!
private var gestureView: UIView!
var mapsViewController: MapsViewController!
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refreshTableView() {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "History")
do {
menuView.history = try managedContext.fetch(fetchRequest)
menuView.tableView.reloadData()
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
private func setup() {
view.backgroundColor = UIColor(white: 1, alpha: 0)
menuView = MenuView(frame: CGRect(x: 0, y: 0, width: 275, height: UIScreen.main.bounds.height))
menuView.delegate = self
//mapboxView.delegate = self
view.addSubview(menuView)
refreshTableView()
self.gestureView = UIView(frame: CGRect(x: 275, y: 0, width: UIScreen.main.bounds.width - 275, height: UIScreen.main.bounds.height))
self.gestureView.backgroundColor = UIColor(white: 1, alpha: 0)
self.gestureView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(SideMenuViewController.hiddenMenu)))
view.addSubview(self.gestureView)
}
public func displayMenu() {
refreshTableView()
UIView.animate(withDuration: 0.5) {
self.view.frame.origin.x = 0
}
}
public func hiddenMenu() {
UIView.animate(withDuration: 0.5) {
self.view.frame.origin.x = -self.view.frame.size.width
}
}
func clickHistory(address: String, lat: String, lng: String) {
hiddenMenu()
self.mapsViewController.updateLocation(address: address, lat: Double(lat)!, lng: Double(lng)!)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
9ee10052168425f2717c3440e237ac30
| 29.516129 | 140 | 0.635307 | 4.73 | false | false | false | false |
MrBendel/InfinityScrollView
|
APLoopingScrollView/APLoopingScrollView/Examples/LoopingScrollViewWithScaling.swift
|
2
|
1076
|
//
// LoopingScrollViewWithScaling.swift
// APLoopingScrollView
//
// Created by Andrew Poes on 9/14/15.
// Copyright © 2015 Andrew Poes. All rights reserved.
//
import UIKit
class LoopingScrollViewWithScaling: APLoopingScrollView {
var edgeScale: CGFloat = 0.9
override func updateViews() {
// reset the transforms
for indexPath in self.visibleItems {
if let view = self.view(forIndexPath: indexPath) {
view.transform = CGAffineTransformIdentity
}
}
// update the frames
super.updateViews()
// set the transforms
let centerX = CGRectGetWidth(self.frame) * 0.5
for indexPath in self.visibleItems {
if let view = self.view(forIndexPath: indexPath) {
let progX = (view.center.x - self.contentOffset.x - centerX) / centerX
let scale = 1 - fabs(progX * (1 - edgeScale))
let transform = CGAffineTransformMakeScale(scale, scale)
view.transform = transform
}
}
}
}
|
mit
|
0f94d0273c5e141af50ca86d322ae444
| 31.606061 | 86 | 0.602791 | 4.613734 | false | false | false | false |
egorio/devslopes-showcase
|
devslopes-showcase/Controllers/FeedViewController.swift
|
1
|
5226
|
//
// FeedViewController.swift
// devslopes-showcase
//
// Created by Egorio on 3/15/16.
// Copyright © 2016 Egorio. All rights reserved.
//
import UIKit
import Firebase
import Alamofire
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var postField: MaterialTextField!
@IBOutlet weak var chooseImageButton: UIImageView!
var posts = [Post]()
var imagePicker: UIImagePickerController!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 300
imagePicker = UIImagePickerController()
imagePicker.delegate = self
DataService.instance.posts.observeEventType(.Value, withBlock: { (snapshot) in
guard let snapshots = snapshot.children.allObjects as? [FDataSnapshot] else {
return
}
self.posts = []
for snapshot in snapshots {
if let dictionary = snapshot.value as? [String: AnyObject] {
let post = Post(id: snapshot.key, dictionary: dictionary)
self.posts.append(post)
}
}
self.tableView.reloadData()
})
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = (tableView.dequeueReusableCellWithIdentifier(Identifier.cellFeed) as? FeedTableCell) ?? FeedTableCell()
let post = posts[indexPath.row]
cell.configure(post)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let post = posts[indexPath.row]
if post.imageUrl == nil {
return 200
}
return tableView.estimatedRowHeight
}
/*
* Shows error alert
*/
func showErrorAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
}
extension FeedViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String: AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
chooseImageButton.image = image
chooseImageButton.highlighted = true
}
@IBAction func chooseImage(sender: UITapGestureRecognizer) {
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func createPost(sender: AnyObject) {
guard let text = postField.text where text != "" else {
return showErrorAlert("Post text is required", message: "Please enter post text before publish")
}
if let image = chooseImageButton.image where chooseImageButton.highlighted == true {
let url = NSURL(string: "https://post.imageshack.us/upload_api.php")!
let file = UIImageJPEGRepresentation(image, 0.5)!
let key = "12DJKPSU5fc3afbd01b1630cc718cae3043220f3".dataUsingEncoding(NSUTF8StringEncoding)!
let json = "json".dataUsingEncoding(NSUTF8StringEncoding)!
Alamofire.upload(.POST, url,
multipartFormData: { (multipartFormData) in
multipartFormData.appendBodyPart(data: file, name: "fileupload", fileName: "image", mimeType: "image/jpg")
multipartFormData.appendBodyPart(data: key, name: "key")
multipartFormData.appendBodyPart(data: json, name: "format")
},
encodingCompletion: { (encodingResult) in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON(completionHandler: { (response) in
if let info = response.result.value as? [String: AnyObject],
let links = info["links"] as? [String: AnyObject],
let imageUrl = links["image_link"] as? String {
self.savePost(["description": text, "imageUrl": imageUrl, "likes": 0])
}
})
case.Failure(let error):
print(error)
}
})
}
else {
savePost(["description": text, "likes": 0])
}
}
func savePost(post: [String: AnyObject]) {
DataService.instance.createPost(post)
postField.text = ""
chooseImageButton.highlighted = false
chooseImageButton.image = UIImage(named: "camera")
}
}
|
mit
|
b437c824eb665de4a9e6973c4afe109d
| 34.787671 | 138 | 0.615885 | 5.288462 | false | false | false | false |
CKOTech/checkoutkit-ios
|
CheckoutKit/CheckoutKit/CardInfo.swift
|
1
|
3910
|
//
// CardInfo.swift
// CheckoutKit
//
// Created by Manon Henrioux on 20/08/2015.
//
//
import Foundation
/** Class containing the card information used for the validity checks in CardValidator */
public struct CardInfo: Equatable {
fileprivate static let DEFAULT_CARD_FORMAT: String = "(\\d{1,4})"
public static let MAESTRO = CardInfo(name: "maestro", pattern: "(5[06-9]|6[37])[0-9]{10,17}$", format: DEFAULT_CARD_FORMAT, cardLength: [12, 13, 14, 15, 16, 17, 18, 19], cvvLength: [3], luhn: true, supported: true)
public static let MASTERCARD = CardInfo(name: "mastercard", pattern: "^5[1-5][0-9]{14}$", format: DEFAULT_CARD_FORMAT, cardLength: [16,17], cvvLength: [3], luhn: true, supported: true)
public static let MASTERCARD2 = CardInfo(name: "mastercard2", pattern: "^(222[1-9]|22[3-9]\\d|2[3-6]\\d{2}|27[0-1]\\d|2720|5[1-5])", format: DEFAULT_CARD_FORMAT, cardLength: [16,17], cvvLength: [3], luhn: true, supported: true)
public static let DINERSCLUB = CardInfo(name: "dinersclub", pattern: "^3(?:0[0-5]|[68][0-9])?[0-9]{11}$", format: "(\\d{1,4})(\\d{1,6})?(\\d{1,4})?", cardLength: [14], cvvLength: [3], luhn: true, supported: true)
public static let LASER = CardInfo(name: "laser", pattern: "^(6304|6706|6709|6771)[0-9]{12,15}$", format: DEFAULT_CARD_FORMAT, cardLength: [16,17, 18, 19], cvvLength: [3], luhn: true, supported: false)
public static let JCB = CardInfo(name: "jcb", pattern: "^(?:2131|1800|35[0-9]{3})[0-9]{11}$", format: DEFAULT_CARD_FORMAT, cardLength: [16], cvvLength: [3], luhn: true, supported: true)
public static let UNIONPAY = CardInfo(name: "unionpay", pattern: "^(62[0-9]{14,17})$", format: DEFAULT_CARD_FORMAT, cardLength: [16,17, 18, 19], cvvLength: [3], luhn: false, supported: false)
public static let DISCOVER = CardInfo(name: "discover", pattern: "^6(?:011|5[0-9]{2})[0-9]{12}$", format: DEFAULT_CARD_FORMAT, cardLength: [16], cvvLength: [3], luhn: true, supported: true)
public static let AMEX = CardInfo(name: "amex", pattern: "^3[47][0-9]{13}$", format: "^(\\d{1,4})(\\d{1,6})?(\\d{1,5})?$", cardLength: [15], cvvLength: [4], luhn: true, supported: true)
public static let VISA = CardInfo(name: "visa", pattern: "^4[0-9]{12}(?:[0-9]{3})?$", format: DEFAULT_CARD_FORMAT, cardLength: [13, 16], cvvLength: [3], luhn: true, supported: true)
public static let cards: [CardInfo] = [.MAESTRO, .MASTERCARD, .MASTERCARD2, .DINERSCLUB, .LASER, .JCB, .UNIONPAY, .DISCOVER, .AMEX, .VISA]
public let name: String
public let pattern: String
public let format: String
public let cardLength: [Int]
public let cvvLength: [Int]
public let luhn: Bool
public let supported: Bool
/**
Default constructor
@param name name of the card
@param pattern regular expression matching the card's code
@param format default card display format
@param cardLength array containing all the possible lengths of the card's code
@param cvvLength array containing all the possible lengths of the card's CVV
@param luhn does the card's number respects the luhn validation or not
@param supported is this card usable with Checkout services
*/
fileprivate init(name: String, pattern: String, format: String, cardLength: [Int], cvvLength: [Int], luhn: Bool, supported: Bool) {
self.name = name
self.pattern = pattern
self.format = format
self.cardLength = cardLength
self.cvvLength = cvvLength
self.luhn = luhn
self.supported = supported
}
}
/*
Function used for testing purposes, returns true if the fields of both instances are identical
*/
public func ==(lhs: CardInfo, rhs: CardInfo) -> Bool {
return lhs.format == rhs.format && lhs.pattern == rhs.pattern && lhs.luhn == rhs.luhn && lhs.supported == rhs.supported && lhs.name == rhs.name
}
|
mit
|
53210a63ba6abf13d28f9bc59c1bcf1b
| 51.837838 | 231 | 0.650895 | 3.252912 | false | false | false | false |
jtbandes/swift
|
test/Constraints/existential_metatypes.swift
|
13
|
2832
|
// RUN: %target-typecheck-verify-swift
protocol P {}
protocol Q {}
protocol PP: P {}
var qp: Q.Protocol
var pp: P.Protocol = qp // expected-error{{cannot convert value of type 'Q.Protocol' to specified type 'P.Protocol'}}
var qt: Q.Type
qt = qp // expected-error{{cannot assign value of type 'Q.Protocol' to type 'Q.Type'}}
qp = qt // expected-error{{cannot assign value of type 'Q.Type' to type 'Q.Protocol'}}
var pt: P.Type = qt // expected-error{{cannot convert value of type 'Q.Type' to specified type 'P.Type'}}
pt = pp // expected-error{{cannot assign value of type 'P.Protocol' to type 'P.Type'}}
pp = pt // expected-error{{cannot assign value of type 'P.Type' to type 'P.Protocol'}}
var pqt: (P & Q).Type
pt = pqt
qt = pqt
var pqp: (P & Q).Protocol
pp = pqp // expected-error{{cannot assign value of type '(P & Q).Protocol' to type 'P.Protocol'}}
qp = pqp // expected-error{{cannot assign value of type '(P & Q).Protocol' to type 'Q.Protocol'}}
var ppp: PP.Protocol
pp = ppp // expected-error{{cannot assign value of type 'PP.Protocol' to type 'P.Protocol'}}
var ppt: PP.Type
pt = ppt
var at: Any.Type
at = pt
var ap: Any.Protocol
ap = pp // expected-error{{cannot assign value of type 'P.Protocol' to type 'Any.Protocol'}}
ap = pt // expected-error{{cannot assign value of type 'P.Type' to type 'Any.Protocol'}}
// Meta-metatypes
protocol Toaster {}
class WashingMachine : Toaster {}
class Dryer : WashingMachine {}
class HairDryer {}
let a: Toaster.Type.Protocol = Toaster.Type.self
let b: Any.Type.Type = Toaster.Type.self // expected-error {{cannot convert value of type 'Toaster.Type.Protocol' to specified type 'Any.Type.Type'}}
let c: Any.Type.Protocol = Toaster.Type.self // expected-error {{cannot convert value of type 'Toaster.Type.Protocol' to specified type 'Any.Type.Protocol'}}
let d: Toaster.Type.Type = WashingMachine.Type.self
let e: Any.Type.Type = WashingMachine.Type.self
let f: Toaster.Type.Type = Dryer.Type.self
let g: Toaster.Type.Type = HairDryer.Type.self // expected-error {{cannot convert value of type 'HairDryer.Type.Type' to specified type 'Toaster.Type.Type'}}
let h: WashingMachine.Type.Type = Dryer.Type.self // expected-error {{cannot convert value of type 'Dryer.Type.Type' to specified type 'WashingMachine.Type.Type'}}
func generic<T : WashingMachine>(_ t: T.Type) {
let _: Toaster.Type.Type = type(of: t)
}
// rdar://problem/20780797
protocol P2 {
init(x: Int)
var elements: [P2] {get}
}
extension P2 {
init() { self.init(x: 5) }
}
func testP2(_ pt: P2.Type) {
pt.init().elements // expected-warning {{expression of type '[P2]' is unused}}
}
// rdar://problem/21597711
protocol P3 {
func withP3(_ fn: (P3) -> ())
}
class Something {
func takeP3(_ p: P3) { }
}
func testP3(_ p: P3, something: Something) {
p.withP3(Something.takeP3(something))
}
|
apache-2.0
|
3573edb618139679c3ae0de0f5353be3
| 31.551724 | 163 | 0.695268 | 3.136213 | false | false | false | false |
MukeshKumarS/Swift
|
test/SILOptimizer/definite_init_diagnostics.swift
|
1
|
31600
|
// RUN: %target-swift-frontend -emit-sil -sdk %S/../SILGen/Inputs %s -I %S/../SILGen/Inputs -enable-source-import -parse-stdlib -o /dev/null -verify
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Swift
import gizmo
func markUsed<T>(t: T) {}
// These are tests for definite initialization, which is implemented by the
// memory promotion pass.
func test1() -> Int {
// expected-warning @+1 {{variable 'a' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
var a : Int // expected-note {{variable defined here}}
return a // expected-error {{variable 'a' used before being initialized}}
}
func takes_inout(inout a: Int) {}
func takes_closure(fn: () -> ()) {}
class SomeClass {
var x : Int // expected-note {{'self.x' not initialized}}
var computedProperty : Int { return 42 }
init() { x = 0 }
init(b : Bool) {
if (b) {}
} // expected-error {{return from initializer without initializing all stored properties}}
func baseMethod() {}
}
struct SomeStruct { var x = 1 }
func test2() {
// inout.
var a1 : Int // expected-note {{variable defined here}}
takes_inout(&a1) // expected-error {{variable 'a1' passed by reference before being initialized}}
var a2 = 4
takes_inout(&a2) // ok.
var a3 : Int
a3 = 4
takes_inout(&a3) // ok.
// Address-of with Builtin.addressof.
var a4 : Int // expected-note {{variable defined here}}
Builtin.addressof(&a4) // expected-error {{address of variable 'a4' taken before it is initialized}}
// Closures.
// expected-warning @+1 {{variable 'b1' was never mutated}} {{3-6=let}}
var b1 : Int // expected-note {{variable defined here}}
takes_closure { // expected-error {{variable 'b1' captured by a closure before being initialized}}
markUsed(b1)
}
var b1a : Int // expected-note {{variable defined here}}
takes_closure { // expected-error {{variable 'b1a' captured by a closure before being initialized}}
b1a += 1
markUsed(b1a)
}
var b2 = 4
takes_closure { // ok.
markUsed(b2)
}
b2 = 1
var b3 : Int
b3 = 4
takes_closure { // ok.
markUsed(b3)
}
var b4 : Int?
takes_closure { // ok.
markUsed(b4!)
}
b4 = 7
// Structs
var s1 : SomeStruct
s1 = SomeStruct() // ok
_ = s1
var s2 : SomeStruct // expected-note {{variable defined here}}
s2.x = 1 // expected-error {{struct 's2' must be completely initialized before a member is stored to}}
// Classes
// expected-warning @+1 {{variable 'c1' was never mutated}} {{3-6=let}}
var c1 : SomeClass // expected-note {{variable defined here}}
markUsed(c1.x) // expected-error {{variable 'c1' used before being initialized}}
let c2 = SomeClass()
markUsed(c2.x) // ok
// Weak
weak var w1 : SomeClass?
_ = w1 // ok: default-initialized
weak var w2 = SomeClass()
_ = w2 // ok
// Unowned. This is immediately crashing code (it causes a retain of a
// released object) so it should be diagnosed with a warning someday.
// expected-warning @+1 {{variable 'u1' was never mutated; consider changing to 'let' constant}} {{11-14=let}}
unowned var u1 : SomeClass // expected-note {{variable defined here}}
_ = u1 // expected-error {{variable 'u1' used before being initialized}}
unowned let u2 = SomeClass()
_ = u2 // ok
}
// Tuple field sensitivity.
func test4() {
// expected-warning @+1 {{variable 't1' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
var t1 = (1, 2, 3)
markUsed(t1.0 + t1.1 + t1.2) // ok
// expected-warning @+1 {{variable 't2' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
var t2 : (Int, Int, Int) // expected-note 3 {{variable defined here}}
markUsed(t2.0) // expected-error {{variable 't2.0' used before being initialized}}
markUsed(t2.1) // expected-error {{variable 't2.1' used before being initialized}}
markUsed(t2.2) // expected-error {{variable 't2.2' used before being initialized}}
var t3 : (Int, Int, Int) // expected-note {{variable defined here}}
t3.0 = 1; t3.2 = 42
markUsed(t3.0)
markUsed(t3.1) // expected-error {{variable 't3.1' used before being initialized}}
markUsed(t3.2)
// Partially set, wholey read.
var t4 : (Int, Int, Int) // expected-note 1 {{variable defined here}}
t4.0 = 1; t4.2 = 42
_ = t4 // expected-error {{variable 't4.1' used before being initialized}}
// Subelement sets.
var t5 : (a : (Int, Int), b : Int) // expected-note {{variable defined here}}
t5.a = (1,2)
markUsed(t5.a.0)
markUsed(t5.a.1)
markUsed(t5.b) // expected-error {{variable 't5.b' used before being initialized}}
var t6 : (a : (Int, Int), b : Int) // expected-note {{variable defined here}}
t6.b = 12; t6.a.1 = 1
markUsed(t6.a.0) // expected-error {{variable 't6.a.0' used before being initialized}}
markUsed(t6.a.1)
markUsed(t6.b)
}
func tupleinout(inout a: (lo: Int, hi: Int)) {
markUsed(a.0) // ok
markUsed(a.1) // ok
}
// Address only types
func test5<T>(x: T, y: T) {
var a : ((T, T), T) // expected-note {{variable defined here}}
a.0 = (x, y)
_ = a // expected-error {{variable 'a.1' used before being initialized}}
}
struct IntFloatStruct { var a = 1, b = 2.0 }
func test6() -> Int {
var a = IntFloatStruct()
a.a = 1
a.b = 2
return a.a
}
// Control flow.
func test7(cond: Bool) {
var a : Int
if cond { a = 42 } else { a = 17 }
markUsed(a) // ok
var b : Int // expected-note {{variable defined here}}
if cond { } else { b = 17 }
markUsed(b) // expected-error {{variable 'b' used before being initialized}}
}
protocol SomeProtocol {
func protoMe()
}
protocol DerivedProtocol : SomeProtocol {}
func existentials(i: Int, dp: DerivedProtocol) {
// expected-warning @+1 {{variable 'a' was written to, but never read}}
var a : Any = ()
a = i
// expected-warning @+1 {{variable 'b' was written to, but never read}}
var b : Any
b = ()
// expected-warning @+1 {{variable 'c' was never used}} {{7-8=_}}
var c : Any // no uses.
// expected-warning @+1 {{variable 'd1' was never mutated}} {{3-6=let}}
var d1 : Any // expected-note {{variable defined here}}
_ = d1 // expected-error {{variable 'd1' used before being initialized}}
// expected-warning @+1 {{variable 'e' was never mutated}} {{3-6=let}}
var e : SomeProtocol // expected-note {{variable defined here}}
e.protoMe() // expected-error {{variable 'e' used before being initialized}}
var f : SomeProtocol = dp // ok, init'd by existential upcast.
// expected-warning @+1 {{variable 'g' was never mutated}} {{3-6=let}}
var g : DerivedProtocol // expected-note {{variable defined here}}
f = g // expected-error {{variable 'g' used before being initialized}}
_ = f
}
// Tests for top level code.
var g1 : Int // expected-note {{variable defined here}}
var g2 : Int = 42
func testTopLevelCode() { // expected-error {{variable 'g1' used by function definition before being initialized}}
markUsed(g1)
markUsed(g2)
}
var (g3,g4) : (Int,Int) // expected-note 2 {{variable defined here}}
class DITLC_Class {
init() { // expected-error {{variable 'g3' used by function definition before being initialized}}
markUsed(g3)
}
deinit { // expected-error {{variable 'g4' used by function definition before being initialized}}
markUsed(g4)
}
}
struct EmptyStruct {}
func useEmptyStruct(a: EmptyStruct) {}
func emptyStructTest() {
// <rdar://problem/20065892> Diagnostic for an uninitialized constant calls it a variable
let a : EmptyStruct // expected-note {{constant defined here}}
useEmptyStruct(a) // expected-error {{constant 'a' used before being initialized}}
var (b,c,d) : (EmptyStruct,EmptyStruct,EmptyStruct) // expected-note 2 {{variable defined here}}
c = EmptyStruct()
useEmptyStruct(b) // expected-error {{variable 'b' used before being initialized}}
useEmptyStruct(c)
useEmptyStruct(d) // expected-error {{variable 'd' used before being initialized}}
var (e,f) : (EmptyStruct,EmptyStruct)
(e, f) = (EmptyStruct(),EmptyStruct())
useEmptyStruct(e)
useEmptyStruct(f)
var g : (EmptyStruct,EmptyStruct)
g = (EmptyStruct(),EmptyStruct())
useEmptyStruct(g.0)
useEmptyStruct(g.1)
}
func takesTuplePair(inout a : (SomeClass, SomeClass)) {}
// This tests cases where an store might be an init or assign based on control
// flow path reaching it.
func conditionalInitOrAssign(c : Bool, x : Int) {
var t : Int // Test trivial types.
if c {
t = 0
}
if c {
t = x
}
t = 2
_ = t
// Nontrivial type
var sc : SomeClass
if c {
sc = SomeClass()
}
sc = SomeClass()
_ = sc
// Tuple element types
var tt : (SomeClass, SomeClass)
if c {
tt.0 = SomeClass()
} else {
tt.1 = SomeClass()
}
tt.0 = SomeClass()
tt.1 = tt.0
var t2 : (SomeClass, SomeClass) // expected-note {{variable defined here}}
t2.0 = SomeClass()
takesTuplePair(&t2) // expected-error {{variable 't2.1' passed by reference before being initialized}}
}
enum NotInitializedUnion {
init() {
} // expected-error {{return from enum initializer method without storing to 'self'}}
case X
case Y
}
extension NotInitializedUnion {
init(a : Int) {
} // expected-error {{return from enum initializer method without storing to 'self'}}
}
enum NotInitializedGenericUnion<T> {
init() {
} // expected-error {{return from enum initializer method without storing to 'self'}}
case X
}
class SomeDerivedClass : SomeClass {
var y : Int
override init() {
y = 42 // ok
super.init()
}
init(a : Bool) {
super.init() // expected-error {{property 'self.y' not initialized at super.init call}}
}
init(a : Bool, b : Bool) {
// x is a superclass member. It cannot be used before we are initialized.
x = 17 // expected-error {{use of 'self' in property access 'x' before super.init initializes self}}
y = 42
super.init()
}
init(a : Bool, b : Bool, c : Bool) {
y = 42
super.init()
}
init(a : Bool, b : Bool, c : Bool, d : Bool) {
y = 42
super.init()
super.init() // expected-error {{super.init called multiple times in initializer}}
}
init(a : Bool, b : Bool, c : Bool, d : Bool, e : Bool) {
super.init() // expected-error {{property 'self.y' not initialized at super.init call}}
super.init() // expected-error {{super.init called multiple times in initializer}}
}
init(a : Bool, b : Bool, c : Bool, d : Bool, e : Bool, f : Bool) {
y = 11
if a { super.init() }
x = 42 // expected-error {{use of 'self' in property access 'x' before super.init initializes self}}
} // expected-error {{super.init isn't called on all paths before returning from initializer}}
func someMethod() {}
init(a : Int) {
y = 42
super.init()
}
init(a : Int, b : Bool) {
y = 42
someMethod() // expected-error {{use of 'self' in method call 'someMethod' before super.init initializes self}}
super.init()
}
init(a : Int, b : Int) {
y = 42
baseMethod() // expected-error {{use of 'self' in method call 'baseMethod' before super.init initializes self}}
super.init()
}
init(a : Int, b : Int, c : Int) {
y = computedProperty // expected-error {{use of 'self' in property access 'computedProperty' before super.init initializes self}}
super.init()
}
}
//===----------------------------------------------------------------------===//
// Delegating initializers
//===----------------------------------------------------------------------===//
class DelegatingCtorClass {
var ivar: EmptyStruct
init() { ivar = EmptyStruct() }
convenience init(x: EmptyStruct) {
self.init()
_ = ivar // okay: ivar has been initialized by the delegation above
}
convenience init(x: EmptyStruct, y: EmptyStruct) {
_ = ivar // expected-error {{use of 'self' in property access 'ivar' before self.init initializes self}}
ivar = x // expected-error {{use of 'self' in property access 'ivar' before self.init initializes self}}
self.init()
}
convenience init(x: EmptyStruct, y: EmptyStruct, z: EmptyStruct) {
self.init()
self.init() // expected-error {{self.init called multiple times in initializer}}
}
convenience init(x: (EmptyStruct, EmptyStruct)) {
method() // expected-error {{use of 'self' in method call 'method' before self.init initializes self}}
self.init()
}
convenience init(c : Bool) {
if c {
return
}
self.init()
} // expected-error {{self.init isn't called on all paths before returning from initializer}}
convenience init(bool: Bool) {
doesntReturn()
}
convenience init(double: Double) {
} // expected-error{{self.init isn't called on all paths before returning from initializer}}
func method() {}
}
struct DelegatingCtorStruct {
var ivar : EmptyStruct
init() { ivar = EmptyStruct() }
init(a : Double) {
self.init()
_ = ivar // okay: ivar has been initialized by the delegation above
}
init(a : Int) {
_ = ivar // expected-error {{'self' used before self.init call}}
self.init()
}
init(a : Float) {
self.init()
self.init() // expected-error {{self.init called multiple times in initializer}}
}
init(c : Bool) {
if c {
return
}
self.init()
} // expected-error {{self.init isn't called on all paths before returning from initializer}}
}
enum DelegatingCtorEnum {
case Dinosaur, Train, Truck
init() { self = .Train }
init(a : Double) {
self.init()
_ = self // okay: self has been initialized by the delegation above
self = .Dinosaur
}
init(a : Int) {
_ = self // expected-error {{'self' used before self.init call}}
self.init()
}
init(a : Float) {
self.init()
self.init() // expected-error {{self.init called multiple times in initializer}}
}
init(c : Bool) {
if c {
return
}
self.init()
} // expected-error {{self.init isn't called on all paths before returning from initializer}}
}
//===----------------------------------------------------------------------===//
// Delegating initializers vs extensions
//===----------------------------------------------------------------------===//
protocol TriviallyConstructible {
init()
func go(x: Int)
}
extension TriviallyConstructible {
init(up: Int) {
self.init()
go(up)
}
init(down: Int) {
go(down) // expected-error {{'self' used before self.init call}}
self.init()
}
}
class TrivialClass : TriviallyConstructible {
required init() {}
func go(x: Int) {}
convenience init(y: Int) {
self.init(up: y * y)
}
}
struct TrivialStruct : TriviallyConstructible {
init() {}
func go(x: Int) {}
init(y: Int) {
self.init(up: y * y)
}
}
enum TrivialEnum : TriviallyConstructible {
case NotSoTrivial
init() {
self = NotSoTrivial
}
func go(x: Int) {}
init(y: Int) {
self.init(up: y * y)
}
}
@requires_stored_property_inits
class RequiresInitsDerived : Gizmo {
var a = 1
var b = 2
var c = 3
override init() {
super.init()
}
init(i: Int) {
if i > 0 {
super.init()
}
} // expected-error{{super.init isn't called on all paths before returning from initializer}}
init(d: Double) {
f() // expected-error {{use of 'self' in method call 'f' before super.init initializes self}}
super.init()
}
init(t: ()) {
a = 5 // expected-error {{use of 'self' in property access 'a' before super.init initializes self}}
b = 10 // expected-error {{use of 'self' in property access 'b' before super.init initializes self}}
super.init()
c = 15
}
func f() { }
}
// rdar://16119509 - Dataflow problem where we reject valid code.
class rdar16119509_Buffer {
init(x : Int) { }
}
class rdar16119509_Base {}
class rdar16119509_Derived : rdar16119509_Base {
override init() {
var capacity = 2
while capacity < 2 {
capacity <<= 1
}
buffer = rdar16119509_Buffer(x: capacity)
}
var buffer : rdar16119509_Buffer
}
// <rdar://problem/16797372> Bogus error: self.init called multiple times in initializer
extension Foo {
convenience init() {
for _ in 0..<42 {
}
self.init(a: 4)
}
}
class Foo {
init(a : Int) {}
}
@noreturn
func doesntReturn() {
while true {}
}
func doesReturn() {}
func testNoReturn1(b : Bool) -> Any {
var a : Any
if b {
a = 42
} else {
doesntReturn()
}
return a // Ok, because the noreturn call path isn't viable.
}
func testNoReturn2(b : Bool) -> Any {
var a : Any // expected-note {{variable defined here}}
if b {
a = 42
} else {
doesReturn()
}
// Not ok, since doesReturn() doesn't kill control flow.
return a // expected-error {{variable 'a' used before being initialized}}
}
class PerpetualMotion {
@noreturn func start() {
repeat {} while true
}
@noreturn static func stop() {
repeat {} while true
}
}
func testNoReturn3(b : Bool) -> Any {
let a : Int
switch b {
default:
PerpetualMotion().start()
}
return a
}
func testNoReturn4(b : Bool) -> Any {
let a : Int
switch b {
default:
PerpetualMotion.stop()
}
return a
}
// <rdar://problem/16687555> [DI] New convenience initializers cannot call inherited convenience initializers
class BaseWithConvenienceInits {
init(int: Int) {}
convenience init() {
self.init(int: 3)
}
}
class DerivedUsingConvenienceInits : BaseWithConvenienceInits {
convenience init(string: String) {
self.init()
}
}
// <rdar://problem/16660680> QoI: _preconditionFailure() in init method complains about super.init being called multiple times
class ClassWhoseInitDoesntReturn : BaseWithConvenienceInits {
init() {
_preconditionFailure("leave me alone dude");
}
}
// <rdar://problem/17233681> DI: Incorrectly diagnostic in delegating init with generic enum
enum r17233681Lazy<T> {
case Thunk(() -> T)
case Value(T)
init(value: T) {
self = .Value(value)
}
}
extension r17233681Lazy {
init(otherValue: T) {
self.init(value: otherValue)
}
}
// <rdar://problem/17556858> delegating init that delegates to @_transparent init fails
struct FortyTwo { }
extension Double {
init(v : FortyTwo) {
self.init(0.0)
}
}
// <rdar://problem/17686667> If super.init is implicitly inserted, DI diagnostics have no location info
class r17686667Base {}
class r17686667Test : r17686667Base {
var x: Int
override init() { // expected-error {{property 'self.x' not initialized at implicitly generated super.init call}}
}
}
// <rdar://problem/18199087> DI doesn't catch use of super properties lexically inside super.init call
class r18199087BaseClass {
let data: Int
init(val: Int) {
data = val
}
}
class r18199087SubClassA: r18199087BaseClass {
init() {
super.init(val: self.data) // expected-error {{use of 'self' in property access 'data' before super.init initializes self}}
}
}
// <rdar://problem/18414728> QoI: DI should talk about "implicit use of self" instead of individual properties in some cases
class rdar18414728Base {
var prop:String? { return "boo" }
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let aaaaa:String // expected-note 3 {{'self.aaaaa' not initialized}}
init() {
if let p1 = prop { // expected-error {{use of 'self' in property access 'prop' before all stored properties are initialized}}
aaaaa = p1
}
aaaaa = "foo" // expected-error {{immutable value 'self.aaaaa' may only be initialized once}}
}
init(a : ()) {
method1(42) // expected-error {{use of 'self' in method call 'method1' before all stored properties are initialized}}
aaaaa = "foo"
}
init(b : ()) {
final_method() // expected-error {{use of 'self' in method call 'final_method' before all stored properties are initialized}}
aaaaa = "foo"
}
init(c : ()) {
aaaaa = "foo"
final_method() // ok
}
func method1(a : Int) {}
final func final_method() {}
}
class rdar18414728Derived : rdar18414728Base {
var prop2:String? { return "boo" }
// expected-note @+1 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}}
let aaaaa2:String
override init() {
if let p1 = prop2 { // expected-error {{use of 'self' in property access 'prop2' before super.init initializes self}}
aaaaa2 = p1
}
aaaaa2 = "foo" // expected-error {{immutable value 'self.aaaaa2' may only be initialized once}}
super.init()
}
override init(a : ()) {
method2() // expected-error {{use of 'self' in method call 'method2' before super.init initializes self}}
aaaaa2 = "foo"
super.init()
}
override init(b : ()) {
aaaaa2 = "foo"
method2() // expected-error {{use of 'self' in method call 'method2' before super.init initializes self}}
super.init()
}
override init(c : ()) {
super.init() // expected-error {{property 'self.aaaaa2' not initialized at super.init call}}
aaaaa2 = "foo" // expected-error {{immutable value 'self.aaaaa2' may only be initialized once}}
method2()
}
func method2() {}
}
struct rdar18414728Struct {
var computed:Int? { return 4 }
var i : Int // expected-note 2 {{'self.i' not initialized}}
var j : Int // expected-note {{'self.j' not initialized}}
init() {
j = 42
if let p1 = computed { // expected-error {{'self' used before all stored properties are initialized}}
i = p1
}
i = 1
}
init(a : ()) {
method(42) // expected-error {{'self' used before all stored properties are initialized}}
i = 1
j = 2
}
func method(a : Int) {}
}
extension Int {
mutating func mutate() {}
func inspect() {}
}
// <rdar://problem/19035287> let properties should only be initializable, not reassignable
struct LetProperties {
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let arr : [Int]
// expected-note @+1 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}}
let (u, v) : (Int, Int)
// expected-note @+1 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}}
let w : (Int, Int)
let x = 42
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let y : Int
let z : Int? // expected-note{{'self.z' not initialized}}
// Let properties can be initialized naturally exactly once along any given
// path through an initializer.
init(cond : Bool) {
if cond {
w.0 = 4
(u,v) = (4,2)
y = 71
} else {
y = 13
v = 2
u = v+1
w.0 = 7
}
w.1 = 19
z = nil
arr = []
}
// Multiple initializations are an error.
init(a : Int) {
y = a
y = a // expected-error {{immutable value 'self.y' may only be initialized once}}
u = a
v = a
u = a // expected-error {{immutable value 'self.u' may only be initialized once}}
v = a // expected-error {{immutable value 'self.v' may only be initialized once}}
w.0 = a
w.1 = a
w.0 = a // expected-error {{immutable value 'self.w.0' may only be initialized once}}
w.1 = a // expected-error {{immutable value 'self.w.1' may only be initialized once}}
arr = []
arr = [] // expected-error {{immutable value 'self.arr' may only be initialized once}}
} // expected-error {{return from initializer without initializing all stored properties}}
// inout uses of let properties are an error.
init() {
u = 1; v = 13; w = (1,2); y = 1 ; z = u
var variable = 42
swap(&u, &variable) // expected-error {{immutable value 'self.u' may not be passed inout}}
u.inspect() // ok, non mutating.
u.mutate() // expected-error {{mutating method 'mutate' may not be used on immutable value 'self.u'}}
arr = []
arr += [] // expected-error {{mutating operator '+=' may not be used on immutable value 'self.arr'}}
arr.append(4) // expected-error {{mutating method 'append' may not be used on immutable value 'self.arr'}}
arr[12] = 17 // expected-error {{immutable value 'self.arr' may not be assigned to}}
}
}
// <rdar://problem/19215313> let properties don't work with protocol method dispatch
protocol TestMutabilityProtocol {
func toIntMax()
mutating func changeToIntMax()
}
class C<T : TestMutabilityProtocol> {
let x : T
let y : T
init(a : T) {
x = a; y = a
x.toIntMax()
y.changeToIntMax() // expected-error {{mutating method 'changeToIntMax' may not be used on immutable value 'self.y'}}
}
}
struct MyMutabilityImplementation : TestMutabilityProtocol {
func toIntMax() {
}
mutating func changeToIntMax() {
}
}
// <rdar://problem/16181314> don't require immediate initialization of 'let' values
func testLocalProperties(b : Int) -> Int {
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let x : Int
let y : Int // never assigned is ok expected-warning {{immutable value 'y' was never used}} {{7-8=_}}
x = b
x = b // expected-error {{immutable value 'x' may only be initialized once}}
// This is ok, since it is assigned multiple times on different paths.
let z : Int
if true || false {
z = b
} else {
z = b
}
_ = z
return x
}
// Should be rejected as multiple assignment.
func testAddressOnlyProperty<T>(b : T) -> T {
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let x : T
let y : T
let z : T // never assigned is ok. expected-warning {{immutable value 'z' was never used}} {{7-8=_}}
x = b
y = b
x = b // expected-error {{immutable value 'x' may only be initialized once}}
var tmp = b
swap(&x, &tmp) // expected-error {{immutable value 'x' may not be passed inout}}
return y
}
// <rdar://problem/19254812> DI bug when referencing let member of a class
class r19254812Base {}
class r19254812Derived: r19254812Base{
let pi = 3.14159265359
init(x : ()) {
markUsed(pi) // ok, no diagnostic expected.
}
}
// <rdar://problem/19259730> Using mutating methods in a struct initializer with a let property is rejected
struct StructMutatingMethodTest {
let a, b: String // expected-note 2 {{'self.b' not initialized}}
init(x: String, y: String) {
a = x
b = y
mutate() // ok
}
init(x: String) {
a = x
mutate() // expected-error {{'self' used before all stored properties are initialized}}
b = x
}
init() {
a = ""
nonmutate() // expected-error {{'self' used before all stored properties are initialized}}
b = ""
}
mutating func mutate() {}
func nonmutate() {}
}
// <rdar://problem/19268443> DI should reject this call to transparent function
class TransparentFunction {
let x : Int
let y : Int
init() {
x = 42
++x // expected-error {{mutating operator '++' may not be used on immutable value 'self.x'}}
y = 12
myTransparentFunction(&y) // expected-error {{immutable value 'self.y' may not be passed inout}}
}
}
@_transparent
func myTransparentFunction(inout x : Int) {}
// <rdar://problem/19782264> Immutable, optional class members can't have their subproperties read from during init()
class MyClassWithAnInt {
let channelCount : Int = 42
}
class MyClassTestExample {
let clientFormat : MyClassWithAnInt!
init(){
clientFormat = MyClassWithAnInt()
_ = clientFormat.channelCount
}
}
// <rdar://problem/19746552> QoI: variable "used before being initialized" instead of "returned uninitialized" in address-only enum/struct
struct AddressOnlyStructWithInit<T, U> {
let a : T?
let b : U? // expected-note {{'self.b' not initialized}}
init(a : T) {
self.a = a
} // expected-error {{return from initializer without initializing all stored properties}}
}
enum AddressOnlyEnumWithInit<T> {
case X(T), Y
init() {
} // expected-error {{return from enum initializer method without storing to 'self'}}
}
// <rdar://problem/20135113> QoI: enum failable init that doesn't assign to self produces poor error
enum MyAwesomeEnum {
case One, Two
init?() {
}// expected-error {{return from enum initializer method without storing to 'self'}}
}
// <rdar://problem/20679379> DI crashes on initializers on protocol extensions
extension SomeProtocol {
init?() {
let a = self // expected-error {{variable 'self' used before being initialized}}
self = a
}
init(a : Int) {
} // expected-error {{protocol extension initializer never chained to 'self.init'}}
init(c : Float) {
protoMe() // expected-error {{variable 'self' used before being initialized}}
} // expected-error {{protocol extension initializer never chained to 'self.init'}}
}
// Lvalue check when the archetypes are not the same.
struct LValueCheck<T> {
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let x = 0 // expected-note {{initial value already provided in 'let' declaration}}
}
extension LValueCheck {
init(newY: Int) {
x = 42 // expected-error {{immutable value 'self.x' may only be initialized once}}
}
}
// <rdar://problem/20477982> Accessing let-property with default value in init() can throw spurious error
struct DontLoadFullStruct {
let x: Int = 1
let y: Int
init() {
y = x // ok!
}
}
func testReassignment() {
let c : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
c = 12
c = 32 // expected-error {{immutable value 'c' may only be initialized once}}
_ = c
}
// <rdar://problem/21295093> Swift protocol cannot implement default initializer
protocol ProtocolInitTest {
init()
init(a : Int)
var i: Int { get set }
}
extension ProtocolInitTest {
init() {
} // expected-error {{protocol extension initializer never chained to 'self.init'}}
init(b : Float) {
self.init(a: 42) // ok
}
// <rdar://problem/21684596> QoI: Poor DI diagnostic in protocol extension initializer
init(test1 ii: Int) {
i = ii // expected-error {{'self' used before self.init call}}
self.init()
}
init(test2 ii: Int) {
self = unsafeBitCast(0, Self.self)
i = ii
}
init(test3 ii: Int) {
i = ii // expected-error {{'self' used before chaining to another self.init requirement}}
self = unsafeBitCast(0, Self.self)
}
init(test4 ii: Int) {
i = ii // expected-error {{'self' used before chaining to another self.init requirement}}
} // expected-error {{protocol extension initializer never chained to 'self.init'}}
}
// <rdar://problem/22436880> Function accepting UnsafeMutablePointer is able to change value of immutable value
func bug22436880(x: UnsafeMutablePointer<Int>) {}
func test22436880() {
let x: Int
x = 1
bug22436880(&x) // expected-error {{immutable value 'x' may not be passed inout}}
}
// sr-184
let x: String? // expected-note 2 {{constant defined here}}
print(x?.characters.count) // expected-error {{constant 'x' used before being initialized}}
print(x!) // expected-error {{constant 'x' used before being initialized}}
|
apache-2.0
|
48a09c5b31411b6eb36fcc69804efbef
| 25.377295 | 148 | 0.622911 | 3.543395 | false | false | false | false |
jigneshsheth/Datastructures
|
DataStructure/DataStructure/Shopify/ProductRating.swift
|
1
|
3366
|
//
// ProductRating.swift
// DataStructure
//
// Created by Jigs Sheth on 11/4/21.
// Copyright © 2021 jigneshsheth.com. All rights reserved.
//
import Foundation
// have array with this input
// Class Product - title, popularity, price.
// Equatable, comparable ( == , < ) // two dimention comparison
// description: {return title}
// create Array of products
// array.sort()/ sorted()
// print the array
class ProductRating:Comparable,CustomStringConvertible {
var title:String
var popularity:Int
var price:Int
public init(title:String, popularity:Int,price:Int) {
self.title = title
self.popularity = popularity
self.price = price
}
public static func < (lhs: ProductRating, rhs: ProductRating) -> Bool {
if lhs.popularity == rhs.popularity {
return lhs.price < rhs.price
}
return lhs.popularity > rhs.popularity
}
static func == (lhs: ProductRating, rhs: ProductRating) -> Bool {
return lhs.title == rhs.title && lhs.price == rhs.price && lhs.popularity == rhs.popularity
}
var description:String {
return self.title
}
}
//
//
// var inputArray = ["Selfie Stick,98,29",
//"iPhone Case,90,15",
//"Fire TV Stick,48,49",
//"Wyze Cam,48,25",
//"Water Filter,56,49",
//"Blue Light Blocking Glasses,90,16",
//"Ice Maker,47,119",
//"Video Doorbell,47,199",
//"AA Batteries,64,12",
//"Disinfecting Wipes,37,12",
//"Baseball Cards,73,16",
//"Winter Gloves,32,112",
//"Microphone,44,22",
//"Pet Kennel,5,24",
//"Jenga Classic Game,100,7",
//"Ink Cartridges,88,45",
//"Instant Pot,98,59",
//"Hoze Nozzle,74,26",
//"Gift Card,45,25",
//"Keyboard,82,19"]
//
// var modifiedArray:[Product] = []
//
// for val in inputArray
//{
// // print(val)
// let prod = val.components(separatedBy: ",")
// modifiedArray.append(Product(title:prod[0],popularity:Int(prod[1])!, price:Int(prod[2])!))
//}
//
//var result = modifiedArray.sorted()
//for val in result{
// print(val)
//}
//
/*
Your previous Plain Text content is preserved below:
Simple Product Sorting
Description
Write a program that sorts a list of comma separated products.
Each input row looks like "TITLE,POPULARITY,PRICE". Meaning "Selfie Stick,98,29" says we sold 98 "Selfie Stick"s at 29 dollars each. All numbers are integers. The input will be provided in a hardcoded array so no file I/O is needed.
The list should be sorted by:
By most popular first.
If products are equally popular, sort by cheapest price (lower is better).
You don't need to write your own sorting algorithm. It's recommended to use a built-in sorting library.
Example
If the input is the following array:
"Selfie Stick,98,29",
"iPhone Case,90,15",
"Fire TV Stick,48,49",
"Wyze Cam,48,25",
"Water Filter,56,49",
"Blue Light Blocking Glasses,90,16",
"Ice Maker,47,119",
"Video Doorbell,47,199",
"AA Batteries,64,12",
"Disinfecting Wipes,37,12",
"Baseball Cards,73,16",
"Winter Gloves,32,112",
"Microphone,44,22",
"Pet Kennel,5,24",
"Jenga Classic Game,100,7",
"Ink Cartridges,88,45",
"Instant Pot,98,59",
"Hoze Nozzle,74,26",
"Gift Card,45,25",
"Keyboard,82,19"
The sorted output should be:
Jenga Classic Game
Selfie Stick
Instant Pot
iPhone Case
Blue Light Blocking Glasses
Ink Cartridges
Keyboard
Hoze Nozzle
Baseball Cards
AA Batteries
Water Filter
Wyze Cam
Fire TV Stick
Ice Maker
Video Doorbell
Gift Card
Microphone
Disinfecting Wipes
Winter Gloves
Pet Kennel
*/
|
mit
|
d51b046edad58d08aa9188573aa9385b
| 20.163522 | 232 | 0.702823 | 3.064663 | false | false | false | false |
aronse/Hero
|
Examples/Examples/ListToGrid/ListTableViewController.swift
|
2
|
4268
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Hero
class ListTableViewCell: UITableViewCell {
override func layoutSubviews() {
super.layoutSubviews()
imageView?.frame.origin.x = 0
imageView?.frame.size = CGSize(width: bounds.height, height: bounds.height)
textLabel?.frame.origin.x = bounds.height + 10
detailTextLabel?.frame.origin.x = bounds.height + 10
}
}
class ListTableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ImageLibrary.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "item", for: indexPath)
cell.heroModifiers = [.fade, .translate(x:-100)]
cell.imageView!.heroID = "image_\(indexPath.item)"
cell.imageView!.heroModifiers = [.arc]
cell.imageView!.image = ImageLibrary.thumbnail(index:indexPath.item)
cell.imageView!.isOpaque = true
cell.textLabel!.text = "Item \(indexPath.item)"
cell.detailTextLabel!.text = "Description \(indexPath.item)"
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 52
}
@IBAction func toGrid(_ sender: Any) {
let next = (UIStoryboard(name: "ListToGrid", bundle: nil).instantiateViewController(withIdentifier: "grid") as? GridCollectionViewController)!
next.collectionView?.contentOffset.y = tableView.contentOffset.y + tableView.contentInset.top
hero_replaceViewController(with: next)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = (viewController(forStoryboardName: "ImageViewer") as? ImageViewController)!
vc.selectedIndex = indexPath
vc.view.backgroundColor = UIColor.white
vc.collectionView!.backgroundColor = UIColor.white
navigationController!.pushViewController(vc, animated: true)
}
}
extension ListTableViewController: HeroViewControllerDelegate {
func heroWillStartAnimatingTo(viewController: UIViewController) {
if let _ = viewController as? GridCollectionViewController {
tableView.heroModifiers = [.ignoreSubviewModifiers]
} else if viewController is ImageViewController {
} else {
tableView.heroModifiers = [.cascade]
}
}
func heroWillStartAnimatingFrom(viewController: UIViewController) {
if let _ = viewController as? GridCollectionViewController {
tableView.heroModifiers = [.ignoreSubviewModifiers]
} else {
tableView.heroModifiers = [.cascade]
}
if let vc = viewController as? ImageViewController,
let originalCellIndex = vc.selectedIndex,
let currentCellIndex = vc.collectionView?.indexPathsForVisibleItems[0] {
if tableView.indexPathsForVisibleRows?.contains(currentCellIndex) != true {
// make the cell visible
tableView.scrollToRow(at: currentCellIndex,
at: originalCellIndex < currentCellIndex ? .bottom : .top,
animated: false)
}
}
}
}
|
mit
|
ed9b46abfce1770d80b9be359d0f96f5
| 41.257426 | 146 | 0.731959 | 4.861048 | false | false | false | false |
LYM-mg/MGDYZB
|
MGDYZB简单封装版/MGDYZB/Class/Profile/Model/ProfileModel.swift
|
1
|
877
|
//
// ProfileModel.swift
// MGDYZB
//
// Created by ming on 16/10/30.
// Copyright © 2016年 ming. All rights reserved.
// 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles
// github: https://github.com/LYM-mg
//
import UIKit
class ProfileModel: NSObject {
// MARK:- 定义属性
var title : String = ""
var icon : String = ""
var detailTitle: String = ""
// MARK:- 自定义构造函数
override init() {
}
init(icon: String, title: String, detailTitle: String = "") {
self.icon = icon
self.title = title
if detailTitle != "" {
self.detailTitle = detailTitle
}
}
init(dict: [String: Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) { }
}
|
mit
|
b937ed1349741f9f1fb4827c963cc84a
| 19.634146 | 74 | 0.559102 | 3.662338 | false | false | false | false |
a7ex/SipHash
|
sources/Primitive Types.swift
|
1
|
5294
|
//
// Primitive Types.swift
// SipHash
//
// Created by Károly Lőrentey on 2016-11-14.
// Copyright © 2016 Károly Lőrentey.
//
extension SipHasher {
// MARK: Appending Integers
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Bool) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Bool>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Int) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Int>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: UInt) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<UInt>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Int64) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Int64>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: UInt64) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<UInt64>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Int32) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Int32>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: UInt32) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<UInt32>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Int16) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Int16>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: UInt16) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<UInt16>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Int8) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Int8>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: UInt8) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<UInt8>.size))
}
}
extension SipHasher {
// MARK: Appending Floating Point Types
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Float) {
var data = value.isZero ? 0.0 : value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Float>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Double) {
var data = value.isZero ? 0.0 : value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Double>.size))
}
#if arch(i386) || arch(x86_64)
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Float80) {
var data = value.isZero ? 0.0 : value
// Float80 is 16 bytes wide but the last 6 are uninitialized.
let buffer = UnsafeRawBufferPointer(start: &data, count: 10)
append(buffer)
}
#endif
}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import CoreGraphics
extension SipHasher {
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: CGFloat) {
var data = value.isZero ? 0.0 : value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<CGFloat>.size))
}
}
#endif
extension SipHasher {
// MARK: Appending Optionals
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append<Value: Hashable>(_ value: Value?) {
if let value = value {
self.append(1 as UInt8)
self.append(value)
}
else {
self.append(0 as UInt8)
}
}
}
|
mit
|
e8ab34db6e16df356be20c749cc85d1d
| 31.648148 | 91 | 0.607865 | 4.184335 | false | false | false | false |
devpunk/cartesian
|
cartesian/Firebase/Database/Base/FDb.swift
|
1
|
3128
|
import Foundation
import FirebaseDatabase
class FDb
{
static let user:String = "user"
static let gallery:String = "gallery"
private let reference:DatabaseReference
init()
{
reference = Database.database().reference()
}
//MARK: public
@discardableResult func createChild(
path:String,
json:Any) -> String
{
let childReference:DatabaseReference = reference.child(path).childByAutoId()
let childId:String = childReference.key
childReference.setValue(json)
return childId
}
func updateChild(
path:String,
json:Any)
{
let childReference:DatabaseReference = reference.child(path)
childReference.setValue(json)
}
func removeChild(path:String)
{
let childReference:DatabaseReference = reference.child(path)
childReference.removeValue()
}
func listenOnce(
path:String,
nodeType:FDbProtocol.Type,
completion:@escaping((FDbProtocol?) -> ()))
{
let pathReference:DatabaseReference = reference.child(path)
pathReference.observeSingleEvent(of:DataEventType.value)
{ (snapshot:DataSnapshot) in
var node:FDbProtocol?
guard
let json:Any = snapshot.value
else
{
completion(node)
return
}
if let _:NSNull = json as? NSNull
{
}
else
{
node = nodeType.init(snapshot:json)
}
completion(node)
}
}
func listen(
eventType:DataEventType,
path:String,
nodeType:FDbProtocol.Type,
completion:@escaping((FDbProtocol?) -> ())) -> UInt
{
let pathReference:DatabaseReference = reference.child(path)
let handler:UInt = pathReference.observe(eventType)
{ (snapshot:DataSnapshot) in
var node:FDbProtocol?
guard
let json:Any = snapshot.value
else
{
completion(node)
return
}
if let _:NSNull = json as? NSNull
{
}
else
{
node = nodeType.init(snapshot:json)
}
completion(node)
}
return handler
}
func stopListening(
path:String,
handler:UInt)
{
let pathReference:DatabaseReference = reference.child(path)
pathReference.removeObserver(withHandle:handler)
}
func transaction(
path:String,
transactionBlock:@escaping((MutableData) -> (TransactionResult)))
{
let childReference:DatabaseReference = reference.child(path)
childReference.runTransactionBlock(transactionBlock)
}
}
|
mit
|
e1599f0c223b0890f79c7cad03b944f4
| 23.4375 | 84 | 0.512148 | 5.468531 | false | false | false | false |
mbcharbonneau/MonsterPit
|
Home Control/RoomSensorCell.swift
|
1
|
2497
|
//
// RoomSensorCell.swift
// Home Control
//
// Created by mbcharbonneau on 7/21/15.
// Copyright (c) 2015 Once Living LLC. All rights reserved.
//
import UIKit
class RoomSensorCell: UICollectionViewCell {
@IBOutlet weak private var nameLabel: UILabel?
@IBOutlet weak private var tempLabel: UILabel?
@IBOutlet weak private var humidityLabel: UILabel?
@IBOutlet weak private var lightLabel: UILabel?
@IBOutlet weak private var lastUpdatedLabel: UILabel?
private var lastUpdate: NSDate?
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
backgroundColor = Configuration.Colors.Red
layer.cornerRadius = 6.0
}
func configureWithSensor( sensor: RoomSensor ) {
nameLabel?.text = sensor.name
lastUpdate = sensor.updatedAt
if let degreesC = sensor.temperature {
let tempString = NSString( format:"%.1f", celsiusToFahrenheit( degreesC ) )
tempLabel?.text = "\(tempString) ℉"
} else {
tempLabel?.text = "-.- ℉"
}
if let humidity = sensor.humidity {
let humidityString = NSString( format:"%.0f", humidity * 100.0 )
humidityLabel?.text = "H: \(humidityString)%"
} else {
humidityLabel?.text = "H: -.-%"
}
if let light = sensor.light {
let lightString = NSString( format:"%.0f", luxToPercent( light ) * 100.0 )
lightLabel?.text = "L: \(lightString)%"
} else {
lightLabel?.text = "L: -.-%"
}
updateTimeLabel()
}
func updateTimeLabel() {
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Short
formatter.includesApproximationPhrase = false
formatter.collapsesLargestUnit = false
formatter.maximumUnitCount = 1
formatter.allowedUnits = [.Hour, .Minute, .Second, .Day]
if let date = lastUpdate {
let string = formatter.stringFromDate( date, toDate:NSDate() )!
lastUpdatedLabel?.text = "Data is \(string) old"
} else {
lastUpdatedLabel?.text = ""
}
}
private func celsiusToFahrenheit( celsius: Double ) -> Double {
return celsius * 9 / 5 + 32
}
private func luxToPercent( lux: Double ) -> Double {
return min( lux / 60, 1.0 )
}
}
|
mit
|
1bc300172b14a1fb6220a43be50533e4
| 29.777778 | 87 | 0.587244 | 4.59116 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.