repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
THINKGlobalSchool/SpotConnect | refs/heads/master | ShareAction/TagInputViewController.swift | gpl-2.0 | 1 | //
// TagInputViewController.swift
// SpotConnect
//
// Created by Jeff Tilson on 2015-09-29.
// Copyright © 2015 Jeff Tilson. All rights reserved.
//
import UIKit
protocol TagInputViewControllerDelegate {
func tagInputCompleted(textValue: String)
}
class TagInputViewController: UIViewController, UINavigationControllerDelegate, TLTagsControlDelegate {
// MARK: - Outlets
@IBOutlet weak var tagInput: TLTagsControl!
// MARK: - Class constants/vars
var delegate: TagInputViewControllerDelegate?
var initialTagString: String?
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController?.delegate = self
// Set initial tags if available
if let tagString = self.initialTagString {
if (!tagString.isEmpty) {
let tagArray = tagString.componentsSeparatedByString(", ")
self.tagInput.tags = NSMutableArray(array: tagArray)
self.tagInput.reloadTagSubviews()
}
}
self.tagInput.tapDelegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UINavigationControllerDelegate
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
if (!viewController.isKindOfClass(object_getClass(self))) {
// Convert tags array to a string
if let array = self.tagInput.tags as NSArray as? [String] {
let imploded = array.joinWithSeparator(", ")
self.delegate?.tagInputCompleted(imploded)
}
}
}
// MARK: - TLTagsControlDelegate
func tagsControl(tagsControl: TLTagsControl!, tappedAtIndex index: Int) {
// Handle tap events for tags
}
}
| b35f85d82a8617487a111e621c207231 | 31.03125 | 150 | 0.651707 | false | false | false | false |
n6xej/SwiftWhopperButton | refs/heads/master | SwiftWhopperButton/ViewController.swift | mit | 1 | //
// ViewController.swift
// SwiftBurgerButton
//
// Created by Christopher Worley on 7/10/16.
// Copyright © 2016 stashdump.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var burger0: SwiftWhopperButton!
@IBOutlet weak var burger1: SwiftWhopperButton!
@IBOutlet weak var burger2: SwiftWhopperButton!
@IBOutlet weak var burger3: SwiftWhopperButton!
@IBAction func doMenu(sender: SwiftWhopperButton) {
// do not set isMenu on click, taken care of internally
if sender.isMenu {
print("Was a Menu")
print("Now an X")
}
else {
print("Was an X")
print("Now a Menu")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//
// to create a window programatically do this:
//
// let width = UIScreen.mainScreen().bounds.size.width / 2
// let quarter = width/2
//
// let rect = CGRectMake(quarter , 50, 50, 50)
//
// let vc = SwiftWopperButton.init(frame: rect)
// vc.lineColor = UIColor.yellowColor()
// vc.circleColor = UIColor.purpleColor()
// vc.convert = PathConvertType.HorizontalAndAlt.rawValue
// vc.isMenu = false
NSTimer.schedule(delay: 0.75) { timer in
self.doDemo()
}
}
var demoCnt = 3
func doDemo() {
// see if expired
if self.demoCnt == 0 {
return
}
self.demoCnt -= 1
NSTimer.schedule(delay: 0.0) { timer in
self.burger0.isMenu = !self.burger0.isMenu
NSTimer.schedule(delay: 1.0) { timer in
self.burger0.isMenu = !self.burger0.isMenu
}
}
NSTimer.schedule(delay: 2.25){ timer in
self.burger1.isMenu = !self.burger1.isMenu
NSTimer.schedule(delay: 1.0) { timer in
self.burger1.isMenu = !self.burger1.isMenu
}
}
NSTimer.schedule(delay: 4.5) { timer in
self.burger2.isMenu = !self.burger2.isMenu
NSTimer.schedule(delay: 1.0) { timer in
self.burger2.isMenu = !self.burger2.isMenu
}
}
NSTimer.schedule(delay: 6.75){ timer in
self.burger3.isMenu = !self.burger3.isMenu
NSTimer.schedule(delay: 1.0) { timer in
self.burger3.isMenu = !self.burger3.isMenu
}
NSTimer.schedule(delay: 2.25){ timer in
self.doDemo()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension NSTimer {
class func schedule(delay delay: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = delay + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
}
class func schedule(repeatInterval interval: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = interval + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
}
}
| 0d4f1a0dcd57e814bc0e0997f7fcf4be | 24.638655 | 101 | 0.702393 | false | false | false | false |
BPForEveryone/BloodPressureForEveryone | refs/heads/master | BPApp/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// BPApp
//
// Created by Chris Blackstone on 4/24/17.
// Copyright © 2017 BlackstoneBuilds. 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: "BPApp")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 952fb57a27b00e739b39675adc49b2c3 | 48.397849 | 285 | 0.686112 | false | false | false | false |
ntwf/TheTaleClient | refs/heads/1.2/stable | TheTale/Models/API/TaleAPIConfirmRegistration.swift | mit | 1 | //
// TaleAPIConfirmRegistration.swift
// TheTaleClient
//
// Created by Mikhail Vospennikov on 04/09/2017.
// Copyright © 2017 Mikhail Vospennikov. All rights reserved.
//
import Foundation
extension TaleAPI {
func confirmRegistration(nick: String, email: String, password: String, completionHandler: @escaping (APIResult<JSON>) -> Void) {
var components: [String: String] = [:]
components["nick"] = nick
components["email"] = email
components["password"] = password
guard let request = networkManager.createRequest(fromAPI: .updateProfile, httpParameters: components) else {
return
}
fetch(request: request, parse: { (json) -> JSON? in
if let dictionary = json["data"] as? JSON {
return dictionary
} else {
return nil
}
}, completionHandler: completionHandler)
}
}
| 0322a5cde62177f13507d8b1fd6d4ae5 | 25.575758 | 131 | 0.652223 | false | false | false | false |
xeecos/motionmaker | refs/heads/master | GIFMaker/CameraSettingCell.swift | mit | 1 | //
// CameraSettingCell.swift
// GIFMaker
//
// Created by indream on 15/9/20.
// Copyright © 2015年 indream. All rights reserved.
//
import UIKit
class CameraSettingCell: UITableViewCell {
@IBOutlet weak var focusLabel: UILabel!
@IBOutlet weak var focusSlider: UISlider!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var speedSlider: UISlider!
@IBOutlet weak var isoLabel: UILabel!
@IBOutlet weak var isoSlider: UISlider!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var timeSlider: UISlider!
@IBOutlet weak var intervalLabel: UILabel!
@IBOutlet weak var intervalSlider: UISlider!
var cid:Int16 = 0
var sid:Int16 = 0
weak var tableView:UITableView!
func setCameraIndex(_ sid:Int16, cid:Int16){
self.cid = cid
if(self.cid<0){
self.cid = 0
}
self.sid = sid
if(self.sid<0){
self.sid = 0
}
updateConfig()
}
override func awakeFromNib() {
super.awakeFromNib()
updateConfig()
}
func updateConfig(){
let cam:CameraModel? = DataManager.sharedManager().camera(sid,cid: cid)!
if(cam==nil){
DataManager.sharedManager().createCamera(sid,cid: cid)
}
let focus:Float = Float(cam!.focus)
let speed:Float = Float(cam!.speed)
if((focusSlider) != nil){
focusSlider.value = focus
focusLabel.text = String(format: "%.2f", focusSlider.value/8000.0)
speedSlider.value = 0
speedLabel.text = String(format: "1/%.0f", speed)
isoSlider.value = Float(cam!.iso)
isoLabel.text = String(format: "%.0f", isoSlider.value)
}
if((timeSlider) != nil){
timeSlider.value = 0
timeLabel.text = String(format: "%d %@", cam!.time,NSLocalizedString("secs", comment: ""))
intervalSlider.value = 0
intervalLabel.text = String(format: "%.1f %@ / %d %@", cam!.interval,NSLocalizedString("secs", comment: ""),Int(Float(cam!.time)/Float(cam!.interval)),NSLocalizedString("frames", comment: ""))
}
}
func assignTableView(_ tableView:UITableView){
self.tableView = tableView
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func focusChanged(_ sender: AnyObject) {
focusLabel.text = String(format: "%.2f", focusSlider.value/8000.0)
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
cam.focus = focusSlider.value
tableView.alpha = 0.1
VideoManager.sharedManager().configureDevice(sid,cid:cid)
}
@IBAction func speedChanged(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
var scale:Float = 1
if(cam.speed<500){
scale = 3
}
if(cam.speed<300){
scale = 5
}
if(cam.speed<100){
scale = 10
}
if(cam.speed<50){
scale = 20
}
let speed = speedSlider.value/scale
if(Float(cam.speed)+speed<2){
speedLabel.text = String(format: "1/%d", 2)
}else{
speedLabel.text = String(format: "1/%.0f", Float(cam.speed)+speed)
}
tableView.alpha = 0.1
VideoManager.sharedManager().configureDevice(sid,cid:cid)
}
@IBAction func speedTouchEnd(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
var scale:Float = 1
if(cam.speed<500){
scale = 3
}
if(cam.speed<300){
scale = 5
}
if(cam.speed<100){
scale = 10
}
if(cam.speed<50){
scale = 20
}
cam.speed += Int16(speedSlider.value/scale)
if(cam.speed<2){
cam.speed = 2
}else if(cam.speed>8000){
cam.speed = 8000
}
speedLabel.text = String(format: "1/%d", cam.speed)
speedSlider.value = 0
tableView.alpha = 1.0
VideoManager.sharedManager().configureDevice(sid,cid:cid)
}
@IBAction func focusEnd(_ sender: AnyObject) {
tableView.alpha = 1.0
}
@IBAction func isoEnd(_ sender: AnyObject) {
tableView.alpha = 1.0
}
@IBAction func isoChanged(_ sender: AnyObject) {
isoLabel.text = String(format: "%.0f", isoSlider.value)
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
cam.iso = Int16(isoSlider.value)
tableView.alpha = 0.1
VideoManager.sharedManager().configureDevice(sid,cid:cid)
}
@IBAction func timeChanged(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
let time = timeSlider.value/2
timeLabel.text = String(format: "%.1f %@", Float(cam.time)+time,NSLocalizedString("secs", comment: ""))
intervalLabel.text = String(format: "%.1f %@ / %d %@", cam.interval,NSLocalizedString("secs", comment: ""),Int((Float(cam.time)+time)/cam.interval),NSLocalizedString("frames", comment: ""))
}
@IBAction func timeTouchEnd(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
cam.time += Int32(floorf(timeSlider.value/2))
if(cam.time<0){
cam.time = 0
}
timeSlider.value = 0
timeLabel.text = String(format: "%.1f %@", Float(cam.time),NSLocalizedString("secs", comment: ""))
intervalLabel.text = String(format: "%.1f %@ / %d %@", cam.interval,NSLocalizedString("secs", comment: ""),Int((Float(cam.time)/cam.interval)),NSLocalizedString("frames", comment: ""))
}
@IBAction func intervalChanged(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
let interval = intervalSlider.value/4
if((cam.interval+interval)>0.1){
intervalLabel.text = String(format: "%.1f %@ / %d %@", (cam.interval+interval),NSLocalizedString("secs", comment: ""),Int(Float(cam.time)/Float(cam.interval+interval)),NSLocalizedString("frames", comment: ""))
}else{
intervalLabel.text = String(format: "%.1f %@ / %d %@",0.1,NSLocalizedString("secs", comment: ""),Int(Float(cam.time)/0.1),NSLocalizedString("frames", comment: ""))
}
}
@IBAction func intervalTouchEnd(_ sender: AnyObject) {
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid: cid)!
cam.interval += intervalSlider.value/4
if(cam.interval<0.1){
cam.interval = 0.1
}
intervalSlider.value = 0
timeLabel.text = String(format: "%.1f %@", Float(cam.time),NSLocalizedString("secs", comment: ""))
intervalLabel.text = String(format: "%.1f %@ / %d %@", cam.interval,NSLocalizedString("secs", comment: ""),Int((Float(cam.time)/cam.interval)),NSLocalizedString("frames", comment: ""))
}
}
| 11469efe96293b530c3b204e2fe04c69 | 37.772973 | 221 | 0.595009 | false | false | false | false |
lemonmojo/StartupDisk | refs/heads/master | StartupDisk/AppDelegate.swift | bsd-3-clause | 1 | //
// AppDelegate.swift
// StartupDisk
//
// Created by Felix Deimel on 04.06.14.
// Copyright (c) 2014 Lemon Mojo. All rights reserved.
//
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
@IBOutlet var statusMenu: NSMenu!
var statusItem: NSStatusItem
override init()
{
let lengthSquare: CGFloat = -2 // TODO: Workaround for Xcode 6 Beta, should actually be: NSSquareStatusItemLength (see http://stackoverflow.com/questions/24024723/swift-using-nsstatusbar-statusitemwithlength-and-nsvariablestatusitemlength)
self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(lengthSquare)
}
override func awakeFromNib()
{
self.statusItem.menu = self.statusMenu
self.statusItem.highlightMode = true
}
func applicationDidFinishLaunching(aNotification: NSNotification?)
{
updateStatusItem()
}
func updateStatusItem()
{
self.statusItem.title = nil
var icon = NSImage(named: "Icon")
icon?.size = NSSize(width: 16, height: 16)
icon?.setTemplate(true)
self.statusItem.image = icon
}
func menuNeedsUpdate(menu: NSMenu!)
{
if (menu != self.statusMenu) {
return
}
menu.removeAllItems()
var vols = LMVolume.mountedLocalVolumesWithBootableOSXInstallations()
var startupDiskDevicePath = LMVolume.startupDiskDevicePath()
for vol in vols {
var item = NSMenuItem(title: vol.name, action: "statusMenuItemVolume_Action:", keyEquivalent: "")
item.representedObject = vol
var icon : NSImage? = NSWorkspace.sharedWorkspace().iconForFile(vol.path)
if (icon != nil) {
icon?.size = NSSize(width: 16, height: 16)
}
item.image = icon
if (vol.devicePath == startupDiskDevicePath) {
item.state = NSOnState
}
menu.addItem(item)
}
menu.addItem(NSMenuItem.separatorItem())
menu.addItem(NSMenuItem(title: "System Preferences", action: "statusMenuItemSystemPreferences_Action:", keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "About StartupDisk", action: "statusMenuItemAbout_Action:", keyEquivalent: ""))
menu.addItem(NSMenuItem.separatorItem())
menu.addItem(NSMenuItem(title: "Quit StartupDisk", action: "statusMenuItemQuit_Action:", keyEquivalent: ""))
}
func statusMenuItemVolume_Action(sender: NSMenuItem)
{
var vol = sender.representedObject as LMVolume
if (vol.setStartupDisk()) {
var alert = NSAlert()
alert.addButtonWithTitle("Restart")
alert.addButtonWithTitle("Cancel")
alert.messageText = "Do you want to restart the Computer?"
alert.informativeText = NSString(format: "Your Computer will start up using %@.", vol.name)
alert.alertStyle = NSAlertStyle.InformationalAlertStyle
var response = alert.runModal()
if (response == NSAlertFirstButtonReturn) {
LMUtils.restartMac()
}
}
}
func statusMenuItemSystemPreferences_Action(sender: NSMenuItem)
{
NSWorkspace.sharedWorkspace().openURL(NSURL(fileURLWithPath: "/System/Library/PreferencePanes/StartupDisk.prefPane")!)
}
func statusMenuItemAbout_Action(sender: NSMenuItem)
{
NSApplication.sharedApplication().orderFrontStandardAboutPanel(self)
NSApplication.sharedApplication().activateIgnoringOtherApps(true)
}
func statusMenuItemQuit_Action(sender: NSMenuItem)
{
NSApplication.sharedApplication().terminate(self)
}
} | 1a0cf402f3e9651178201051ffcecad7 | 32.151261 | 247 | 0.618661 | false | false | false | false |
Ivacker/swift | refs/heads/master | test/SILGen/generic_closures.swift | apache-2.0 | 9 | // RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s
import Swift
var zero: Int
// CHECK-LABEL: sil hidden @_TF16generic_closures28generic_nondependent_context{{.*}}
func generic_nondependent_context<T>(x: T, y: Int) -> Int {
var y = y
func foo() -> Int { return y }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures28generic_nondependent_context{{.*}} : $@convention(thin) (@owned @box Int, @inout Int) -> Int
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures15generic_capture{{.*}}
func generic_capture<T>(x: T) -> Any.Type {
func foo() -> Any.Type { return T.self }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures15generic_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick protocol<>.Type
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures20generic_capture_cast{{.*}}
func generic_capture_cast<T>(x: T, y: Any) -> Bool {
func foo(a: Any) -> Bool { return a is T }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures20generic_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in protocol<>) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo(y)
}
protocol Concept {
var sensical: Bool { get }
}
// CHECK-LABEL: sil hidden @_TF16generic_closures29generic_nocapture_existential{{.*}}
func generic_nocapture_existential<T>(x: T, y: Concept) -> Bool {
func foo(a: Concept) -> Bool { return a.sensical }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures29generic_nocapture_existential{{.*}} : $@convention(thin) (@in Concept) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo(y)
}
// CHECK-LABEL: sil hidden @_TF16generic_closures25generic_dependent_context{{.*}}
func generic_dependent_context<T>(x: T, y: Int) -> T {
func foo() -> T { return x }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures25generic_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@out τ_0_0, @owned @box τ_0_0, @inout τ_0_0) -> ()
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>
return foo()
}
enum Optionable<T> {
case Some(T)
case None
}
class NestedGeneric<U> {
class func generic_nondependent_context<T>(x: T, y: Int, z: U) -> Int {
func foo() -> Int { return y }
return foo()
}
class func generic_dependent_inner_context<T>(x: T, y: Int, z: U) -> T {
func foo() -> T { return x }
return foo()
}
class func generic_dependent_outer_context<T>(x: T, y: Int, z: U) -> U {
func foo() -> U { return z }
return foo()
}
class func generic_dependent_both_contexts<T>(x: T, y: Int, z: U) -> (T, U) {
func foo() -> (T, U) { return (x, z) }
return foo()
}
// CHECK-LABEL: sil hidden @_TFC16generic_closures13NestedGeneric20nested_reabstraction{{.*}}
// CHECK: [[REABSTRACT:%.*]] = function_ref @_TTRG__rXFo__dT__XFo_iT__iT__
// CHECK: partial_apply [[REABSTRACT]]<U, T>
func nested_reabstraction<T>(x: T) -> Optionable<() -> ()> {
return .Some({})
}
}
// CHECK-LABEL: sil hidden @_TF16generic_closures24generic_curried_function{{.*}} : $@convention(thin) <T, U> (@in U, @in T) -> () {
// CHECK-LABEL: sil shared @_TF16generic_closures24generic_curried_function{{.*}}
func generic_curried_function<T, U>(x: T)(y: U) { }
var f: (Int) -> () = generic_curried_function(zero)
// <rdar://problem/15417773>
// Ensure that nested closures capture the generic parameters of their nested
// context.
// CHECK: sil hidden @_TF16generic_closures25nested_closure_in_generic{{.*}} : $@convention(thin) <T> (@out T, @in T) -> ()
// CHECK: function_ref [[OUTER_CLOSURE:@_TFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_]]
// CHECK: sil shared [[OUTER_CLOSURE]] : $@convention(thin) <T> (@out T, @inout T) -> ()
// CHECK: function_ref [[INNER_CLOSURE:@_TFFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_U_FT_Q_]]
// CHECK: sil shared [[INNER_CLOSURE]] : $@convention(thin) <T> (@out T, @inout T) -> () {
func nested_closure_in_generic<T>(x:T) -> T {
return { { x }() }()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures16local_properties
func local_properties<T>(inout t: T) {
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $T
var prop: T {
get {
return t
}
set {
t = newValue
}
}
// CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@out τ_0_0, @owned @box τ_0_0, @inout τ_0_0) -> ()
// CHECK: apply [[GETTER_REF]]
t = prop
// CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned @box τ_0_0, @inout τ_0_0) -> ()
// CHECK: apply [[SETTER_REF]]
prop = t
var prop2: T {
get {
return t
}
set {
// doesn't capture anything
}
}
// CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@out τ_0_0, @owned @box τ_0_0, @inout τ_0_0) -> ()
// CHECK: apply [[GETTER2_REF]]
t = prop2
// CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> ()
// CHECK: apply [[SETTER2_REF]]
prop2 = t
}
protocol Fooable {
static func foo() -> Bool
}
// <rdar://problem/16399018>
func shmassert(@autoclosure f: () -> Bool) {}
// CHECK-LABEL: sil hidden @_TF16generic_closures21capture_generic_param
func capture_generic_param<A: Fooable>(x: A) {
shmassert(A.foo())
}
| 4edea43f295a47a41c0365968b0a58d3 | 36.248366 | 195 | 0.614669 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Interop/C/struct/struct-decl-context-module-interface.swift | apache-2.0 | 10 | // RUN: %target-swift-ide-test -print-module -module-to-print=StructDeclContext -I %S/Inputs -source-filename=x | %FileCheck %s
// This test checks that structs that are imported from a C module are imported
// into the top-level scope in Swift, even when they are lexically declared
// nested in other C structs.
// CHECK: struct StructRegular {
// CHECK-NEXT: init()
// CHECK-NEXT: init(complete_immediately: StructNestedComplete1, completed_later: UnsafeMutablePointer<StructNestedCompletedLater1>!)
// CHECK-NEXT: var complete_immediately: StructNestedComplete1
// CHECK-NEXT: var completed_later: UnsafeMutablePointer<StructNestedCompletedLater1>!
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedComplete1 {
// CHECK-NEXT: init()
// CHECK-NEXT: init(complete_immediately_nested: StructNestedNestedComplete1, completed_later_nested: UnsafeMutablePointer<StructNestedNestedCompletedLater1>!)
// CHECK-NEXT: var complete_immediately_nested: StructNestedNestedComplete1
// CHECK-NEXT: var completed_later_nested: UnsafeMutablePointer<StructNestedNestedCompletedLater1>!
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedNestedComplete1 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedNestedCompletedLater1 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedCompletedLater1 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct StructTypedefTag2 {
// CHECK-NEXT: init()
// CHECK-NEXT: init(complete_immediately: StructNestedComplete2, completed_later: UnsafeMutablePointer<StructNestedCompletedLater2>!)
// CHECK-NEXT: var complete_immediately: StructNestedComplete2
// CHECK-NEXT: var completed_later: UnsafeMutablePointer<StructNestedCompletedLater2>!
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedComplete2 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias StructTypedefName2 = StructTypedefTag2
// CHECK-NEXT: struct StructNestedCompletedLater2 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct StructTypedefName3 {
// CHECK-NEXT: init()
// CHECK-NEXT: init(complete_immediately: StructNestedComplete3, completed_later: UnsafeMutablePointer<StructNestedCompletedLater3>!)
// CHECK-NEXT: var complete_immediately: StructNestedComplete3
// CHECK-NEXT: var completed_later: UnsafeMutablePointer<StructNestedCompletedLater3>!
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedComplete3 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedCompletedLater3 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct StructTypedefTag4 {
// CHECK-NEXT: init()
// CHECK-NEXT: init(complete_immediately: StructNestedComplete4, completed_later: UnsafeMutablePointer<StructNestedCompletedLater4>!)
// CHECK-NEXT: var complete_immediately: StructNestedComplete4
// CHECK-NEXT: var completed_later: UnsafeMutablePointer<StructNestedCompletedLater4>!
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedComplete4 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias StructTypedefName4 = UnsafeMutablePointer<StructTypedefTag4>
// CHECK-NEXT: struct StructNestedCompletedLater4 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedComplete5 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias StructTypedefName5 = OpaquePointer
// CHECK-NEXT: struct StructNestedCompletedLater5 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct StructTypedefName6 {
// CHECK-NEXT: init()
// CHECK-NEXT: init(complete_immediately: StructNestedComplete6, completed_later: UnsafeMutablePointer<StructNestedCompletedLater6>!)
// CHECK-NEXT: var complete_immediately: StructNestedComplete6
// CHECK-NEXT: var completed_later: UnsafeMutablePointer<StructNestedCompletedLater6>!
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedComplete6 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias StructTypedefName6Ptr = UnsafeMutablePointer<StructTypedefName6>
// CHECK-NEXT: struct StructNestedCompletedLater6 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct StructTypedefName7 {
// CHECK-NEXT: init()
// CHECK-NEXT: init(complete_immediately: StructNestedComplete7, completed_later: UnsafeMutablePointer<StructNestedCompletedLater7>!)
// CHECK-NEXT: var complete_immediately: StructNestedComplete7
// CHECK-NEXT: var completed_later: UnsafeMutablePointer<StructNestedCompletedLater7>!
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedComplete7 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias StructTypedefName7Ptr = UnsafeMutablePointer<StructTypedefName7>
// CHECK-NEXT: struct StructNestedCompletedLater7 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct StructTypedefName8 {
// CHECK-NEXT: init()
// CHECK-NEXT: init(complete_immediately: StructNestedComplete8, completed_later: UnsafeMutablePointer<StructNestedCompletedLater8>!)
// CHECK-NEXT: var complete_immediately: StructNestedComplete8
// CHECK-NEXT: var completed_later: UnsafeMutablePointer<StructNestedCompletedLater8>!
// CHECK-NEXT: }
// CHECK-NEXT: struct StructNestedComplete8 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias StructTypedefName8Ptr = UnsafeMutablePointer<StructTypedefName8>
// CHECK-NEXT: typealias StructTypedefName8PtrPtr = UnsafeMutablePointer<UnsafeMutablePointer<StructTypedefName8>?>
// CHECK-NEXT: struct StructNestedCompletedLater8 {
// CHECK-NEXT: init()
// CHECK-NEXT: }
| 50395d7fe0982376aa90c74a18567795 | 48.035714 | 161 | 0.762564 | false | false | false | false |
Jnosh/swift | refs/heads/master | test/SourceKit/SyntaxMapData/syntaxmap-edit-block-comment.swift | apache-2.0 | 1 | // RUN: %sourcekitd-test -req=open -print-raw-response %S/Inputs/syntaxmap-edit-block-comment.swift == -req=edit -print-raw-response %S/Inputs/syntaxmap-edit-block-comment.swift -pos=3:2 -replace=" " -length=1 == -req=edit -print-raw-response %S/Inputs/syntaxmap-edit-block-comment.swift -pos=3:2 -replace="/" -length=1 | %sed_clean > %t.response
// RUN: %FileCheck -input-file=%t.response %s
// CHECK: {{^}}{
// CHECK-NEXT: key.offset: 0,
// CHECK-NEXT: key.length: 29,
// CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse,
// CHECK-NEXT: key.syntaxmap: [
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword,
// CHECK-NEXT: key.offset: 0,
// CHECK-NEXT: key.length: 3
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier,
// CHECK-NEXT: key.offset: 4,
// CHECK-NEXT: key.length: 1
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.comment,
// CHECK-NEXT: key.offset: 8,
// CHECK-NEXT: key.length: 6
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword,
// CHECK-NEXT: key.offset: 15,
// CHECK-NEXT: key.length: 4
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier,
// CHECK-NEXT: key.offset: 20,
// CHECK-NEXT: key.length: 3
// CHECK-NEXT: }
// CHECK-NEXT: ],
// CHECK: {{^}}{
// CHECK-NEXT: key.offset: 8,
// CHECK-NEXT: key.length: 21,
// CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse,
// CHECK-NEXT: key.syntaxmap: [
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.comment,
// CHECK-NEXT: key.offset: 8,
// CHECK-NEXT: key.length: 21
// CHECK-NEXT: }
// CHECK-NEXT: ],
// CHECK: {{^}}{
// CHECK-NEXT: key.offset: 8,
// CHECK-NEXT: key.length: 21,
// CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse,
// CHECK-NEXT: key.syntaxmap: [
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.comment,
// CHECK-NEXT: key.offset: 8,
// CHECK-NEXT: key.length: 6
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword,
// CHECK-NEXT: key.offset: 15,
// CHECK-NEXT: key.length: 4
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier,
// CHECK-NEXT: key.offset: 20,
// CHECK-NEXT: key.length: 3
// CHECK-NEXT: }
// CHECK-NEXT: ],
| 6471db43862682922acc3d8ab90ff2fa | 36.275362 | 347 | 0.633359 | false | false | true | false |
FirebaseExtended/mlkit-material-ios | refs/heads/master | ShowcaseApp/ShowcaseAppSwift/Controllers/VideoCamViewController.swift | apache-2.0 | 1 | /**
* Copyright 2019 Google ML Kit team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import AVFoundation
import Firebase
import GTMSessionFetcher
import MaterialComponents
/**
* The camera mode view controller that displays a rear facing live feed.
*/
private let videoDataOutputQueueLabel = "com.google.firebaseml.visiondetector.VideoDataOutputQueue"
private let videoSessionQueueLabel = "com.google.firebaseml.visiondetector.VideoSessionQueue"
//* Duration for presenting the bottom sheet.
private let kBottomSheetAnimationDurationInSec: CGFloat = 0.25
//* Duration for confirming stage.
private let kConfirmingDurationInSec: CGFloat = 1.5
// Constants for alpha values.
private let kOpaqueAlpha: CGFloat = 1.0
private let kTransparentAlpha: CGFloat = 0.0
//* Radius of the searching indicator.
private let kSearchingIndicatorRadius: CGFloat = 24.0
//* Target height of the thumbnail when it sits on top of the bottom sheet.
private let kThumbnailbottomSheetTargetHeight: CGFloat = 200.0
//* Padding around the thumbnail when it sits on top of the bottom sheet.
private let kThumbnailPaddingAround: CGFloat = 24.0
//* The thumbnail will fade out when it reaches this threshhold from screen edge.
private let kThumbnailFadeOutEdgeThreshhold: CGFloat = 200.0
//* Number of faked product search results.
private let kFakeProductSearchResultCount = 10
// Chip message related values.
private let kChipBackgroundAlpha: CGFloat = 0.6
private let kChipCornerRadius: CGFloat = 8.0
private let kChipFadeInDuration: CGFloat = 0.075
private let kChipScaleDuration: CGFloat = 0.15
private let kChipScaleFromRatio: CGFloat = 0.8
private let kChipScaleToRatio: CGFloat = 1.25
private let kChipBottomPadding: CGFloat = 36.0
//* The message shown in detecting stage.
private let kDetectingStageMessage = "Point your camera at an object"
//* The Message shown in confirming stage.
private let kConfirmingStageMessage = "Keep camera still for a moment"
//* The message shown in searching stage.
private let kSearchingMessage = "Searching"
// Strings for fake search results.
private let kFakeProductNameFormat = "Fake product name: %li"
private let kFakeProductTypeName = "Fashion"
private let kFakeProductPriceText = "$10"
private let kFakeProductItemNumberText = "12345678"
private let kKeyFileName = "key"
private let kKeyFileType = "plist"
class VideoCamViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate, MDCBottomSheetControllerDelegate {
// Views to be added as subviews of current view.
private var previewView: UIView!
private var overlayView: DetectionOverlayView!
private var detectingReticle: CameraReticle!
private var confirmingSpinner: ConfirmationSpinner!
private var searchingIndicator: MDCActivityIndicator!
// Video capture related properties.
private var session = AVCaptureSession()
private var videoDataOutput: AVCaptureVideoDataOutput!
private var videoDataOutputQueue = DispatchQueue(label: videoDataOutputQueueLabel)
private var sessionQueue = DispatchQueue(label: videoSessionQueueLabel)
private var previewLayer: AVCaptureVideoPreviewLayer!
// Vision server to generate `VisionObjectDetector`.
private let vision = Vision.vision()
// Current status in object detection.
var status = ODTStatus.notStarted {
didSet {
switch status {
case .notStarted:
hideMessage()
confirmingSpinner.isHidden = true
detectingReticle.isHidden = true
showSearchingIndicator(false)
case .detecting:
showMessage(kDetectingStageMessage)
detectingReticle.isHidden = false
confirmingSpinner.isHidden = true
showSearchingIndicator(false)
case .confirming:
showMessage(kConfirmingStageMessage)
detectingReticle.isHidden = true
confirmingSpinner.isHidden = false
showSearchingIndicator(false)
case .searching:
showMessage(kSearchingMessage)
confirmingSpinner.isHidden = true
detectingReticle.isHidden = true
showSearchingIndicator(true)
case .searched:
hideMessage()
confirmingSpinner.isHidden = true
detectingReticle.isHidden = true
showSearchingIndicator(false)
}
}
}
// View to show message during different stages.
private var messageView: MDCChipView!
// Properties to record latest detected results.
private var lastDetectedObject: VisionObject!
private var lastDetectedSampleBuffer: SampleBuffer!
// Width to height ratio of the thumbnail.
private var thumbnailWidthHeightRatio: CGFloat = 0.0
// Target height of the bottom sheet.
private var bottomSheetTargetHeight: CGFloat = 0.0
// Array of timers scheduled before confirmation.
private var timers = [AnyHashable]()
// Used to fetch product search results.
private var fetcherService = GTMSessionFetcherService()
deinit {
clearLastDetectedObject()
fetcherService.stopAllFetchers()
}
// MARK: - UIViewController
override func loadView() {
super.loadView()
view.clipsToBounds = true
setUpPreviewView()
setUpOverlayView()
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
setCameraSelection()
// Set up video processing pipeline.
setUpVideoProcessing()
// Set up camera preview.
#if !TARGET_IPHONE_SIMULATOR
setUpCameraPreviewLayer()
#endif
setUpDetectingReticle()
setUpConfirmingSpinner()
setUpSearchingIndicator()
setUpMessageView()
startToDetect()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer.frame = view.frame
previewLayer.position = CGPoint(x: previewLayer.frame.midX, y: previewLayer.frame.midY)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
weak var weakSelf = self
#if !TARGET_IPHONE_SIMULATOR
sessionQueue.async(execute: {
weakSelf?.session.stopRunning()
})
#endif
}
// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
func captureOutput(_ captureOutput: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection) {
let buffer = SampleBuffer(sampleBuffer: sampleBuffer)
detectObject(in: buffer)
}
// MARK: - MDCBottomSheetControllerDelegate
func bottomSheetControllerDidDismissBottomSheet(_ controller: MDCBottomSheetController) {
bottomSheetTargetHeight = 0
startToDetect()
}
func bottomSheetControllerDidChangeYOffset(_ controller: MDCBottomSheetController, yOffset: CGFloat) {
let imageStartY = yOffset - kThumbnailbottomSheetTargetHeight - kThumbnailPaddingAround
let rect = CGRect(x: kThumbnailPaddingAround,
y: imageStartY,
width: kThumbnailbottomSheetTargetHeight * thumbnailWidthHeightRatio,
height: kThumbnailbottomSheetTargetHeight) // Height
guard let currentWindow = UIApplication.shared.keyWindow else { return }
let safeInsets = UIUtilities.safeAreaInsets()
let screenHeight = currentWindow.bounds.size.height
let topFadeOutOffsetY = safeInsets.top + kThumbnailFadeOutEdgeThreshhold
let bottomFadeOutOffsetY = screenHeight - safeInsets.bottom - kThumbnailFadeOutEdgeThreshhold
let imageAlpha = ratioOfCurrentValue(yOffset,
from: (yOffset > bottomSheetTargetHeight) ?
bottomFadeOutOffsetY : topFadeOutOffsetY,
to: bottomSheetTargetHeight)
overlayView.showImage(in: rect, alpha: imageAlpha)
}
// MARK: - Private
//* Prepares camera session for video processing.
func setUpVideoProcessing() {
weak var weakSelf = self
sessionQueue.async(execute: {
guard let strongSelf = weakSelf else {
return
}
strongSelf.videoDataOutput = AVCaptureVideoDataOutput()
let rgbOutputSettings = [
kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32BGRA)
]
strongSelf.videoDataOutput.videoSettings = rgbOutputSettings
if let videoDataOutput = strongSelf.videoDataOutput {
if !strongSelf.session.canAddOutput(videoDataOutput) {
if strongSelf.videoDataOutput != nil {
strongSelf.session.removeOutput(videoDataOutput)
strongSelf.videoDataOutput = nil
}
print("Failed to set up video output")
return
}
}
strongSelf.videoDataOutput.alwaysDiscardsLateVideoFrames = true
strongSelf.videoDataOutput.setSampleBufferDelegate(strongSelf, queue: strongSelf.videoDataOutputQueue)
if let videoDataOutput = strongSelf.videoDataOutput {
strongSelf.session.addOutput(videoDataOutput)
}
})
}
//* Prepares preview view for camera session.
func setUpPreviewView() {
previewView = UIView(frame: view.frame)
previewView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(previewView)
}
//* Initiates and prepares camera preview layer for later video capture.
func setUpCameraPreviewLayer() {
previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.backgroundColor = UIColor.black.cgColor
previewLayer.videoGravity = .resizeAspectFill
let rootLayer = previewView.layer
rootLayer.masksToBounds = true
previewLayer.frame = rootLayer.bounds
rootLayer.addSublayer(previewLayer)
}
//* Prepares camera for later video capture.
func setCameraSelection() {
weak var weakSelf = self
sessionQueue.async(execute: {
guard let strongSelf = weakSelf else {
return
}
strongSelf.session.beginConfiguration()
strongSelf.session.sessionPreset = .hd1280x720
let oldInputs = strongSelf.session.inputs
for oldInput in oldInputs {
strongSelf.session.removeInput(oldInput)
}
let input = strongSelf.pickCamera(.back)
if input == nil {
// Failed, restore old inputs
for oldInput in oldInputs {
strongSelf.session.addInput(oldInput)
}
} else {
// Succeeded, set input and update connection states
if let input = input {
strongSelf.session.addInput(input)
}
}
strongSelf.session.commitConfiguration()
})
}
//* Determines camera for later video capture. Here only rear camera is picked.
func pickCamera(_ desiredPosition: AVCaptureDevice.Position) -> AVCaptureDeviceInput? {
var hadError = false
for device in AVCaptureDevice.devices(for: .video) where device.position == desiredPosition {
do {
let input = try AVCaptureDeviceInput(device: device)
if session.canAddInput(input) {
return input
}
} catch {
hadError = true
print("Could not initialize for AVMediaTypeVideo for device \(device)")
}
}
if !hadError {
print("No camera found for requested orientation")
}
return nil
}
//* Initiates and prepares overlay view for later video capture.
func setUpOverlayView() {
overlayView = DetectionOverlayView(frame: view.frame)
overlayView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(overlayView)
}
//* Clears up the overlay view. Caller must make sure this runs on the main thread.
func cleanUpOverlayView() {
assert(Thread.current.isEqual(Thread.main), "cleanUpOverlayView is not running on the main thread")
overlayView.hideSubviews()
overlayView.frame = view.frame
}
//* Initiates and prepares detecting reticle for later video capture.
func setUpDetectingReticle() {
detectingReticle = CameraReticle()
detectingReticle.translatesAutoresizingMaskIntoConstraints = false
let size = detectingReticle.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude))
detectingReticle.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
if let detectingReticle = detectingReticle {
view.addSubview(detectingReticle)
}
NSLayoutConstraint.activate([
detectingReticle.centerXAnchor.constraint(equalTo: view.centerXAnchor),
detectingReticle.centerYAnchor.constraint(equalTo: view.centerYAnchor)
].compactMap { $0 })
}
//* Initiates and prepares confirming spinner for later video capture.
func setUpConfirmingSpinner() {
confirmingSpinner = ConfirmationSpinner(duration: CFTimeInterval(kConfirmingDurationInSec))
confirmingSpinner.translatesAutoresizingMaskIntoConstraints = false
let size = confirmingSpinner.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude))
confirmingSpinner.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
if let confirmingSpinner = confirmingSpinner {
view.addSubview(confirmingSpinner)
}
NSLayoutConstraint.activate([
confirmingSpinner.centerXAnchor.constraint(equalTo: view.centerXAnchor),
confirmingSpinner.centerYAnchor.constraint(equalTo: view.centerYAnchor)
].compactMap { $0 })
}
//* Initiates and prepares searching indicator for later video capture.
func setUpSearchingIndicator() {
searchingIndicator = MDCActivityIndicator()
searchingIndicator.radius = kSearchingIndicatorRadius
searchingIndicator.cycleColors = [UIColor.white]
let size = confirmingSpinner.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude))
let centerX = view.frame.midX
let centerY = view.frame.midY
searchingIndicator.frame = CGRect(x: centerX, y: centerY, width: size.width, height: size.height)
view.addSubview(searchingIndicator)
NSLayoutConstraint.activate([
searchingIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
searchingIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor)
].compactMap { $0 })
}
//* Initiates and prepares message view for later video capture.
func setUpMessageView() {
messageView = MDCChipView()
messageView.backgroundColor = UIColor.black.withAlphaComponent(kChipBackgroundAlpha)
messageView.isUserInteractionEnabled = false
messageView.clipsToBounds = true
messageView.titleLabel.textColor = UIColor.white
messageView.layer.cornerRadius = kChipCornerRadius
view.addSubview(messageView)
messageView.alpha = kTransparentAlpha
}
/**
* Clears last detected object. Caller must make sure that this method runs on the main thread.
*/
func clearLastDetectedObject() {
assert(Thread.current.isEqual(Thread.main), "clearLastDetectedObject is not running on the main thread")
lastDetectedObject = nil
lastDetectedSampleBuffer = nil
for timer in timers {
guard let timer = timer as? Timer else {
continue
}
timer.invalidate()
}
}
// MARK: - Object detection and tracking.
/**
* Called to detect objects in the given sample buffer.
*
* @param sampleBuffer The `SampleBuffer` for object detection.
*/
func detectObject(in sampleBuffer: SampleBuffer) {
let orientation = UIUtilities.imageOrientation(from: UIDevice.current.orientation, withCaptureDevicePosition: .back)
let image = VisionImage(buffer: sampleBuffer.data)
let metadata = VisionImageMetadata()
metadata.orientation = orientation
// metadata.orientation = FIRVisionDetectorImageOrientationRightTop;
image.metadata = metadata
let options = VisionObjectDetectorOptions()
options.shouldEnableMultipleObjects = false
options.shouldEnableClassification = false
options.detectorMode = .stream
let objectDetector = vision.objectDetector(options: options)
do {
let objects = try objectDetector.results(in: image)
weak var weakSelf = self
DispatchQueue.main.async(execute: {
weakSelf?.onDetectedObjects(objects, in: sampleBuffer)
})
} catch {
}
}
/**
* Call when objects are detected in the given sample buffer. Caller must make sure that this method
* runs on the main thread.
*
* @param objects The list of objects that is detected in the given sample buffer.
* @param sampleBuffer The given sampleBuffer.
*/
func onDetectedObjects(_ objects: [VisionObject]?, in sampleBuffer: SampleBuffer) {
assert(Thread.current.isEqual(Thread.main), "onDetectedObjects:inSampleBuffer is not running on the main thread")
guard let objects = objects, objects.count == 1, let object = objects.first, object.trackingID != nil else {
startToDetect()
return
}
let sampleBufferSize = self.sampleBufferSize(sampleBuffer.data)
let isFocusInsideObjectFrame = object.frame.contains(CGPoint(x: sampleBufferSize.width / 2,
y: sampleBufferSize.height / 2))
if !isFocusInsideObjectFrame {
startToDetect()
return
}
switch status {
case .detecting:
cleanUpOverlayView()
let convertedRect = convertedRectOfObjectFrame(object.frame, inSampleBufferFrameSize: sampleBufferSize)
overlayView.showBox(in: convertedRect)
start(toConfirmObject: object, sampleBuffer: sampleBuffer)
case .confirming:
let convertedRect = convertedRectOfObjectFrame(object.frame, inSampleBufferFrameSize: sampleBufferSize)
overlayView.showBox(in: convertedRect)
lastDetectedObject = object
lastDetectedSampleBuffer = sampleBuffer
case .searching, .searched, .notStarted:
break
}
}
// MARK: - Status Handling
/**
* Called when it needs to start the detection. Caller must make sure that this method runs on the
* main thread.
*/
func startToDetect() {
assert(Thread.current.isEqual(Thread.main), "startToDetect is not running on the main thread")
status = .detecting
cleanUpOverlayView()
clearLastDetectedObject()
weak var weakSelf = self
sessionQueue.async(execute: {
guard let strongSelf = weakSelf else {
return
}
#if !TARGET_IPHONE_SIMULATOR
if !strongSelf.session.isRunning {
strongSelf.session.startRunning()
}
#endif
})
}
/**
* Starts a product search with last detected object. Caller must make sure that this method runs on
* the main thread.
*/
func startToSearch() {
assert(Thread.current.isEqual(Thread.main),
"startToSearchWithImage:originalWidth:originalHeight is not running on the main thread")
status = .searching
let originalSampleBufferSize = sampleBufferSize(lastDetectedSampleBuffer.data)
let croppedImage = self.croppedImage(from: lastDetectedSampleBuffer.data, in: lastDetectedObject.frame)
let convertedRect = convertedRectOfObjectFrame(lastDetectedObject.frame,
inSampleBufferFrameSize: originalSampleBufferSize)
thumbnailWidthHeightRatio = lastDetectedObject.frame.size.height / lastDetectedObject.frame.size.width
overlayView.image.image = croppedImage
cleanUpOverlayView()
overlayView.showImage(in: convertedRect, alpha: 1)
guard let productSearchRequest = productSearchRequest(from: croppedImage) else {
processSearchResponse(nil, for: croppedImage, originalWidth: size_t(originalSampleBufferSize.width),
originalHeight: size_t(originalSampleBufferSize.height), useFakeResponse: true)
clearLastDetectedObject()
return
}
let fetcher = fetcherService.fetcher(with: productSearchRequest)
weak var weakSelf = self
DispatchQueue.global(qos: .default).async(execute: {
fetcher.beginFetch { data, error in
guard let strongSelf = weakSelf else {
return
}
if error != nil {
if let error = error {
print("error in fetching: \(error)")
}
strongSelf.clearLastDetectedObject()
return
}
DispatchQueue.main.async(execute: {
guard let strongSelf = weakSelf else {
return
}
strongSelf.processSearchResponse(data, for: croppedImage,
originalWidth: size_t(originalSampleBufferSize.width),
originalHeight: size_t(originalSampleBufferSize.height),
useFakeResponse: false)
strongSelf.clearLastDetectedObject()
})
}
})
}
/**
* Processes search response from server. Caller must make sure that this method runs on the main
* thread.
*
* @param response The raw response from server on product search request.
* @param image The image of the detected object that is to be searched.
* @param width The width of the original sample buffer.
* @param height The height of the original sample buffer.
* @param useFakeResponse Whether to use fake response or send a product search request to the
* server.
*/
func processSearchResponse(_ response: Data?, for image: UIImage, originalWidth width: size_t,
originalHeight height: size_t, useFakeResponse: Bool) {
assert(Thread.current.isEqual(Thread.main), """
processSearchRespose:forImage:originalWidth:originalHeight is not running on the main \
thread
""")
status = .searched
var products: [Product]
if useFakeResponse {
products = fakeProductSearchResults()
} else {
products = Product.products(fromResponse: response) ?? []
}
let productsViewController = ProductListViewController(products: products)
let bottomSheet = MDCBottomSheetController(contentViewController: productsViewController)
bottomSheet.trackingScrollView = productsViewController.collectionView
bottomSheet.scrimColor = UIColor.clear
bottomSheet.dismissOnBackgroundTap = true
bottomSheet.delegate = self
let contentHeight = productsViewController.collectionViewLayout.collectionViewContentSize.height
let screenHeight = view.frame.size.height
let safeInsets = UIUtilities.safeAreaInsets()
let toOffsetY = contentHeight > screenHeight ?
screenHeight / 2.0 - safeInsets.bottom : screenHeight - contentHeight - safeInsets.top - safeInsets.bottom
bottomSheetTargetHeight = toOffsetY
let toFrame = CGRect(x: kThumbnailPaddingAround,
y: toOffsetY - kThumbnailbottomSheetTargetHeight - kThumbnailPaddingAround,
width: thumbnailWidthHeightRatio * kThumbnailbottomSheetTargetHeight,
height: kThumbnailbottomSheetTargetHeight) // Height
UIView.animate(withDuration: TimeInterval(kBottomSheetAnimationDurationInSec), animations: {
self.overlayView.showImage(in: toFrame, alpha: 1)
})
present(bottomSheet, animated: true)
}
/**
* Calculates the ratio of current value based on `from` and `to` value.
*
* @param currentValue The current value.
* @param fromValue The start point of the range.
* @param toValue The end point of the range.
* @return Position of current value in the whole range. It falls into [0,1].
*/
func ratioOfCurrentValue(_ currentValue: CGFloat, from fromValue: CGFloat, to toValue: CGFloat) -> CGFloat {
var ratio = (currentValue - fromValue) / (toValue - fromValue)
ratio = min(ratio, 1)
return max(ratio, 0)
}
/**
* Called to confirm on the given object.Caller must make sure that this method runs on the main
* thread.
*
* @param object The object to confirm. It will be regarded as the same object if its objectID stays
* the same during this stage.
* @param sampleBuffer The original sample buffer that this object was detected in.
*/
func start(toConfirmObject object: VisionObject, sampleBuffer: SampleBuffer) {
assert(Thread.current.isEqual(Thread.main), "startToConfirmObject:sampleBuffer is not running on the main thread")
clearLastDetectedObject()
let timer = Timer.scheduledTimer(timeInterval: TimeInterval(kConfirmingDurationInSec),
target: self, selector: #selector(onTimerFired),
userInfo: nil, repeats: false)
timers.append(timer)
status = .confirming
lastDetectedObject = object
lastDetectedSampleBuffer = sampleBuffer
}
//* Called when timer is up and the detected object is confirmed.
@objc func onTimerFired() {
weak var weakSelf = self
DispatchQueue.main.async(execute: {
guard let strongSelf = weakSelf else {
return
}
switch strongSelf.status {
case .confirming:
#if !TARGET_IPHONE_SIMULATOR
strongSelf.sessionQueue.async(execute: {
weakSelf?.session.stopRunning()
})
#endif
strongSelf.startToSearch()
case .detecting, .notStarted, .searched, .searching:
break
}
})
}
/**
* Overrides setter for `status` property. It also shows corresponding indicator/message with the
* status change. Caller must make sure that this method runs on the main thread.
*
* @param status The new status.
*/
// MARK: - Util methods
/**
* Returns size of given `CMSampleBufferRef`.
*
* @param sampleBuffer The `CMSampleBufferRef` to get size from.
* @return The size of the given `CMSampleBufferRef`. It describes its width and height.
*/
func sampleBufferSize(_ sampleBuffer: CMSampleBuffer) -> CGSize {
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return CGSize.zero
}
let imageWidth = CVPixelBufferGetWidth(imageBuffer)
let imageHeight = CVPixelBufferGetHeight(imageBuffer)
return CGSize(width: CGFloat(imageWidth), height: CGFloat(imageHeight))
}
/**
* Converts given frame of a detected object to a `CGRect` in coordinate system of current view.
*
* @param frame The frame of detected object.
* @param size The frame size of the sample buffer.
* @return Converted rect.
*/
func convertedRectOfObjectFrame(_ frame: CGRect, inSampleBufferFrameSize size: CGSize) -> CGRect {
let normalizedRect = CGRect(x: frame.origin.x / size.width,
y: frame.origin.y / size.height,
width: frame.size.width / size.width,
height: frame.size.height / size.height) // Height
let convertedRect = previewLayer.layerRectConverted(fromMetadataOutputRect: normalizedRect)
return convertedRect.standardized
}
/**
* Crops given `CMSampleBufferRef` with given rect.
*
* @param sampleBuffer The sample buffer to be cropped.
* @param rect The rect of the area to be cropped.
* @return Returns cropped image to the given rect.
*/
func croppedImage(from sampleBuffer: CMSampleBuffer, in rect: CGRect) -> UIImage {
let croppedSampleBuffer = ImageUtilities.croppedSampleBuffer(sampleBuffer, with: rect)
let croppedImage = ImageUtilities.image(from: croppedSampleBuffer)
return UIUtilities.orientedUpImage(from: croppedImage!)
}
/**
* Shows/Hides searching indicator.
*
* @param isVisible Whether to show/hide searching indicator. YES to show, NO to hide.
*/
func showSearchingIndicator(_ isVisible: Bool) {
if isVisible {
searchingIndicator.isHidden = false
searchingIndicator.startAnimating()
} else {
searchingIndicator.isHidden = true
searchingIndicator.stopAnimating()
}
}
func showMessage(_ message: String) {
if messageView.titleLabel.text == message {
return
}
messageView.titleLabel.text = message
messageView.sizeToFit()
let size = messageView.sizeThatFits(view.frame.size)
let startX = (view.frame.size.width - size.width) / 2.0
let startY = view.frame.size.height - kChipBottomPadding - size.height
messageView.frame = CGRect(x: startX, y: startY, width: size.width, height: size.height)
if messageView.alpha != kTransparentAlpha {
return
}
messageView.alpha = kTransparentAlpha
UIView.animate(withDuration: TimeInterval(kChipFadeInDuration), animations: {
self.messageView?.alpha = kOpaqueAlpha
})
let messageCenter = CGPoint(x: messageView.frame.midX, y: messageView.frame.midY)
messageView.transform = messageView.transform.scaledBy(x: kChipScaleFromRatio, y: kChipScaleFromRatio)
messageView.sizeToFit()
UIView.animate(withDuration: TimeInterval(kChipScaleDuration), animations: {
self.messageView.center = messageCenter
self.messageView.transform = self.messageView.transform.scaledBy(x: kChipScaleToRatio, y: kChipScaleToRatio)
})
}
func hideMessage() {
UIView.animate(withDuration: TimeInterval(kChipFadeInDuration), animations: {
self.messageView.alpha = kTransparentAlpha
})
}
/**
* Generates fake product search results for demo when there are no real backend server hooked up.
*/
func fakeProductSearchResults() -> [Product] {
var fakeProductSearchResults: [Product] = []
for index in 0..<kFakeProductSearchResultCount {
let product = Product.init(productName: String(format: kFakeProductNameFormat, index + 1),
score: nil, itemNo: kFakeProductPriceText, imageURL: nil,
priceFullText: kFakeProductPriceText, productTypeName: kFakeProductTypeName)
fakeProductSearchResults.append(product)
}
return fakeProductSearchResults
}
}
/**
* A wrapper class that holds a reference to `CMSampleBufferRef` to let ARC take care of its
* lifecyle for this `CMSampleBufferRef`.
*/
class SampleBuffer: NSObject {
// The encapsulated `CMSampleBufferRed` data.
var data: CMSampleBuffer!
// MARK: - Public
init(sampleBuffer: CMSampleBuffer) {
super.init()
self.data = sampleBuffer
}
}
| b7a70949047401bdee4f67a3c19fbc35 | 37.16791 | 128 | 0.706944 | false | false | false | false |
rajeshmud/CLChart | refs/heads/master | CLApp/CLCharts/CLCharts/Charts/CLChartPoint.swift | mit | 1 | //
// ChartPoint.swift
// CLCharts
//
// Created by Rajesh Mudaliyar on 11/09/15.
// Copyright © 2015 Rajesh Mudaliyar. All rights reserved.
//
import UIKit
public class ChartPoint: Equatable {
public let x: CLAxisValue
public let y: CLAxisValue
required public init(x: CLAxisValue, y: CLAxisValue) {
self.x = x
self.y = y
}
public var text: String {
return "\(self.x.text), \(self.y.text)"
}
}
public func ==(lhs: ChartPoint, rhs: ChartPoint) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public class CLPointBubble: ChartPoint {
public let diameterScalar: Double
public let bgColor: UIColor
public let borderColor: UIColor
public init(x: CLAxisValue, y: CLAxisValue, diameterScalar: Double, bgColor: UIColor, borderColor: UIColor = UIColor.blackColor()) {
self.diameterScalar = diameterScalar
self.bgColor = bgColor
self.borderColor = borderColor
super.init(x: x, y: y)
}
public init(point:ChartPoint, diameterScalar: Double = 0.0, bgColor: UIColor = UIColor.blackColor(), borderColor: UIColor = UIColor.blackColor()) {
self.diameterScalar = diameterScalar
self.bgColor = bgColor
self.borderColor = borderColor
super.init(x: point.x, y: point.y)
}
required public init(x: CLAxisValue, y: CLAxisValue) {
fatalError("init(x:y:) has not been implemented")
}
}
public class CLPointCandleStick: ChartPoint {
public let date: NSDate
public let open: Double
public let close: Double
public let low: Double
public let high: Double
public init(date: NSDate, formatter: NSDateFormatter, high: Double, low: Double, open: Double, close: Double, labelHidden: Bool = false) {
let x = CLAxisValueDate(date: date, formatter: formatter)
self.date = date
x.hidden = labelHidden
let highY = CLAxisValueDouble(high)
self.high = high
self.low = low
self.open = open
self.close = close
super.init(x: x, y: highY)
}
required public init(x: CLAxisValue, y: CLAxisValue) {
fatalError("init(x:y:) has not been implemented")
}
}
| 713b017a100cb10ba1a34f461afbf664 | 27.2875 | 151 | 0.629253 | false | false | false | false |
jkpang/PPBadgeView | refs/heads/master | PPBadgeView/swift/UIBarButtonItem+PPBadgeView.swift | mit | 1 | //
// UIBarButtonItem+PPBadgeView.swift
// PPBadgeViewSwift
//
// Created by AndyPang on 2017/6/19.
// Copyright © 2017年 AndyPang. All rights reserved.
//
/*
*********************************************************************************
*
* Weibo : jkpang-庞 ( http://weibo.com/jkpang )
* Email : [email protected]
* QQ 群 : 323408051
* GitHub: https://github.com/jkpang
*
*********************************************************************************
*/
import UIKit
public extension PP where Base: UIBarButtonItem {
var badgeView: PPBadgeControl {
return _bottomView.pp.badgeView
}
/// 添加带文本内容的Badge, 默认右上角, 红色, 18pts
///
/// Add Badge with text content, the default upper right corner, red backgroundColor, 18pts
///
/// - Parameter text: 文本字符串
func addBadge(text: String) {
_bottomView.pp.addBadge(text: text)
}
/// 添加带数字的Badge, 默认右上角,红色,18pts
///
/// Add the Badge with numbers, the default upper right corner, red backgroundColor, 18pts
///
/// - Parameter number: 整形数字
func addBadge(number: Int) {
_bottomView.pp.addBadge(number: number)
}
/// 添加带颜色的小圆点, 默认右上角, 红色, 8pts
///
/// Add small dots with color, the default upper right corner, red backgroundColor, 8pts
///
/// - Parameter color: 颜色
func addDot(color: UIColor?) {
_bottomView.pp.addDot(color: color)
}
/// 设置Badge的偏移量, Badge中心点默认为其父视图的右上角
///
/// Set Badge offset, Badge center point defaults to the top right corner of its parent view
///
/// - Parameters:
/// - x: X轴偏移量 (x<0: 左移, x>0: 右移) axis offset (x <0: left, x> 0: right)
/// - y: Y轴偏移量 (y<0: 上移, y>0: 下移) axis offset (Y <0: up, y> 0: down)
func moveBadge(x: CGFloat, y: CGFloat) {
_bottomView.pp.moveBadge(x: x, y: y)
}
/// 设置Badge伸缩的方向
///
/// Setting the direction of Badge expansion
///
/// PPBadgeViewFlexModeHead, 左伸缩 Head Flex : <==●
/// PPBadgeViewFlexModeTail, 右伸缩 Tail Flex : ●==>
/// PPBadgeViewFlexModeMiddle 左右伸缩 Middle Flex : <=●=>
/// - Parameter flexMode : Default is PPBadgeViewFlexModeTail
func setBadge(flexMode: PPBadgeViewFlexMode = .tail) {
_bottomView.pp.setBadge(flexMode: flexMode)
}
/// 设置Badge的高度,因为Badge宽度是动态可变的,通过改变Badge高度,其宽度也按比例变化,方便布局
///
/// (注意: 此方法需要将Badge添加到控件上后再调用!!!)
///
/// Set the height of Badge, because the Badge width is dynamically and variable.By changing the Badge height in proportion to facilitate the layout.
///
/// (Note: this method needs to add Badge to the controls and then use it !!!)
///
/// - Parameter points: 高度大小
func setBadge(height: CGFloat) {
_bottomView.pp.setBadge(height: height)
}
/// 显示Badge
func showBadge() {
_bottomView.pp.showBadge()
}
/// 隐藏Badge
func hiddenBadge() {
_bottomView.pp.hiddenBadge()
}
// MARK: - 数字增加/减少, 注意:以下方法只适用于Badge内容为纯数字的情况
// MARK: - Digital increase /decrease, note: the following method applies only to cases where the Badge content is purely numeric
/// badge数字加1
func increase() {
_bottomView.pp.increase()
}
/// badge数字加number
func increaseBy(number: Int) {
_bottomView.pp.increaseBy(number: number)
}
/// badge数字加1
func decrease() {
_bottomView.pp.decrease()
}
/// badge数字减number
func decreaseBy(number: Int) {
_bottomView.pp.decreaseBy(number: number)
}
/// 通过Xcode视图调试工具找到UIBarButtonItem的Badge所在父视图为:UIImageView
private var _bottomView: UIView {
let navigationButton = (self.base.value(forKey: "_view") as? UIView) ?? UIView()
let systemVersion = (UIDevice.current.systemVersion as NSString).doubleValue
let controlName = (systemVersion < 11.0 ? "UIImageView" : "UIButton" )
for subView in navigationButton.subviews {
if subView.isKind(of: NSClassFromString(controlName)!) {
subView.layer.masksToBounds = false
return subView
}
}
return navigationButton
}
}
| afc45bd766b91d64f7c65a04a92a59a5 | 29.955882 | 154 | 0.587648 | false | false | false | false |
mohamede1945/KVOController-Swift | refs/heads/master | KVOController-Swift-Example/Clock.swift | mit | 1 | //
// Clock.swift
// KVOController
//
// Created by Mohamed Afifi on 7/23/15.
// Copyright (c) 2015 mohamede1945. All rights reserved.
//
import UIKit
/**
Represents the clock class.
@author mohamede1945
@version 1.0
*/
class Clock : NSObject {
/// Represents the timer property.
fileprivate var timer: Timer?
/// Represents the date property.
dynamic fileprivate (set) var date = Date()
/**
Initialize new instance.
- returns: The new created instance.
*/
override init() {
super.init()
timer = Timer(interval: 1, repeated: true) { [weak self] () -> Void in
self?.date = Date()
}
}
}
/**
Represents the timer class.
@author mohamede1945
@version 1.0
*/
class Timer {
/// Represents the is cancelled property.
fileprivate var isCancelled = false
/// Represents the repeated property.
fileprivate let repeated: Bool
/// Represents the timer property.
fileprivate let timer: DispatchSourceTimer
/**
Initialize new instance with interval, repeated, queue and handler.
- parameter interval: The interval parameter.
- parameter repeated: The repeated parameter.
- parameter queue: The queue parameter.
- parameter handler: The handler parameter.
- returns: The new created instance.
*/
init(interval: TimeInterval, repeated: Bool, queue: DispatchQueue = DispatchQueue.main, handler: @escaping ()->()) {
self.repeated = repeated
timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: queue)
timer.scheduleRepeating(deadline: DispatchTime.now(), interval: .seconds(1), leeway: .milliseconds(0))
timer.setEventHandler { [weak self] in
if self?.isCancelled == false {
handler()
}
}
timer.resume();
}
/**
Cancel.
*/
func cancel() {
isCancelled = true
timer.cancel()
}
/**
Deallocate the instance.
*/
deinit {
cancel()
}
}
| 495fcdbb29d8ffce607c838e38ecda21 | 20.863158 | 120 | 0.620607 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/Interpreter/SDK/libc.swift | apache-2.0 | 5 | /* magic */
// Do not edit the line above.
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-run-simple-swift %s %t | FileCheck %s
// REQUIRES: executable_test
// XFAIL: linux
import Darwin
let sourcePath = Process.arguments[1]
let tempPath = Process.arguments[2] + "/libc.txt"
// CHECK: Hello world
fputs("Hello world", stdout)
// CHECK: 4294967295
print("\(UINT32_MAX)")
// CHECK: the magic word is ///* magic *///
let sourceFile = open(sourcePath, O_RDONLY)
assert(sourceFile >= 0)
var bytes = UnsafeMutablePointer<CChar>(allocatingCapacity: 12)
var readed = read(sourceFile, bytes, 11)
close(sourceFile)
assert(readed == 11)
bytes[11] = CChar(0)
print("the magic word is //\(String(cString: bytes))//")
// CHECK: O_CREAT|O_EXCL returned errno *17*
let errFile =
open(sourcePath, O_RDONLY | O_CREAT | O_EXCL)
if errFile != -1 {
print("O_CREAT|O_EXCL failed to return an error")
} else {
print("O_CREAT|O_EXCL returned errno *\(errno)*")
}
// CHECK: created mode *33216*
let tempFile =
open(tempPath, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR)
let written = write(tempFile, bytes, 11)
assert(written == 11)
close(tempFile)
var statbuf = stat()
let err = stat(tempPath, &statbuf)
if err != 0 {
print("stat returned \(err), errno \(errno)")
} else {
print("created mode *\(statbuf.st_mode)*")
assert(statbuf.st_mode == S_IFREG | S_IRUSR | S_IWUSR | S_IXUSR)
}
| b927143e8fb726f89bf4578d45924d9b | 25.074074 | 72 | 0.661932 | false | false | false | false |
JamesWatling/actor-platform | refs/heads/master | actor-apps/app-ios/Actor/Controllers Support/AANavigationController.swift | mit | 13 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import UIKit
class AANavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.translucent = true
navigationBar.hideBottomHairline()
view.backgroundColor = MainAppTheme.list.backyardColor
}
// MARK: -
// MARK: Methods
// override func viewWillAppear(animated: Bool) {
// super.viewWillAppear(animated)
// navigationBar.hideBottomHairline()
// view.backgroundColor = MainAppTheme.list.backyardColor
// }
func makeBarTransparent() {
navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationBar.shadowImage = UIImage()
navigationBar.translucent = true
}
}
extension UINavigationBar {
func hideBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(self)
navigationBarImageView!.hidden = true
}
func showBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(self)
navigationBarImageView!.hidden = false
}
private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
if view.isKindOfClass(UIImageView) && view.bounds.height <= 1.0 {
return (view as! UIImageView)
}
let subviews = (view.subviews as! [UIView])
for subview: UIView in subviews {
if let imageView: UIImageView = hairlineImageViewInNavigationBar(subview) {
return imageView
}
}
return nil
}
} | f39046bf780fd03a41b96aa55f8a81f2 | 28.051724 | 88 | 0.644299 | false | false | false | false |
gezhixin/MoreThanDrawerMenumDemo | refs/heads/master | special/Mian/WebClient/WebClient.swift | mit | 1 | //
// WebClient.swift
// special
//
// Created by 葛枝鑫 on 15/6/27.
// Copyright (c) 2015年 葛枝鑫. All rights reserved.
//
import UIKit
import Alamofire
class WebClient: NSObject {
class func Login(name string:String, passwd:String, sucess:(user: UserModel)->Void, failue:(code: Int, msg: String?)->Void) {
let param = ["u": string, "p": passwd]
STNet.postWithAction(Actions.loginAction, parameters: param, sucess: { (data) -> Void in
let user: UserModel = UserModel()
user.name = data!["Name"].stringValue
user.id = data!["Id"].int64Value
user.ImgUrl = data!["ImgUrl"].string
user.email = data!["Email"].string
user.sex = data!["Sex"].int
sucess(user: user)
}) { (code, msg) -> Void in
failue(code: code, msg: msg)
}
}
}
| 6dd6de6cd0a9d0e20903863fb5947f4c | 28.1 | 129 | 0.563574 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | refs/heads/master | Pod/Classes/Sources.Api/BarometerBridge.swift | apache-2.0 | 1 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Interface for Barometer management purposes
Auto-generated implementation of IBarometer specification.
*/
public class BarometerBridge : BaseSensorBridge, IBarometer, APIBridge {
/**
API Delegate.
*/
private var delegate : IBarometer? = nil
/**
Constructor with delegate.
@param delegate The delegate implementing platform specific functions.
*/
public init(delegate : IBarometer?) {
self.delegate = delegate
}
/**
Get the delegate implementation.
@return IBarometer delegate that manages platform specific functions..
*/
public final func getDelegate() -> IBarometer? {
return self.delegate
}
/**
Set the delegate implementation.
@param delegate The delegate implementing platform specific functions.
*/
public final func setDelegate(delegate : IBarometer) {
self.delegate = delegate;
}
/**
Invokes the given method specified in the API request object.
@param request APIRequest object containing method name and parameters.
@return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions.
*/
public override func invoke(request : APIRequest) -> APIResponse? {
let response : APIResponse = APIResponse()
var responseCode : Int32 = 200
var responseMessage : String = "OK"
let responseJSON : String? = "null"
switch request.getMethodName()! {
default:
// 404 - response null.
responseCode = 404
responseMessage = "BarometerBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15."
}
response.setResponse(responseJSON!)
response.setStatusCode(responseCode)
response.setStatusMessage(responseMessage)
return response
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| c57ab48dde00422fb13f7d1ddbd6ded8 | 34.876289 | 188 | 0.625 | false | false | false | false |
shanyazhou/XMG_DouYuTV | refs/heads/master | DouYuTV/DouYuTV/Classes/Home/Controller/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// DouYuTV
//
// Created by shanyazhou on 2017/4/25.
// Copyright © 2017年 SYZ. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setupUI()
}
}
// MARK: - 设置UI界面
extension HomeViewController {
fileprivate func setupUI() {
//1.设置导航栏
setupNavigationBar()
}
//设置导航栏
private func setupNavigationBar() {
//1.设置左侧的item
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
//2.设置右侧的item
let size = CGSize(width: 40, height: 40)
let historyItem = UIBarButtonItem(imageName: "Image_my_history", highImageName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_click", size: size)
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem]
}
}
| fa8e47098f809705641001a4531aeb26 | 23.93617 | 125 | 0.627986 | false | false | false | false |
WeMadeCode/ZXPageView | refs/heads/master | Example/Pods/SwifterSwift/Sources/SwifterSwift/SwiftStdlib/OptionalExtensions.swift | mit | 1 | //
// OptionalExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 3/3/17.
// Copyright © 2017 SwifterSwift
//
// MARK: - Methods
public extension Optional {
/// SwifterSwift: Get self of default value (if self is nil).
///
/// let foo: String? = nil
/// print(foo.unwrapped(or: "bar")) -> "bar"
///
/// let bar: String? = "bar"
/// print(bar.unwrapped(or: "foo")) -> "bar"
///
/// - Parameter defaultValue: default value to return if self is nil.
/// - Returns: self if not nil or default value if nil.
func unwrapped(or defaultValue: Wrapped) -> Wrapped {
// http://www.russbishop.net/improving-optionals
return self ?? defaultValue
}
/// SwifterSwift: Gets the wrapped value of an optional. If the optional is `nil`, throw a custom error.
///
/// let foo: String? = nil
/// try print(foo.unwrapped(or: MyError.notFound)) -> error: MyError.notFound
///
/// let bar: String? = "bar"
/// try print(bar.unwrapped(or: MyError.notFound)) -> "bar"
///
/// - Parameter error: The error to throw if the optional is `nil`.
/// - Returns: The value wrapped by the optional.
/// - Throws: The error passed in.
func unwrapped(or error: Error) throws -> Wrapped {
guard let wrapped = self else { throw error }
return wrapped
}
/// SwifterSwift: Runs a block to Wrapped if not nil
///
/// let foo: String? = nil
/// foo.run { unwrappedFoo in
/// // block will never run sice foo is nill
/// print(unwrappedFoo)
/// }
///
/// let bar: String? = "bar"
/// bar.run { unwrappedBar in
/// // block will run sice bar is not nill
/// print(unwrappedBar) -> "bar"
/// }
///
/// - Parameter block: a block to run if self is not nil.
func run(_ block: (Wrapped) -> Void) {
// http://www.russbishop.net/improving-optionals
_ = map(block)
}
/// SwifterSwift: Assign an optional value to a variable only if the value is not nil.
///
/// let someParameter: String? = nil
/// let parameters = [String:Any]() //Some parameters to be attached to a GET request
/// parameters[someKey] ??= someParameter //It won't be added to the parameters dict
///
/// - Parameters:
/// - lhs: Any?
/// - rhs: Any?
static func ??= (lhs: inout Optional, rhs: Optional) {
guard let rhs = rhs else { return }
lhs = rhs
}
/// SwifterSwift: Assign an optional value to a variable only if the variable is nil.
///
/// var someText: String? = nil
/// let newText = "Foo"
/// let defaultText = "Bar"
/// someText ?= newText //someText is now "Foo" because it was nil before
/// someText ?= defaultText //someText doesn't change its value because it's not nil
///
/// - Parameters:
/// - lhs: Any?
/// - rhs: Any?
static func ?= (lhs: inout Optional, rhs: @autoclosure () -> Optional) {
if lhs == nil {
lhs = rhs()
}
}
}
// MARK: - Methods (Collection)
public extension Optional where Wrapped: Collection {
/// SwifterSwift: Check if optional is nil or empty collection.
var isNilOrEmpty: Bool {
guard let collection = self else { return true }
return collection.isEmpty
}
/// SwifterSwift: Returns the collection only if it is not nill and not empty.
var nonEmpty: Wrapped? {
guard let collection = self else { return nil }
guard !collection.isEmpty else { return nil }
return collection
}
}
// MARK: - Operators
infix operator ??= : AssignmentPrecedence
infix operator ?= : AssignmentPrecedence
| 249b8981f752990d74245c79d3372cc4 | 31.560345 | 108 | 0.58062 | false | false | false | false |
AbePralle/PlasmacoreDemos | refs/heads/master | SlidingPuzzle/Libraries/Plasmacore/Swift/PlasmacoreMessage.swift | unlicense | 2 | #if os(OSX)
import Cocoa
#endif
class PlasmacoreMessage
{
struct DataType
{
static let STRING = 1
static let REAL64 = 2
static let INT64 = 3
static let INT32 = 4
static let LOGICAL = 5
static let BYTES = 6
}
static var next_message_id = 1
var type : String
var message_id : Int
var data = [UInt8]()
var string_buffer = [Character]()
var entries = [String:Int]()
var position = 0
convenience init( type:String )
{
self.init( type:type, message_id:PlasmacoreMessage.next_message_id )
PlasmacoreMessage.next_message_id += 1
}
convenience init( data:[UInt8] )
{
self.init()
self.data = data
type = readString()
message_id = readIntX()
while (indexAnother()) {}
}
convenience init( type:String, message_id:Int )
{
self.init()
self.type = type
self.message_id = message_id
writeString( type )
writeIntX( message_id )
}
init()
{
type = "Unspecified"
message_id = 0
}
func createReply()->PlasmacoreMessage
{
return PlasmacoreMessage( type:"<reply>", message_id:message_id )
}
func getBytes( name:String )->[UInt8]
{
if let offset = entries[ name ]
{
position = offset
switch (readIntX())
{
case DataType.BYTES:
let count = readIntX()
var buffer = [UInt8]()
buffer.reserveCapacity( count )
for _ in 1...count
{
buffer.append( UInt8(readByte()) )
}
return buffer
default:
break
}
}
return [UInt8]()
}
func getInt32( name:String, default_value:Int=0 )->Int
{
if let offset = entries[ name ]
{
position = offset
switch (readIntX())
{
case DataType.REAL64:
return Int(readReal64())
case DataType.INT64:
return Int(readInt64X())
case DataType.INT32:
return readIntX()
case DataType.LOGICAL:
return readIntX()
default:
return default_value
}
}
return default_value
}
func getInt64( name:String, default_value:Int64=0 )->Int64
{
if let offset = entries[ name ]
{
position = offset
switch (readIntX())
{
case DataType.REAL64:
return Int64(readReal64())
case DataType.INT64:
return readInt64X()
case DataType.INT32:
return Int64(readIntX())
case DataType.LOGICAL:
return Int64(readIntX())
default:
return default_value
}
}
return default_value
}
func getLogical( name:String, default_value:Bool=false )->Bool
{
return getInt32( name: name, default_value:(default_value ? 1 : 0) ) != 0
}
func getReal64( name:String, default_value:Double=0.0 )->Double
{
if let offset = entries[ name ]
{
position = offset
switch (readIntX())
{
case DataType.REAL64:
return readReal64()
case DataType.INT64:
return Double(readInt64X())
case DataType.INT32:
return Double(readIntX())
case DataType.LOGICAL:
return Double(readIntX())
default:
return default_value
}
}
return default_value
}
func getString( name:String, default_value:String="" )->String
{
if let offset = entries[ name ]
{
position = offset
switch (readIntX())
{
case DataType.STRING:
return readString()
default:
return default_value
}
}
return default_value
}
func indexAnother()->Bool
{
if (position == data.count) { return false }
let name = readString()
entries[ name ] = position
switch (readIntX())
{
case DataType.STRING:
let count = readIntX()
for _ in 1...count
{
_ = readIntX()
}
return true
case DataType.REAL64:
_ = readReal64()
return true
case DataType.INT64:
_ = readInt64X()
return true
case DataType.INT32:
_ = readIntX()
return true
case DataType.LOGICAL:
_ = readIntX()
return true
case DataType.BYTES:
position += readIntX()
return true
default:
return false
}
}
func send()
{
Plasmacore.singleton.send( self );
}
func send_rsvp( _ callback:@escaping ((PlasmacoreMessage)->Void) )
{
Plasmacore.singleton.send_rsvp( self, callback:callback );
}
@discardableResult
func set( name:String, value:[UInt8] )->PlasmacoreMessage
{
position = data.count
writeString( name )
entries[ name ] = position
writeIntX( DataType.BYTES )
writeIntX( value.count )
for byte in value
{
writeIntX( Int(byte) )
}
return self
}
@discardableResult
func set( name:String, value:Int64 )->PlasmacoreMessage
{
position = data.count
writeString( name )
entries[ name ] = position
writeIntX( DataType.INT64 )
writeIntX( Int(value>>32) )
writeIntX( Int(value) )
return self
}
@discardableResult
func set( name:String, value:Int )->PlasmacoreMessage
{
position = data.count
writeString( name )
entries[ name ] = position
writeIntX( DataType.INT32 )
writeIntX( value )
return self
}
@discardableResult
func set( name:String, value:Bool )->PlasmacoreMessage
{
position = data.count
writeString( name )
entries[ name ] = position
writeIntX( DataType.LOGICAL )
writeIntX( value ? 1 : 0 )
return self
}
@discardableResult
func set( name:String, value:Double )->PlasmacoreMessage
{
position = data.count
writeString( name )
entries[ name ] = position
writeIntX( DataType.REAL64 )
writeReal64( value )
return self
}
@discardableResult
func set( name:String, value:String )->PlasmacoreMessage
{
position = data.count
writeString( name )
entries[ name ] = position
writeIntX( DataType.STRING )
writeString( value )
return self
}
//---------------------------------------------------------------------------
// PRIVATE
//---------------------------------------------------------------------------
fileprivate func readByte()->Int
{
if (position >= data.count) { return 0 }
position += 1
return Int(data[position-1])
}
fileprivate func readInt64X()->Int64
{
let result = Int64( readIntX() ) << 32
return result | Int64( UInt32(readIntX()) )
}
fileprivate func readInt32()->Int
{
var result = readByte()
result = (result << 8) | readByte()
result = (result << 8) | readByte()
return (result << 8) | readByte()
}
fileprivate func readIntX()->Int
{
let b = readByte()
if ((b & 0xc0) != 0x80)
{
return b
}
switch (b & 0x30)
{
case 0x00:
return ((b & 15) << 8) | readByte()
case 0x10:
position += 2
if (position > data.count)
{
position = data.count
return 0
}
return ((b & 15) << 16) | (Int(data[position-2])<<8) | Int(data[position-1])
case 0x20:
position += 3
if (position > data.count)
{
position = data.count
return 0
}
return ((b & 15) << 24) | (Int(data[position-3])<<16) | (Int(data[position-2]<<8)) | Int(data[position-1])
default:
return readInt32()
}
}
fileprivate func readReal64()->Double
{
var n = UInt64( readInt32() ) << 32
n = n | UInt64( UInt32(readInt32()) )
return unsafeBitCast( n, to:Double.self )
}
fileprivate func readString()->String
{
string_buffer.removeAll( keepingCapacity:true )
let count = readIntX()
for _ in 0..<count
{
string_buffer.append( Character(UnicodeScalar(readIntX())!) )
}
return String( string_buffer )
}
fileprivate func writeByte( _ value:Int )
{
position += 1
if (position > data.count)
{
data.append( UInt8(value&255) )
}
else
{
data[ position-1 ] = UInt8( value )
}
}
fileprivate func writeInt32( _ value:Int )
{
writeByte( value >> 24 )
writeByte( value >> 16 )
writeByte( value >> 8 )
writeByte( value )
}
fileprivate func writeInt64X( _ value:Int64 )
{
writeIntX( Int(value>>32) )
writeIntX( Int(value) )
}
fileprivate func writeIntX( _ value:Int )
{
if (value >= -64 && value <= 127)
{
writeByte( value )
}
else if (value >= -0x400 && value <= 0x3ff)
{
writeByte( 0x80 | ((value >> 8) & 15) )
writeByte( value )
}
else if (value >= -0x40000 && value <= 0x3ffff)
{
writeByte( 0x90 | ((value >> 16) & 15) )
writeByte( value >> 8 )
writeByte( value )
}
else if (value >= -0x4000000 && value <= 0x3ffffff)
{
writeByte( 0xa0 | ((value >> 24) & 15) )
writeByte( value >> 16 )
writeByte( value >> 8 )
writeByte( value )
}
else
{
writeByte( 0xb0 )
writeInt32( value )
}
}
fileprivate func writeReal64( _ value:Double )
{
let bits = unsafeBitCast(value, to: Int64.self)
writeInt32( Int((bits>>32)&0xFFFFffff) )
writeInt32( Int(bits&0xFFFFffff) )
}
fileprivate func writeString( _ value:String )
{
writeIntX( value.unicodeScalars.count )
for ch in value.unicodeScalars
{
writeIntX( Int(ch.value) )
}
}
}
| 1aea4df6e1fc8f7c703c0a130900e777 | 19.396104 | 114 | 0.563515 | false | false | false | false |
MakeSchool/TripPlanner | refs/heads/master | TripPlannerTests/Model/JSONEncodingSpec.swift | mit | 1 | //
// JSONEncodingSpec.swift
// TripPlanner
//
// Created by Benjamin Encz on 10/8/15.
// Copyright © 2015 Make School. All rights reserved.
//
import Foundation
import Quick
import Nimble
import CoreLocation
@testable import TripPlanner
class JSONEncodingSpec: QuickSpec {
override func spec() {
describe("JSONEncoding") {
context("encodeJSONTrip") {
it("generates valid and JSON that correctly represents the provided trip") {
let stack = CoreDataStack(stackType: .InMemory)
let client = CoreDataClient(stack: stack)
let trip = Trip(context: client.context)
trip.serverID = "10"
let waypoint1 = Waypoint(context: client.context)
waypoint1.location = CLLocationCoordinate2D(latitude: 30.8, longitude: 14.2)
waypoint1.trip = trip
let waypoint2 = Waypoint(context: client.context)
waypoint2.location = CLLocationCoordinate2D(latitude: 30.8, longitude: 14.2)
waypoint2.trip = trip
client.saveStack()
let jsonData = JSONEncoding.encodeJSONTrip(trip)
let parsedTrip: JSONTrip = parse(jsonData)!
expect(parsedTrip.serverID).to(equal("10"))
expect(parsedTrip.waypoints.count).to(equal(2))
expect(parsedTrip.waypoints[0].location.latitude).to(equal(30.8))
expect(parsedTrip.waypoints[0].location.longitude).to(equal(14.2))
}
}
}
}
}
| 442237ad0619623f503b91b02fdc50c1 | 25.610169 | 86 | 0.605096 | false | false | false | false |
Desgard/Calendouer-iOS | refs/heads/master | Calendouer/Calendouer/App/View/setting/SwitchSettingTableViewCell.swift | mit | 1 | //
// SwitchSettingTableViewCell.swift
// Calendouer
//
// Created by 段昊宇 on 2017/3/9.
// Copyright © 2017年 Desgard_Duan. All rights reserved.
//
import UIKit
import SnapKit
import TKSwitcherCollection
class SwitchSettingTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
var valueChanged: (_ isOn: Bool) -> () = {
status in
}
var onSwitch: TKSmileSwitch = {
var _switch = TKSmileSwitch(frame: CGRect(x: 0, y: 0, width: 40, height: 20))
_switch.backgroundColor = UIColor.clear
return _switch
}()
override func awakeFromNib() {
super.awakeFromNib()
initialView()
setLayout()
}
private func initialView() {
onSwitch.addTarget(self, action: #selector(switchValueChange), for: .valueChanged)
self.addSubview(onSwitch)
}
private func setLayout() {
onSwitch.snp.makeConstraints { (make) in
make.right.equalTo(self.snp.right).offset(-30)
make.centerY.equalTo(titleLabel)
make.height.equalTo(20)
make.width.equalTo(40)
}
}
public func initialCell(title: String, status: Bool, switchAction: @escaping (_ isOn: Bool) -> ()) {
self.titleLabel.text = title
if !status {
self.onSwitch.changeValue()
}
self.valueChanged = switchAction
}
public func getSwitchStatus() -> Bool {
return onSwitch.isOn
}
public func switchValueChange () {
print("The switch status: ", !self.getSwitchStatus())
self.valueChanged(!self.getSwitchStatus())
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| 6aef673d5bcf1c23029f2c016b03cf95 | 25.485294 | 104 | 0.607996 | false | false | false | false |
arcontrerasa/SwiftParseRestClient | refs/heads/master | ParseRestClient/Operation.swift | mit | 1 | //
// Operation.swift
// Pods
//
// Created by Armando Contreras on 9/15/15.
//
//
import Foundation
import UIKit
class Operation: NSOperation {
// use the KVO mechanism to indicate that changes to "state" affect other properties as well
class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsCancelled() -> Set<NSObject> {
return ["state"]
}
// MARK: State Management
private enum State: Int, Comparable {
/// The initial state of an `Operation`.
case Initialized
/// The `Operation` is ready to begin evaluating conditions.
case Pending
/// The `Operation` is evaluating conditions.
case EvaluatingConditions
/**
The `Operation`'s conditions have all been satisfied, and it is ready
to execute.
*/
case Ready
/// The `Operation` is executing.
case Executing
/**
Execution of the `Operation` has finished, but it has not yet notified
the queue of this.
*/
case Finishing
/// The `Operation` has finished executing.
case Finished
/// The `Operation` has been cancelled.
case Cancelled
}
func execute() {
print("\(self.dynamicType) must override `execute()`.")
finish()
}
/**
Indicates that the Operation can now begin to evaluate readiness conditions,
if appropriate.
*/
func willEnqueue() {
state = .Pending
}
/// Private storage for the `state` property that will be KVO observed.
private var _state = State.Initialized
private var state: State {
get {
return _state
}
set(newState) {
// Manually fire the KVO notifications for state change, since this is "private".
willChangeValueForKey("state")
switch (_state, newState) {
case (.Cancelled, _):
break // cannot leave the cancelled state
case (.Finished, _):
break // cannot leave the finished state
default:
assert(_state != newState, "Performing invalid cyclic state transition.")
_state = newState
}
didChangeValueForKey("state")
}
}
private var _internalErrors = [NSError]()
override func cancel() {
cancelWithError()
}
func cancelWithError(error: NSError? = nil) {
if let error = error {
_internalErrors.append(error)
}
state = .Cancelled
}
private(set) var observers = [OperationObserver]()
func addObserver(observer: OperationObserver) {
assert(state < .Executing, "Cannot modify observers after execution has begun.")
observers.append(observer)
}
private var hasFinishedAlready = false
final func finish(errors: [NSError] = []) {
if !hasFinishedAlready {
hasFinishedAlready = true
state = .Finishing
state = .Finished
}
}
}
// Simple operator functions to simplify the assertions used above.
private func <(lhs: Operation.State, rhs: Operation.State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
private func ==(lhs: Operation.State, rhs: Operation.State) -> Bool {
return lhs.rawValue == rhs.rawValue
} | 2d5fbae050e52586ae4a8d7e64555d6b | 25.013514 | 96 | 0.564302 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | StripePaymentSheet/StripePaymentSheet/Internal/API Bindings/Link/ConsumerSession-SignupResponse.swift | mit | 1 | //
// ConsumerSession-SignupResponse.swift
// StripePaymentSheet
//
// Created by Ramon Torres on 4/22/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripePayments
extension ConsumerSession {
class SignupResponse: NSObject, STPAPIResponseDecodable {
let consumerSession: ConsumerSession
let preferences: ConsumerSession.Preferences
let allResponseFields: [AnyHashable: Any]
init(
consumerSession: ConsumerSession,
preferences: ConsumerSession.Preferences,
allResponseFields: [AnyHashable: Any]
) {
self.consumerSession = consumerSession
self.preferences = preferences
self.allResponseFields = allResponseFields
super.init()
}
static func decodedObject(fromAPIResponse response: [AnyHashable : Any]?) -> Self? {
guard
let response = response,
let consumerSession = ConsumerSession.decodedObject(fromAPIResponse: response),
let publishableKey = response["publishable_key"] as? String
else {
return nil
}
return SignupResponse(
consumerSession: consumerSession,
preferences: Preferences(publishableKey: publishableKey),
allResponseFields: response
) as? Self
}
}
}
| 98c5404b3419a2e8843ef4726219858f | 28.673469 | 95 | 0.617607 | false | false | false | false |
danielgindi/Charts | refs/heads/master | Source/Charts/Data/Implementations/Standard/CandleChartDataSet.swift | apache-2.0 | 2 | //
// CandleChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class CandleChartDataSet: LineScatterCandleRadarChartDataSet, CandleChartDataSetProtocol
{
public required init()
{
super.init()
}
public override init(entries: [ChartDataEntry], label: String)
{
super.init(entries: entries, label: label)
}
// MARK: - Data functions and accessors
open override func calcMinMax(entry e: ChartDataEntry)
{
guard let e = e as? CandleChartDataEntry
else { return }
_yMin = Swift.min(e.low, _yMin)
_yMax = Swift.max(e.high, _yMax)
calcMinMaxX(entry: e)
}
open override func calcMinMaxY(entry e: ChartDataEntry)
{
guard let e = e as? CandleChartDataEntry
else { return }
_yMin = Swift.min(e.low, _yMin)
_yMax = Swift.max(e.high, _yMin)
_yMin = Swift.min(e.low, _yMax)
_yMax = Swift.max(e.high, _yMax)
}
// MARK: - Styling functions and accessors
/// the space between the candle entries
///
/// **default**: 0.1 (10%)
private var _barSpace: CGFloat = 0.1
/// the space that is left out on the left and right side of each candle,
/// **default**: 0.1 (10%), max 0.45, min 0.0
open var barSpace: CGFloat
{
get
{
return _barSpace
}
set
{
_barSpace = newValue.clamped(to: 0...0.45)
}
}
/// should the candle bars show?
/// when false, only "ticks" will show
///
/// **default**: true
open var showCandleBar: Bool = true
/// the width of the candle-shadow-line in pixels.
///
/// **default**: 1.5
open var shadowWidth = CGFloat(1.5)
/// the color of the shadow line
open var shadowColor: NSUIColor?
/// use candle color for the shadow
open var shadowColorSameAsCandle = false
/// Is the shadow color same as the candle color?
open var isShadowColorSameAsCandle: Bool { return shadowColorSameAsCandle }
/// color for open == close
open var neutralColor: NSUIColor?
/// color for open > close
open var increasingColor: NSUIColor?
/// color for open < close
open var decreasingColor: NSUIColor?
/// Are increasing values drawn as filled?
/// increasing candlesticks are traditionally hollow
open var increasingFilled = false
/// Are increasing values drawn as filled?
open var isIncreasingFilled: Bool { return increasingFilled }
/// Are decreasing values drawn as filled?
/// descreasing candlesticks are traditionally filled
open var decreasingFilled = true
/// Are decreasing values drawn as filled?
open var isDecreasingFilled: Bool { return decreasingFilled }
}
| a61c26dee70fc0a88d4a1219180f1cdd | 25.128205 | 93 | 0.611711 | false | false | false | false |
Mioke/SwiftArchitectureWithPOP | refs/heads/master | SwiftyArchitecture/Demo/ViewController/DataCenterTestViewController.swift | mit | 1 | //
// DataCenterTestVCViewController.swift
// SAD
//
// Created by KelanJiang on 2020/4/13.
// Copyright © 2020 KleinMioke. All rights reserved.
//
import UIKit
import RxDataSources
import RxSwift
import RxCocoa
import RxRealm
@_exported import MIOSwiftyArchitecture
extension TestObj: IdentifiableType {
typealias Identity = String
var identity: String {
return self.key
}
}
class DataCenterTestViewModel: NSObject {
}
class DataCenterTestCell: UITableViewCell {
var valueLabel: UILabel!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
valueLabel = UILabel()
contentView.addSubview(valueLabel)
valueLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true
valueLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
valueLabel.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension DataCenterTestCell: ReusableView { }
class DataCenterTestViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
typealias Section = RxTableViewSectionedAnimatedDataSource<AnimatableSectionModel<String, TestObj>>
let datasource = Section(configureCell: { datasource, tableView, indexPath, item in
let cell = tableView.dequeReusableCell(forIndexPath: indexPath) as DataCenterTestCell
cell.textLabel?.text = item.key
cell.valueLabel?.text = "\(item.value)"
return cell
})
let disposeBag: DisposeBag = DisposeBag()
var objs: [TestObj] = [] {
didSet {
relay.accept(objs)
}
}
lazy var relay: BehaviorRelay<[TestObj]> = {
return BehaviorRelay(value: objs)
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let button = UIBarButtonItem(
title: "Add",
style: UIBarButtonItem.Style.plain,
target: self,
action: #selector(addSomeObj))
let refreshItem = UIBarButtonItem(
title: "Refresh",
style: .plain,
target: self,
action: #selector(refresh))
self.navigationItem.rightBarButtonItems = [button, refreshItem]
tableView.register(DataCenterTestCell.self,
forCellReuseIdentifier: DataCenterTestCell.reusedIdentifier)
DataAccessObject<TestObj>.all
.map { $0.sorted(by: <) }
.map { [AnimatableSectionModel(model: "", items: $0)] }
.bind(to: tableView.rx.items(dataSource: datasource))
.disposed(by: disposeBag)
tableView.rx
.modelSelected(TestObj.self)
.map { $0.key }
.bind { (key) in
let vc = TestObjModifyVC()
vc.objectKey = key
self.navigationController?.pushViewController(vc, animated: true)
}.disposed(by: self.disposeBag)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// relay.map { $0.sorted(by: { $0.value < $1.value })}
// .map { [AnimatableSectionModel(model: "", items: $0)] }
// .bind(to: tableView.rx.items(dataSource: datasource))
// .disposed(by: disposeBag)
}
func createObj() -> TestObj {
let key = "Key random \(arc4random())"
let obj = TestObj(with: key)
obj.value = Int(arc4random())
return obj
}
@objc func addSomeObj() -> Void {
let obj = createObj()
Observable.just(obj)
.bind(to: AppContextCurrentDatabase().rx.add())
.disposed(by: self.disposeBag)
// try? AppContext.current.db.realm.write {
// AppContext.current.db.realm.add(obj)
// }
// objs.append(createObj())
var racers: [Racer] = []
let aDog = Dog(speed: 100)
racers.append(aDog)
let aMan = Human(speed: 80)
racers.append(aMan)
_ = racers.fastest()
// racers.bla()
let humans = [Human]()
humans.bla()
_ = (humans as [Racer]).fastest()
// humans.fastest()
}
@objc func refresh() -> Void {
print("Show loading")
let request = Request<TestObj>()
DataAccessObject<TestObj>
.update(with: request)
.subscribe({ event in
switch event {
case .completed:
print("Hide loading")
case .error(let error as NSError):
print("Hide loading with error: \(error.localizedDescription)")
default:
break
}
})
.disposed(by: self.disposeBag)
}
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
}
protocol Racer {
var speed: Double { get }
}
extension Sequence where Iterator.Element == Racer {
func fastest() -> Iterator.Element? {
return self.max { $0.speed < $1.speed}
}
}
extension Sequence where Iterator.Element: Racer {
func bla() -> Void {
}
}
struct Human: Racer {
var speed: Double
}
struct Dog: Racer {
var speed: Double
}
| b396e5831c75ce56003295682b5d0bf7 | 26.803738 | 112 | 0.581345 | false | true | false | false |
zmarvin/EnjoyMusic | refs/heads/master | Pods/Macaw/Source/render/GroupRenderer.swift | mit | 1 | import Foundation
import UIKit
class GroupRenderer: NodeRenderer {
let group: Group
fileprivate var renderers: [NodeRenderer] = []
init(group: Group, ctx: RenderContext, animationCache: AnimationCache) {
self.group = group
super.init(node: group, ctx: ctx, animationCache: animationCache)
updateRenderers()
}
override func doAddObservers() {
super.doAddObservers()
group.contentsVar.onChange { _ in
self.updateRenderers()
}
}
override func node() -> Node {
return group
}
override func doRender(_ force: Bool, opacity: Double) {
renderers.forEach { renderer in
renderer.render(force: force, opacity: opacity)
}
}
override func doFindNodeAt(location: CGPoint) -> Node? {
for renderer in renderers.reversed() {
if let node = renderer.findNodeAt(location: location) {
return node
}
}
return nil
}
override func dispose() {
super.dispose()
renderers.forEach { renderer in renderer.dispose() }
renderers = []
}
private func updateRenderers() {
var nodeToRenderer: [Node: NodeRenderer] = [:]
for renderer in renderers {
nodeToRenderer[renderer.node()] = renderer
}
self.renderers = []
for node in group.contents {
if let renderer = nodeToRenderer.removeValue(forKey: node) {
self.renderers.append(renderer)
} else {
self.renderers.append(RenderUtils.createNodeRenderer(node, context: ctx, animationCache: animationCache))
}
}
for renderer in nodeToRenderer.values {
renderer.dispose()
}
}
}
| 71cfae4b180ced3ae50109428263cc44 | 22.939394 | 109 | 0.667089 | false | false | false | false |
kperryua/swift | refs/heads/master | test/decl/var/static_var.swift | apache-2.0 | 3 | // RUN: %target-parse-verify-swift -parse-as-library
// See also rdar://15626843.
static var gvu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{global 'var' declaration requires an initializer expression or getter/setter specifier}}
class var gvu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{global 'var' declaration requires an initializer expression or getter/setter specifier}}
override static var gvu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
// expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}}
override class var gvu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
// expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}}
static override var gvu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}}
// expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}}
class override var gvu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}}
// expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}}
static var gvu7: Int { // expected-error {{static properties may only be declared on a type}}{{1-8=}}
return 42
}
class var gvu8: Int { // expected-error {{class properties may only be declared on a type}}{{1-7=}}
return 42
}
static let glu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{global 'let' declaration requires an initializer expression}}
class let glu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{global 'let' declaration requires an initializer expression}}
override static let glu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
// expected-error@-2 {{global 'let' declaration requires an initializer expression}}
override class let glu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
// expected-error@-2 {{global 'let' declaration requires an initializer expression}}
static override let glu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}}
// expected-error@-2 {{global 'let' declaration requires an initializer expression}}
class override let glu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}}
// expected-error@-2 {{global 'let' declaration requires an initializer expression}}
static var gvi1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}}
class var gvi2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}}
override static var gvi3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
override class var gvi4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
static override var gvi5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}}
class override var gvi6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}}
static let gli1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}}
class let gli2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}}
override static let gli3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
override class let gli4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
static override let gli5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}}
class override let gli6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}}
func inGlobalFunc() {
static var v1: Int // expected-error {{static properties may only be declared on a type}}{{3-10=}}
class var v2: Int // expected-error {{class properties may only be declared on a type}}{{3-9=}}
static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{3-10=}}
class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{3-9=}}
v1 = 1; v2 = 1
_ = v1+v2+l1+l2
}
struct InMemberFunc {
func member() {
static var v1: Int // expected-error {{static properties may only be declared on a type}}{{5-12=}}
class var v2: Int // expected-error {{class properties may only be declared on a type}}{{5-11=}}
static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{5-12=}}
class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{5-11=}}
v1 = 1; v2 = 1
_ = v1+v2+l1+l2
}
}
struct S { // expected-note 3{{extended type declared here}} expected-note{{did you mean 'S'?}}
static var v1: Int = 0
class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static var v3: Int { return 0 }
class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}}
static let l1: Int = 0
class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}}
}
extension S {
static var ev1: Int = 0
class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static var ev3: Int { return 0 }
class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static let el1: Int = 0
class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
}
enum E { // expected-note 3{{extended type declared here}} expected-note{{did you mean 'E'?}}
static var v1: Int = 0
class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static var v3: Int { return 0 }
class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}}
static let l1: Int = 0
class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}}
}
extension E {
static var ev1: Int = 0
class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static var ev3: Int { return 0 }
class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static let el1: Int = 0
class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
}
class C { // expected-note{{did you mean 'C'?}}
static var v1: Int = 0
class final var v3: Int = 0 // expected-error {{class stored properties not supported}}
class var v4: Int = 0 // expected-error {{class stored properties not supported}}
static var v5: Int { return 0 }
class var v6: Int { return 0 }
static final var v7: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}}
static let l1: Int = 0
class let l2: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
class final let l3: Int = 0 // expected-error {{class stored properties not supported}}
static final let l4 = 2 // expected-error {{static declarations are already final}} {{10-16=}}
}
extension C {
static var ev1: Int = 0
class final var ev2: Int = 0 // expected-error {{class stored properties not supported}}
class var ev3: Int = 0 // expected-error {{class stored properties not supported}}
static var ev4: Int { return 0 }
class var ev5: Int { return 0 }
static final var ev6: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}}
static let el1: Int = 0
class let el2: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
class final let el3: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
static final let el4: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}}
}
protocol P { // expected-note{{did you mean 'P'?}}
// Both `static` and `class` property requirements are equivalent in protocols rdar://problem/17198298
static var v1: Int { get }
class var v2: Int { get } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static final var v3: Int { get } // expected-error {{only classes and class members may be marked with 'final'}}
static let l1: Int // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}}
class let l2: Int // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}}
}
struct S1 {
// rdar://15626843
static var x: Int // expected-error {{'static var' declaration requires an initializer expression or getter/setter specifier}}
var y = 1
static var z = 5
}
extension S1 {
static var zz = 42
static var xy: Int { return 5 }
}
enum E1 {
static var y: Int {
get {}
}
}
class C1 {
class var x: Int // expected-error {{class stored properties not supported}} expected-error {{'class var' declaration requires an initializer expression or getter/setter specifier}}
}
class C2 {
var x: Int = 19
class var x: Int = 17 // expected-error{{class stored properties not supported}}
func xx() -> Int { return self.x + C2.x }
}
class ClassHasVars {
static var computedStatic: Int { return 0 } // expected-note 3{{overridden declaration is here}}
final class var computedFinalClass: Int { return 0 } // expected-note 3{{overridden declaration is here}}
class var computedClass: Int { return 0 }
var computedInstance: Int { return 0 }
}
class ClassOverridesVars : ClassHasVars {
override static var computedStatic: Int { return 1 } // expected-error {{cannot override static var}}
override static var computedFinalClass: Int { return 1 } // expected-error {{static var overrides a 'final' class var}}
override class var computedClass: Int { return 1 }
override var computedInstance: Int { return 1 }
}
class ClassOverridesVars2 : ClassHasVars {
override final class var computedStatic: Int { return 1 } // expected-error {{cannot override static var}}
override final class var computedFinalClass: Int { return 1 } // expected-error {{class var overrides a 'final' class var}}
}
class ClassOverridesVars3 : ClassHasVars {
override class var computedStatic: Int { return 1 } // expected-error {{cannot override static var}}
override class var computedFinalClass: Int { return 1 } // expected-error {{class var overrides a 'final' class var}}
}
struct S2 {
var x: Int = 19
static var x: Int = 17
func xx() -> Int { return self.x + C2.x }
}
// Mutating vs non-mutating conflict with static stored property witness - rdar://problem/19887250
protocol Proto {
static var name: String {get set}
}
struct ProtoAdopter : Proto {
static var name: String = "name" // no error, even though static setters aren't mutating
}
// Make sure the logic remains correct if we synthesized accessors for our stored property
protocol ProtosEvilTwin {
static var name: String {get set}
}
extension ProtoAdopter : ProtosEvilTwin {}
// rdar://18990358
public struct Foo { // expected-note {{to match this opening '{'}}}
public static let S { a // expected-error{{computed property must have an explicit type}}
// expected-error@-1{{type annotation missing in pattern}}
// expected-error@-2{{'let' declarations cannot be computed properties}}
// expected-error@-3{{use of unresolved identifier 'a'}}
}
// expected-error@+1 {{expected '}' in struct}}
| 0620886714a60e3f551f3b3dae90ef56 | 54.229323 | 251 | 0.69757 | false | false | false | false |
apple/swift-nio-extras | refs/heads/main | Sources/NIOExtras/DebugInboundEventsHandler.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(tvOS) || os(iOS) || os(watchOS)
import Darwin
#else
import Glibc
#endif
import NIOCore
/// `ChannelInboundHandler` that prints all inbound events that pass through the pipeline by default,
/// overridable by providing your own closure for custom logging. See ``DebugOutboundEventsHandler`` for outbound events.
public class DebugInboundEventsHandler: ChannelInboundHandler {
/// The type of the inbound data which is wrapped in `NIOAny`.
public typealias InboundIn = Any
/// The type of the inbound data which will be forwarded to the next `ChannelInboundHandler` in the `ChannelPipeline`.
public typealias InboudOut = Any
/// Enumeration of possible `ChannelHandler` events which can occur.
public enum Event {
/// Channel was registered.
case registered
/// Channel was unregistered.
case unregistered
/// Channel became active.
case active
/// Channel became inactive.
case inactive
/// Data was received.
case read(data: NIOAny)
/// Current read loop finished.
case readComplete
/// Writability state of the channel changed.
case writabilityChanged(isWritable: Bool)
/// A user inbound event was received.
case userInboundEventTriggered(event: Any)
/// An error was caught.
case errorCaught(Error)
}
var logger: (Event, ChannelHandlerContext) -> ()
/// Initialiser.
/// - Parameter logger: Method for logging events which occur.
public init(logger: @escaping (Event, ChannelHandlerContext) -> () = DebugInboundEventsHandler.defaultPrint) {
self.logger = logger
}
/// Logs ``Event.registered`` to ``logger``
/// Called when the `Channel` has successfully registered with its `EventLoop` to handle I/O.
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
public func channelRegistered(context: ChannelHandlerContext) {
logger(.registered, context)
context.fireChannelRegistered()
}
/// Logs ``Event.unregistered`` to ``logger``
/// Called when the `Channel` has unregistered from its `EventLoop`, and so will no longer be receiving I/O events.
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
public func channelUnregistered(context: ChannelHandlerContext) {
logger(.unregistered, context)
context.fireChannelUnregistered()
}
/// Logs ``Event.active`` to ``logger``
/// Called when the `Channel` has become active, and is able to send and receive data.
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
public func channelActive(context: ChannelHandlerContext) {
logger(.active, context)
context.fireChannelActive()
}
/// Logs ``Event.inactive`` to ``logger``
/// Called when the `Channel` has become inactive and is no longer able to send and receive data`.
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
public func channelInactive(context: ChannelHandlerContext) {
logger(.inactive, context)
context.fireChannelInactive()
}
/// Logs ``Event.read`` to ``logger``
/// Called when some data has been read from the remote peer.
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - data: The data read from the remote peer, wrapped in a `NIOAny`.
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
logger(.read(data: data), context)
context.fireChannelRead(data)
}
/// Logs ``Event.readComplete`` to ``logger``
/// Called when the `Channel` has completed its current read loop, either because no more data is available
/// to read from the transport at this time, or because the `Channel` needs to yield to the event loop to process
/// other I/O events for other `Channel`s.
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
public func channelReadComplete(context: ChannelHandlerContext) {
logger(.readComplete, context)
context.fireChannelReadComplete()
}
/// Logs ``Event.writabilityChanged`` to ``logger``
/// The writability state of the `Channel` has changed, either because it has buffered more data than the writability
/// high water mark, or because the amount of buffered data has dropped below the writability low water mark.
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
public func channelWritabilityChanged(context: ChannelHandlerContext) {
logger(.writabilityChanged(isWritable: context.channel.isWritable), context)
context.fireChannelWritabilityChanged()
}
/// Logs ``Event.userInboundEventTriggered`` to ``logger``
/// Called when a user inbound event has been triggered.
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - event: The event.
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
logger(.userInboundEventTriggered(event: event), context)
context.fireUserInboundEventTriggered(event)
}
/// Logs ``Event.errorCaught`` to ``logger``
/// An error was encountered earlier in the inbound `ChannelPipeline`.
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - error: The `Error` that was encountered.
public func errorCaught(context: ChannelHandlerContext, error: Error) {
logger(.errorCaught(error), context)
context.fireErrorCaught(error)
}
/// Print and flush a textual description of an ``Event``.
/// - parameters:
/// - event: The ``Event`` to print.
/// - context: The context `event` was received in.
public static func defaultPrint(event: Event, in context: ChannelHandlerContext) {
let message: String
switch event {
case .registered:
message = "Channel registered"
case .unregistered:
message = "Channel unregistered"
case .active:
message = "Channel became active"
case .inactive:
message = "Channel became inactive"
case .read(let data):
message = "Channel read \(data)"
case .readComplete:
message = "Channel completed reading"
case .writabilityChanged(let isWritable):
message = "Channel writability changed to \(isWritable)"
case .userInboundEventTriggered(let event):
message = "Channel user inbound event \(event) triggered"
case .errorCaught(let error):
message = "Channel caught error: \(error)"
}
print(message + " in \(context.name)")
fflush(stdout)
}
}
#if swift(>=5.6)
@available(*, unavailable)
extension DebugInboundEventsHandler: Sendable {}
#endif
| 43ab57f130de22b89a7391288ec792f9 | 41.839779 | 122 | 0.652437 | false | false | false | false |
ahoppen/JSONDecoder | refs/heads/master | Pod/Classes/JSONDecoder.swift | mit | 1 | //
// JSONDecoder.swift
// Pods
//
// Created by Alex Hoppen on 12/11/15.
//
//
import Foundation
public enum ParsingError: ErrorType {
case StringConversionFailed(atPath: String?)
case IntegerConversionFailed(atPath: String?)
case UnsingendConversionFailed(atPath: String?)
case DoubleConversionFailed(atPath: String?)
case FloatConversionFailed(atPath: String?)
case NumberConversionFailed(atPath: String?)
case NSErrorConversionFailed(atPath: String?)
case DictionaryConversionFailed(atPath: String?)
case ArrayConversionFailed(atPath: String?)
case DateConversionFailed(atPath: String?)
case EnumConversionFailed(atPath: String?)
case FoundNilWhenDecodingDictionary(atPath: String?)
}
public struct JSONDecoder {
/// The acutal value wrapped by the JSONEncoder
let value: Any
public let pathIdentifier: String?
public var description: String {
return self.toJSON()
}
// MARK: Initilaizers
public init(_ string: String) throws {
try self.init(string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
}
public init(_ data: NSData) throws {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
self.init(jsonObject)
}
private init(_ rawObject: AnyObject) {
self.init(rawObject, pathIdentifier: nil)
}
private init(_ rawObject: AnyObject, pathIdentifier: String?) {
self.pathIdentifier = pathIdentifier
if let array = rawObject as? NSArray {
var collect = [JSONDecoder]()
for val: AnyObject in array {
collect.append(JSONDecoder(val, pathIdentifier: JSONDecoder.pathIdentifierByAppending(existingPath: pathIdentifier, newPath: collect.count)))
}
value = collect
} else if let dict = rawObject as? NSDictionary {
var collect = [String:JSONDecoder]()
for (key, val) in dict {
collect["\(key)"] = JSONDecoder(val, pathIdentifier: JSONDecoder.pathIdentifierByAppending(existingPath: pathIdentifier, newPath: "\(key)"))
}
value = collect
} else {
value = rawObject
}
}
// MARK: Subscripts
public subscript(index: Int) -> JSONDecoder {
get {
if let array = self.value as? [JSONDecoder] {
if index < array.count {
return array[index]
}
}
return JSONDecoder(NSNull(), pathIdentifier: pathIdentifierByAppending(index))
}
}
public subscript(key: String) -> JSONDecoder {
get {
if let dict = self.value as? [String:JSONDecoder] {
if let value = dict[key] {
return value
}
}
return JSONDecoder(NSNull(), pathIdentifier: pathIdentifierByAppending(key))
}
}
// MARK: Decode methods
public func decode<T: JSONDecodable>() -> T? {
return T.decode(self)
}
public func decode<T: JSONDecodable>() throws -> T {
return try T.decode(self)
}
// MARK: Path identifier
func pathIdentifierByAppending(newPath: String) -> String {
return JSONDecoder.pathIdentifierByAppending(existingPath: self.pathIdentifier, newPath: newPath)
}
static func pathIdentifierByAppending(existingPath existingPath: String?, newPath: String) -> String {
if let existingPath = existingPath {
return existingPath + "." + newPath
} else {
return newPath
}
}
func pathIdentifierByAppending(newPath: Int) -> String {
return JSONDecoder.pathIdentifierByAppending(existingPath: self.pathIdentifier, newPath: newPath)
}
static func pathIdentifierByAppending(existingPath existingPath: String?, newPath: Int) -> String {
if let existingPath = existingPath {
return existingPath + "[" + String(newPath) + "]"
} else {
return "[" + String(newPath) + "]"
}
}
///print the decoder in a JSON format. Helpful for debugging.
public func toJSON() -> String {
if let array = value as? [JSONDecoder] {
var result = "["
for decoder in array {
result += decoder.toJSON() + ","
}
result.removeAtIndex(result.endIndex.advancedBy(-1))
return result + "]"
} else if let dict = value as? [String:JSONDecoder] {
var result = "{"
for (key, decoder) in dict {
result += "\"\(key)\": \(decoder.toJSON()),"
}
result.removeAtIndex(result.endIndex.advancedBy(-1))
return result + "}"
} else {
if let value = value as? String {
return "\"\(value)\""
} else if let _ = value as? NSNull {
return "null"
}
return "\(value)"
}
}
} | 9dc52e235f1f56a93dec4ce764fbfe7b | 26.974026 | 145 | 0.700488 | false | false | false | false |
blokadaorg/blokada | refs/heads/main | ios/App/Assets/Resources.swift | mpl-2.0 | 1 | //
// This file is part of Blokada.
//
// 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 https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import SwiftUI
extension Color {
static let cError = Color.red
static let cOk = Color.green
static let cAccent = Color("Orange")
static let cActive = Color.blue
static let cActivePlus = Color("Orange")
static let cActiveGradient = Color("ActiveGradient")
static let cActivePlusGradient = Color("ActivePlusGradient")
static let cPowerButtonGradient = Color("PowerButtonGradient")
static let cPowerButtonOff = Color("PowerButtonOff")
static let cBackground = Color(UIColor.systemBackground)
static let cBackgroundSplash = Color(UIColor.systemBackground)
static let cBackgroundNavBar = Color("Background")
static let cHomeBackground = Color("HomeBackground")
static let cPrimaryBackground = Color(UIColor.systemBackground)
static let cSecondaryBackground = Color(UIColor.secondarySystemBackground)
static let cTertiaryBackground = Color(UIColor.tertiarySystemBackground)
static let cPrimary = Color("Primary")
static let cSemiTransparent = Color("SemiTransparent")
}
extension Image {
static let iBlokada = "Blokada"
static let iBlokadaPlus = "BlokadaPlus"
static let iHeader = "Header"
static let iLisek = "Lisek"
static let fHamburger = "line.horizontal.3"
static let fHelp = "questionmark.circle"
static let fAccount = "person.crop.circle"
static let fLogout = "arrow.uturn.left"
static let fDonate = "heart"
static let fSettings = "gear"
static let fAbout = "person.2"
static let fPower = "power"
static let fPause = "pause"
static let fInfo = "info.circle"
static let fUp = "arrow.up.circle"
static let fLine = "minus"
static let fCheckmark = "checkmark"
static let fXmark = "xmark"
static let fMessage = "message"
static let fComputer = "desktopcomputer"
static let fHide = "eye.slash"
static let fShow = "eye"
static let fSpeed = "speedometer"
static let fLocation = "mappin.and.ellipse"
static let fShield = "lock.shield"
static let fShieldSlash = "shield.slash"
static let fDelete = "delete.left"
static let fShare = "square.and.arrow.up"
static let fCopy = "doc.on.doc"
static let fPlus = "plus.diamond"
static let fCloud = "cloud"
static let fChart = "chart.bar"
static let fPack = "cube.box.fill"
static let fFilter = "line.horizontal.3.decrease"
static let fDevices = "ipad.and.iphone"
}
| ec8c1044945281ce789b3dcbd60f17f0 | 34.269231 | 78 | 0.701563 | false | false | false | false |
SASAbus/SASAbus-ios | refs/heads/master | SASAbus/Controller/News/NewsTabBarController.swift | gpl-3.0 | 1 | //
// NewsTabBarController.swift
// SASAbus
//
// Copyright (C) 2011-2015 Raiffeisen Online GmbH (Norman Marmsoler, Jürgen Sprenger, Aaron Falk) <[email protected]>
//
// This file is part of SASAbus.
//
// SASAbus is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SASAbus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SASAbus. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import Alamofire
import RxSwift
import RxCocoa
class NewsTabBarController: MasterTabBarController {
var newsItems: [News] = []
var bolzanoViewController: NewsTableViewController!
var meranoViewController: NewsTableViewController!
init() {
super.init(nibName: nil, title: L10n.News.title)
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func viewDidLoad() {
super.viewDidLoad()
bolzanoViewController = NewsTableViewController(zone: "BZ")
meranoViewController = NewsTableViewController(zone: "ME")
bolzanoViewController.tabBarItem = UITabBarItem(
title: L10n.News.TabBar.bolzano,
image: Asset.wappenBz.image,
tag: 0
)
meranoViewController.tabBarItem = UITabBarItem(
title: L10n.News.TabBar.merano,
image: Asset.wappenMe.image,
tag: 1
)
self.viewControllers = [bolzanoViewController, meranoViewController]
self.tabBar.tintColor = Theme.orange
self.tabBar.isTranslucent = false
}
override func viewDidAppear(_ animated: Bool) {
for controller in self.viewControllers! {
_ = controller.view
}
self.getNews()
}
func getNews() {
Log.info("Loading news")
_ = NewsApi.news()
.subscribeOn(MainScheduler.asyncInstance)
.observeOn(MainScheduler.instance)
.subscribe(onNext: { news in
self.bolzanoViewController.refreshView(news)
self.meranoViewController.refreshView(news)
}, onError: { error in
ErrorHelper.log(error, message: "Failed to load news")
self.bolzanoViewController.refreshView([])
self.meranoViewController.refreshView([])
})
}
}
| bfc1d8ef1c457ecbb49be69594903dc6 | 30.043478 | 118 | 0.62605 | false | false | false | false |
SukhKalsi/MemeApp | refs/heads/master | MemeMe/MemeMeTextfieldDelegate.swift | mit | 1 | //
// MemeMeTextfieldDelegate.swift
// MemeMe
//
// Created by Sukh Kalsi on 16/08/2015.
// Copyright (c) 2015 Sukh Kalsi. All rights reserved.
//
import Foundation
import UIKit
class MemeMeTextfieldDelegate: NSObject, UITextFieldDelegate {
var activeTextFieldTag: Int?
// Just as user begins typing into any textfield, identifiy if this is first time entering specific textfield - if so clear the default text.
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
var text = textField.text
var tag = textField.tag
// assign our property so we know when editing if we need to move the view up i.e. for Bottom TextField.
self.activeTextFieldTag = tag
// The tag is defined within storyboard attributes inspector for each textfield
if (text == "TOP" && tag == 1) || (text == "BOTTOM" && tag == 2) {
textField.text = ""
}
return true
}
// Once finished, bring focus back to the main app.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// Whilst typing, convert everything to uppercase - for some reason setting capitalisation doesn't do this automatically...
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// If we have upper case, then we directly edit the text field...
if string.capitalizedString != string {
textField.text = textField.text! + string.capitalizedString
return false
}
// Otherwise we allow the proposed edit.
return true
}
} | 356211511673386bee2311b4955faa79 | 33.288462 | 145 | 0.641975 | false | false | false | false |
ahmed-abdurrahman/taby-segmented-control | refs/heads/master | UISegmentedControlAsTabbarDemo/TabySegmentedControl.swift | mit | 1 | //
// TabySegmentedControl.swift
// UISegmentedControlAsTabbarDemo
//
// Created by Ahmed Abdurrahman on 9/16/15.
// Copyright © 2015 A. Abdurrahman. All rights reserved.
//
import UIKit
class TabySegmentedControl: UISegmentedControl {
// func drawRect(){
// super.drawRect()
// initUI()
// }
func initUI(){
setupBackground()
setupFonts()
}
func setupBackground(){
let backgroundImage = UIImage(named: "segmented_unselected_bg")
let dividerImage = UIImage(named: "segmented_separator_bg")
let backgroundImageSelected = UIImage(named: "segmented_selected_bg")
self.setBackgroundImage(backgroundImage, for: UIControlState(), barMetrics: .default)
self.setBackgroundImage(backgroundImageSelected, for: .highlighted, barMetrics: .default)
self.setBackgroundImage(backgroundImageSelected, for: .selected, barMetrics: .default)
self.setDividerImage(dividerImage, forLeftSegmentState: UIControlState(), rightSegmentState: .selected, barMetrics: .default)
self.setDividerImage(dividerImage, forLeftSegmentState: .selected, rightSegmentState: UIControlState(), barMetrics: .default)
self.setDividerImage(dividerImage, forLeftSegmentState: UIControlState(), rightSegmentState: UIControlState(), barMetrics: .default)
}
func setupFonts(){
let font = UIFont.systemFont(ofSize: 16.0)
let normalTextAttributes = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: font
]
self.setTitleTextAttributes(normalTextAttributes, for: UIControlState())
self.setTitleTextAttributes(normalTextAttributes, for: .highlighted)
self.setTitleTextAttributes(normalTextAttributes, for: .selected)
}
}
| efa6ba5dd8f55e586f0abaccbcae67d3 | 35.607843 | 140 | 0.686127 | false | false | false | false |
hgl888/firefox-ios | refs/heads/autocomplete-highlight | Sync/Synchronizers/LoginsSynchronizer.swift | mpl-2.0 | 8 | /* 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 Storage
import XCGLogger
private let log = Logger.syncLogger
let PasswordsStorageVersion = 1
private func makeDeletedLoginRecord(guid: GUID) -> Record<LoginPayload> {
// Local modified time is ignored in upload serialization.
let modified: Timestamp = 0
// Arbitrary large number: deletions sync down first.
let sortindex = 5_000_000
let json: JSON = JSON([
"id": guid,
"deleted": true,
])
let payload = LoginPayload(json)
return Record<LoginPayload>(id: guid, payload: payload, modified: modified, sortindex: sortindex)
}
func makeLoginRecord(login: Login) -> Record<LoginPayload> {
let id = login.guid
let modified: Timestamp = 0 // Ignored in upload serialization.
let sortindex = 1
let tLU = NSNumber(unsignedLongLong: login.timeLastUsed / 1000)
let tPC = NSNumber(unsignedLongLong: login.timePasswordChanged / 1000)
let tC = NSNumber(unsignedLongLong: login.timeCreated / 1000)
let dict: [String: AnyObject] = [
"id": id,
"hostname": login.hostname,
"httpRealm": login.httpRealm ?? JSON.null,
"formSubmitURL": login.formSubmitURL ?? JSON.null,
"username": login.username ?? "",
"password": login.password,
"usernameField": login.usernameField ?? "",
"passwordField": login.passwordField ?? "",
"timesUsed": login.timesUsed,
"timeLastUsed": tLU,
"timePasswordChanged": tPC,
"timeCreated": tC,
]
let payload = LoginPayload(JSON(dict))
return Record<LoginPayload>(id: id, payload: payload, modified: modified, sortindex: sortindex)
}
/**
* Our current local terminology ("logins") has diverged from the terminology in
* use when Sync was built ("passwords"). I've done my best to draw a reasonable line
* between the server collection/record format/etc. and local stuff: local storage
* works with logins, server records and collection are passwords.
*/
public class LoginsSynchronizer: IndependentRecordSynchronizer, Synchronizer {
public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) {
super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "passwords")
}
override var storageVersion: Int {
return PasswordsStorageVersion
}
func getLogin(record: Record<LoginPayload>) -> ServerLogin {
let guid = record.id
let payload = record.payload
let modified = record.modified
let login = ServerLogin(guid: guid, hostname: payload.hostname, username: payload.username, password: payload.password, modified: modified)
login.formSubmitURL = payload.formSubmitURL
login.httpRealm = payload.httpRealm
login.usernameField = payload.usernameField
login.passwordField = payload.passwordField
// Microseconds locally, milliseconds remotely. We should clean this up.
login.timeCreated = 1000 * (payload.timeCreated ?? 0)
login.timeLastUsed = 1000 * (payload.timeLastUsed ?? 0)
login.timePasswordChanged = 1000 * (payload.timePasswordChanged ?? 0)
login.timesUsed = payload.timesUsed ?? 0
return login
}
func applyIncomingToStorage(storage: SyncableLogins, records: [Record<LoginPayload>], fetched: Timestamp) -> Success {
return self.applyIncomingToStorage(records, fetched: fetched) { rec in
let guid = rec.id
let payload = rec.payload
// We apply deletions immediately. That might not be exactly what we want -- perhaps you changed
// a password locally after deleting it remotely -- but it's expedient.
if payload.deleted {
return storage.deleteByGUID(guid, deletedAt: rec.modified)
}
return storage.applyChangedLogin(self.getLogin(rec))
}
}
private func uploadModifiedLogins(logins: [Login], lastTimestamp: Timestamp, fromStorage storage: SyncableLogins, withServer storageClient: Sync15CollectionClient<LoginPayload>) -> DeferredTimestamp {
return self.uploadRecords(logins.map(makeLoginRecord), by: 50, lastTimestamp: lastTimestamp, storageClient: storageClient, onUpload: { storage.markAsSynchronized($0, modified: $1) })
}
private func uploadDeletedLogins(guids: [GUID], lastTimestamp: Timestamp, fromStorage storage: SyncableLogins, withServer storageClient: Sync15CollectionClient<LoginPayload>) -> DeferredTimestamp {
let records = guids.map(makeDeletedLoginRecord)
// Deletions are smaller, so upload 100 at a time.
return self.uploadRecords(records, by: 100, lastTimestamp: lastTimestamp, storageClient: storageClient, onUpload: { storage.markAsDeleted($0) >>> always($1) })
}
// Find any records for which a local overlay exists. If we want to be really precise,
// we can find the original server modified time for each record and use it as
// If-Unmodified-Since on a PUT, or just use the last fetch timestamp, which should
// be equivalent.
// We will already have reconciled any conflicts on download, so this upload phase should
// be as simple as uploading any changed or deleted items.
private func uploadOutgoingFromStorage(storage: SyncableLogins, lastTimestamp: Timestamp, withServer storageClient: Sync15CollectionClient<LoginPayload>) -> Success {
let uploadDeleted: Timestamp -> DeferredTimestamp = { timestamp in
storage.getDeletedLoginsToUpload()
>>== { guids in
return self.uploadDeletedLogins(guids, lastTimestamp: timestamp, fromStorage: storage, withServer: storageClient)
}
}
let uploadModified: Timestamp -> DeferredTimestamp = { timestamp in
storage.getModifiedLoginsToUpload()
>>== { logins in
return self.uploadModifiedLogins(logins, lastTimestamp: timestamp, fromStorage: storage, withServer: storageClient)
}
}
return deferMaybe(lastTimestamp)
>>== uploadDeleted
>>== uploadModified
>>> effect({ log.debug("Done syncing.") })
>>> succeed
}
public func synchronizeLocalLogins(logins: SyncableLogins, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult {
if let reason = self.reasonToNotSync(storageClient) {
return deferMaybe(.NotStarted(reason))
}
let encoder = RecordEncoder<LoginPayload>(decode: { LoginPayload($0) }, encode: { $0 })
guard let passwordsClient = self.collectionClient(encoder, storageClient: storageClient) else {
log.error("Couldn't make logins factory.")
return deferMaybe(FatalError(message: "Couldn't make logins factory."))
}
let since: Timestamp = self.lastFetched
log.debug("Synchronizing \(self.collection). Last fetched: \(since).")
let applyIncomingToStorage: StorageResponse<[Record<LoginPayload>]> -> Success = { response in
let ts = response.metadata.timestampMilliseconds
let lm = response.metadata.lastModifiedMilliseconds!
log.debug("Applying incoming password records from response timestamped \(ts), last modified \(lm).")
log.debug("Records header hint: \(response.metadata.records)")
return self.applyIncomingToStorage(logins, records: response.value, fetched: lm)
}
return passwordsClient.getSince(since)
>>== applyIncomingToStorage
// TODO: If we fetch sorted by date, we can bump the lastFetched timestamp
// to the last successfully applied record timestamp, no matter where we fail.
// There's no need to do the upload before bumping -- the storage of local changes is stable.
>>> { self.uploadOutgoingFromStorage(logins, lastTimestamp: 0, withServer: passwordsClient) }
>>> { return deferMaybe(.Completed) }
}
}
| 5f84b83bb767d5ed89760a916a46fe16 | 46.251429 | 204 | 0.681703 | false | false | false | false |
alblue/swift | refs/heads/master | test/SILGen/downcast_reabstraction.swift | apache-2.0 | 2 |
// RUN: %target-swift-emit-silgen -module-name downcast_reabstraction -enable-sil-ownership %s | %FileCheck %s
// CHECK-LABEL: sil hidden @$s22downcast_reabstraction19condFunctionFromAnyyyypF
// CHECK: checked_cast_addr_br take_always Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed () -> @out (), [[YES:bb[0-9]+]], [[NO:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: [[ORIG_VAL:%.*]] = load [take] [[OUT]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @$sytIegr_Ieg_TR
// CHECK: [[SUBST_VAL:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[ORIG_VAL]])
func condFunctionFromAny(_ x: Any) {
if let f = x as? () -> () {
f()
}
}
// CHECK-LABEL: sil hidden @$s22downcast_reabstraction21uncondFunctionFromAnyyyypF : $@convention(thin) (@in_guaranteed Any) -> () {
// CHECK: unconditional_checked_cast_addr Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed () -> @out ()
// CHECK: [[ORIG_VAL:%.*]] = load [take] [[OUT]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @$sytIegr_Ieg_TR
// CHECK: [[SUBST_VAL:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[ORIG_VAL]])
// CHECK: [[BORROW:%.*]] = begin_borrow [[SUBST_VAL]]
// CHECK: apply [[BORROW]]()
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value [[SUBST_VAL]]
func uncondFunctionFromAny(_ x: Any) {
(x as! () -> ())()
}
| 66349cc1e144579763b1ac9b8fe020e9 | 50.857143 | 175 | 0.557163 | false | false | false | false |
amraboelela/swift | refs/heads/master | test/IRGen/objc_properties_jit.swift | apache-2.0 | 12 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop %s -emit-ir -disable-objc-attr-requires-foundation-module -use-jit | %FileCheck %s
import Foundation
extension NSString {
@objc class var classProp: Int {
get { fatalError() }
set { fatalError() }
}
@objc var instanceProp: Int {
get { fatalError() }
set { fatalError() }
}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} private void @runtime_registration
// CHECK: [[NSOBJECT_UNINIT:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_NSString"
// CHECK: [[NSOBJECT:%.*]] = call %objc_class* @swift_getInitializedObjCClass(%objc_class* [[NSOBJECT_UNINIT]])
// CHECK: [[GET_CLASS_PROP:%.*]] = call i8* @sel_registerName({{.*}}(classProp)
// CHECK: call i8* @class_replaceMethod(%objc_class* @"OBJC_METACLASS_$_NSString", i8* [[GET_CLASS_PROP]]
// CHECK: [[SET_CLASS_PROP:%.*]] = call i8* @sel_registerName({{.*}}(setClassProp:)
// CHECK: call i8* @class_replaceMethod(%objc_class* @"OBJC_METACLASS_$_NSString", i8* [[SET_CLASS_PROP]]
// CHECK: [[GET_INSTANCE_PROP:%.*]] = call i8* @sel_registerName({{.*}}(instanceProp)
// CHECK: call i8* @class_replaceMethod(%objc_class* [[NSOBJECT]], i8* [[GET_INSTANCE_PROP]]
// CHECK: [[SET_INSTANCE_PROP:%.*]] = call i8* @sel_registerName({{.*}}(setInstanceProp:)
// CHECK: call i8* @class_replaceMethod(%objc_class* [[NSOBJECT]], i8* [[SET_INSTANCE_PROP]]
| 05ac20923483a82d4596975924f8ba74 | 56.884615 | 165 | 0.621262 | false | false | false | false |
wilmarvh/Bounce | refs/heads/master | Hooops/Home/HomeViewListLayout.swift | mit | 1 | import UIKit
class HomeViewListLayout: UICollectionViewFlowLayout {
static let height: CGFloat = 250
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override init() {
super.init()
configure()
}
func configure() {
scrollDirection = .vertical
sectionInset = UIEdgeInsetsMake(15, 15, 15, 15)
minimumInteritemSpacing = 0
minimumLineSpacing = 25
}
func itemWidth() -> CGFloat {
return collectionView!.frame.width - sectionInset.left - sectionInset.right - minimumInteritemSpacing
}
override var itemSize: CGSize {
get {
return CGSize(width: itemWidth(), height: HomeViewListLayout.height)
}
set {
self.itemSize = newValue
}
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return collectionView!.contentOffset
}
}
| 286f1fcef45cdd8768fc6593b63ca654 | 24.65 | 109 | 0.614035 | false | true | false | false |
Fenrikur/ef-app_ios | refs/heads/master | Domain Model/EurofurenceModelTests/Deletions/DealersRemoveAllBeforeInsertTests.swift | mit | 2 | import EurofurenceModel
import XCTest
class DealersRemoveAllBeforeInsertTests: XCTestCase {
func testShouldRemoveAllDealersWhenToldTo() {
let originalResponse = ModelCharacteristics.randomWithoutDeletions
var subsequentResponse = originalResponse
subsequentResponse.dealers.removeAllBeforeInsert = true
let context = EurofurenceSessionTestBuilder().build()
context.performSuccessfulSync(response: originalResponse)
context.performSuccessfulSync(response: subsequentResponse)
let index = context.dealersService.makeDealersIndex()
let delegate = CapturingDealersIndexDelegate()
index.setDelegate(delegate)
AlphabetisedDealersGroupAssertion(groups: delegate.capturedAlphabetisedDealerGroups,
fromDealerCharacteristics: subsequentResponse.dealers.changed).assertGroups()
}
}
| c9682944763f0066b67697f09b60ec1e | 42.095238 | 119 | 0.748066 | false | true | false | false |
xixijiushui/douyu | refs/heads/master | douyu1/douyu/Classes/Main/Controller/BaseAnchorViewController.swift | mit | 1 | //
// BaseAnchorViewController.swift
// douyu
//
// Created by 赵伟 on 2016/11/9.
// Copyright © 2016年 赵伟. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kHeaderViewH : CGFloat = 50
let kItemW : CGFloat = (kScreenW - 3 * kItemMargin) / 2
let kNormalItemH : CGFloat = kItemW * 3 / 4
let kPrettyItemH : CGFloat = kItemW * 4 / 3
private let kCycleViewH = kScreenW * 3 / 8
private let kGameViewH : CGFloat = 90
private let kNormalCellID : String = "kNormalCellID"
private let kHeadViewID : String = "kHeadViewID"
let kPrettyCellID : String = "kPrettyCellID"
class BaseAnchorViewController: UIViewController {
//MARK:- 定义属性
var baseVM : BaseViewModel!
lazy var collectionView : UICollectionView = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSizeMake(kItemW, kNormalItemH)
layout.headerReferenceSize = CGSizeMake(kScreenW, kHeaderViewH)
layout.minimumInteritemSpacing = kItemMargin
layout.minimumLineSpacing = 0
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin)
let collectionview : UICollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionview.backgroundColor = UIColor.whiteColor()
collectionview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
collectionview.dataSource = self
collectionview.delegate = self
collectionview.registerNib(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionview.registerNib(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionview.registerNib(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeadViewID)
return collectionview
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
extension BaseAnchorViewController {
func setupUI() {
view.addSubview(collectionView)
}
func loadData() {
}
}
extension BaseAnchorViewController : UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return baseVM.anchorGroups.count
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return baseVM.anchorGroups[section].anchors.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kNormalCellID, forIndexPath: indexPath) as! CollectionNormalCell
cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let headView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: kHeadViewID, forIndexPath: indexPath) as! CollectionHeaderView
headView.group = baseVM.anchorGroups[indexPath.section]
return headView
}
}
extension BaseAnchorViewController : UICollectionViewDelegate {
}
| 30d47743bf70109721f15e5a632e1f31 | 37.054348 | 187 | 0.735219 | false | false | false | false |
researchpanelasia/sop-ios-sdk | refs/heads/master | SurveyonPartnersTests/AuthenticationTests.swift | mit | 1 | //
// AuthenticationTests.swift
// SurveyonPartners
//
// Copyright © 2017年 d8aspring. All rights reserved.
//
import XCTest
@testable import SurveyonPartners
class AuthenticationTests: XCTestCase {
func testCreateSignatureString() {
let obj = Authentication()
XCTAssert(obj.createSignature(message: "aaa=aaa&bbb=bbb&ccc=ccc", key: "hogehoge") == "2fbfe87e54cc53036463633ef29beeaa4d740e435af586798917826d9e525112")
}
func testCreateSignatureDictionary1() {
let obj = Authentication()
let populationDict: Dictionary<String,String> = [
"ccc": "ccc",
"aaa": "aaa",
"bbb": "bbb",
]
XCTAssert(obj.createSignature(parameters: populationDict, key: "hogehoge") == "2fbfe87e54cc53036463633ef29beeaa4d740e435af586798917826d9e525112")
}
func testCreateSignatureDictionary2() {
let obj = Authentication()
let populationDict: Dictionary<String,String> = [
"ccc": "ccc",
"aaa": "aaa",
"bbb": "bbb",
"sop_hoge": "hoge"
]
XCTAssert(obj.createSignature(parameters: populationDict, key: "hogehoge") == "2fbfe87e54cc53036463633ef29beeaa4d740e435af586798917826d9e525112")
}
}
| fea3344292aef6aa4807e14649f75239 | 28.45 | 157 | 0.693548 | false | true | false | false |
stendahls/AsyncTask | refs/heads/master | Tests/Helper.swift | mit | 1 | //
// Helper.swift
// AsyncTask
//
// Created by Zhixuan Lai on 6/10/16.
//
// 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 Collection {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffle()
return list
}
}
extension MutableCollection where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in startIndex ..< endIndex - 1 {
let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i
if i != j {
swap(&self[i], &self[j])
}
}
}
}
// Helpers
extension Double {
static var random: Double {
get {
return Double(arc4random()) / 0xFFFFFFFF
}
}
static func random(min: Double, max: Double) -> Double {
return Double.random * (max - min) + min
}
}
| 1cc670a8f3e35f51aed91ca840ba44ba | 31.106061 | 81 | 0.65361 | false | false | false | false |
dalu93/SwiftHelpSet | refs/heads/master | Sources/UIKIt/BasicAnimation.swift | mit | 1 | //
// BasicAnimation.swift
// SwiftHelpSet
//
// Created by Luca D'Alberti on 7/15/16.
// Copyright © 2016 dalu93. All rights reserved.
//
import Foundation
import UIKit
/**
It describes all the available axes
- x: The X axis
- y: The Y axis
- z: The Z axis
*/
public enum Axis: String {
case x
case y
case z
}
/// This wrapper allows you to handle easily the CABasicAnimation using closures
public class BasicAnimation: NSObject {
fileprivate var _onStop: ((_ finished: Bool) -> ())?
/// Called when the animation finishes
public func onStop(closure: @escaping ((_ finished: Bool) -> ())) -> Self {
_onStop = closure
return self
}
fileprivate var _onStart: VoidClosure?
/// Called when the animation starts
public func onStart(closure: @escaping VoidClosure) -> Self {
_onStart = closure
return self
}
fileprivate let animation: CABasicAnimation
fileprivate weak var layer: CALayer?
/**
Creates a new instance of `BasicAnimation` starting from a `CABasicAnimation` instance.
It's recomended to use the static initializers
- parameter animation: CABasicAnimation instance
- returns: New `BasicAnimation` instance
*/
public init(animation: CABasicAnimation) {
self.animation = animation
super.init()
self.animation.delegate = self
}
/**
Add and starts the animation on the layer
- parameter layer: Layer on which add the animation
- returns: `BasicAnimation` instance
*/
public func add(to layer: CALayer) -> Self {
self.layer = layer
layer.add(animation, forKey: animation.keyPath)
return self
}
/**
Stops and removes the animation from the layer
- returns: `BasicAnimation` instance
*/
public func remove() -> Self {
guard
let layer = layer,
let keyPath = animation.keyPath else { return self }
layer.removeAnimation(forKey: keyPath)
return self
}
deinit {
_ = remove()
}
}
public func ==(lhs: BasicAnimation, rhs: BasicAnimation) -> Bool {
return lhs.animation == rhs.animation && lhs.layer == rhs.layer
}
// MARK: - Static initializers
public extension BasicAnimation {
/**
Creates a new instance of `BasicAnimation` that allows you to create a
simple rotation animation
- parameter axis: The axis on which rotate
- parameter repeatCount: The repeat count
- parameter duration: The animation duration
- returns: `BasicAnimation` instance
*/
static public func rotationAnimation(on axis: Axis = .z, repeatCount: Float = HUGE, duration: CFTimeInterval = 1.0) -> BasicAnimation {
let animation = CABasicAnimation(keyPath: "transform.rotation.\(axis.rawValue)")
animation.toValue = NSNumber(value: M_PI * 2)
animation.duration = duration
animation.repeatCount = repeatCount
return BasicAnimation(animation: animation)
}
}
// MARK: - CAAnimationDelegate
extension BasicAnimation: CAAnimationDelegate {
public func animationDidStart(_ anim: CAAnimation) {
_onStart?()
}
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
_onStop?(flag)
}
}
| 2b26c3f12003b6f21a06789380871081 | 24.873134 | 139 | 0.62071 | false | false | false | false |
vmanot/swift-package-manager | refs/heads/master | Sources/Commands/Destination.swift | apache-2.0 | 1 | import Basic
import Utility
import POSIX
enum DestinationError: Swift.Error {
/// Couldn't find the Xcode installation.
case invalidInstallation(String)
/// The schema version is invalid.
case invalidSchemaVersion
}
extension DestinationError: CustomStringConvertible {
var description: String {
switch self {
case .invalidSchemaVersion:
return "unsupported destination file schema version"
case .invalidInstallation(let problem):
return problem
}
}
}
/// The compilation destination, has information about everything that's required for a certain destination.
public struct Destination {
/// The clang/LLVM triple describing the target OS and architecture.
///
/// The triple has the general format <arch><sub>-<vendor>-<sys>-<abi>, where:
/// - arch = x86_64, i386, arm, thumb, mips, etc.
/// - sub = for ex. on ARM: v5, v6m, v7a, v7m, etc.
/// - vendor = pc, apple, nvidia, ibm, etc.
/// - sys = none, linux, win32, darwin, cuda, etc.
/// - abi = eabi, gnu, android, macho, elf, etc.
///
/// for more information see //https://clang.llvm.org/docs/CrossCompilation.html
public let target: String
/// The SDK used to compile for the destination.
public let sdk: AbsolutePath
/// The binDir in the containing the compilers/linker to be used for the compilation.
public let binDir: AbsolutePath
/// The file extension for dynamic libraries (eg. `.so` or `.dylib`)
public let dynamicLibraryExtension: String
/// Additional flags to be passed to the C compiler.
public let extraCCFlags: [String]
/// Additional flags to be passed to the Swift compiler.
public let extraSwiftCFlags: [String]
/// Additional flags to be passed when compiling with C++.
public let extraCPPFlags: [String]
/// Returns the bin directory for the host.
///
/// - Parameter originalWorkingDirectory: The working directory when the program was launched.
private static func hostBinDir(
originalWorkingDirectory: AbsolutePath = currentWorkingDirectory
) -> AbsolutePath {
#if Xcode
// For Xcode, set bin directory to the build directory containing the fake
// toolchain created during bootstraping. This is obviously not production ready
// and only exists as a development utility right now.
//
// This also means that we should have bootstrapped with the same Swift toolchain
// we're using inside Xcode otherwise we will not be able to load the runtime libraries.
//
// FIXME: We may want to allow overriding this using an env variable but that
// doesn't seem urgent or extremely useful as of now.
return AbsolutePath(#file).parentDirectory
.parentDirectory.parentDirectory.appending(components: ".build", hostTargetTriple, "debug")
#else
return AbsolutePath(
CommandLine.arguments[0], relativeTo: originalWorkingDirectory).parentDirectory
#endif
}
/// The destination describing the host OS.
public static func hostDestination(
_ binDir: AbsolutePath? = nil,
originalWorkingDirectory: AbsolutePath = currentWorkingDirectory
) throws -> Destination {
// Select the correct binDir.
let binDir = binDir ?? Destination.hostBinDir(
originalWorkingDirectory: originalWorkingDirectory)
#if os(macOS)
// Get the SDK.
let sdkPath: AbsolutePath
if let value = lookupExecutablePath(filename: getenv("SYSROOT")) {
sdkPath = value
} else {
// No value in env, so search for it.
let sdkPathStr = try Process.checkNonZeroExit(
args: "xcrun", "--sdk", "macosx", "--show-sdk-path").chomp()
guard !sdkPathStr.isEmpty else {
throw DestinationError.invalidInstallation("default SDK not found")
}
sdkPath = AbsolutePath(sdkPathStr)
}
// Compute common arguments for clang and swift.
// This is currently just frameworks path.
let commonArgs = Destination.sdkPlatformFrameworkPath().map({ ["-F", $0.asString] }) ?? []
return Destination(
target: hostTargetTriple,
sdk: sdkPath,
binDir: binDir,
dynamicLibraryExtension: "dylib",
extraCCFlags: ["-arch", "x86_64", "-mmacosx-version-min=10.10"] + commonArgs,
extraSwiftCFlags: commonArgs,
extraCPPFlags: ["-lc++"]
)
#else
return Destination(
target: hostTargetTriple,
sdk: .root,
binDir: binDir,
dynamicLibraryExtension: "so",
extraCCFlags: ["-fPIC"],
extraSwiftCFlags: [],
extraCPPFlags: ["-lstdc++"]
)
#endif
}
/// Returns macosx sdk platform framework path.
public static func sdkPlatformFrameworkPath() -> AbsolutePath? {
if let path = _sdkPlatformFrameworkPath {
return path
}
let platformPath = try? Process.checkNonZeroExit(
args: "xcrun", "--sdk", "macosx", "--show-sdk-platform-path").chomp()
if let platformPath = platformPath, !platformPath.isEmpty {
_sdkPlatformFrameworkPath = AbsolutePath(platformPath).appending(
components: "Developer", "Library", "Frameworks")
}
return _sdkPlatformFrameworkPath
}
/// Cache storage for sdk platform path.
private static var _sdkPlatformFrameworkPath: AbsolutePath? = nil
#if os(macOS)
/// Returns the host's dynamic library extension.
public static let hostDynamicLibraryExtension = "dylib"
/// Target triple for the host system.
private static let hostTargetTriple = "x86_64-apple-macosx10.10"
#else
/// Returns the host's dynamic library extension.
public static let hostDynamicLibraryExtension = "so"
/// Target triple for the host system.
private static let hostTargetTriple = "x86_64-unknown-linux"
#endif
}
public extension Destination {
/// Load a Destination description from a JSON representation from disk.
public init(fromFile path: AbsolutePath, fileSystem: FileSystem = localFileSystem) throws {
let json = try JSON(bytes: fileSystem.readFileContents(path))
try self.init(json: json)
}
}
extension Destination: JSONMappable {
/// The current schema version.
static let schemaVersion = 1
public init(json: JSON) throws {
// Check schema version.
guard try json.get("version") == Destination.schemaVersion else {
throw DestinationError.invalidSchemaVersion
}
try self.init(
target: json.get("target"),
sdk: AbsolutePath(json.get("sdk")),
binDir: AbsolutePath(json.get("toolchain-bin-dir")),
dynamicLibraryExtension: json.get("dynamic-library-extension"),
extraCCFlags: json.get("extra-cc-flags"),
extraSwiftCFlags: json.get("extra-swiftc-flags"),
extraCPPFlags: json.get("extra-cpp-flags")
)
}
}
| 6e64570e0a57b0497f8f86e7de1ecf4d | 36.154639 | 108 | 0.641509 | false | false | false | false |
congncif/IDMCore | refs/heads/master | IDMCore/Classes/DedicatedErrorHandling.swift | mit | 1 | //
// DedicatedErrorHandling.swift
// IDMCore
//
// Created by NGUYEN CHI CONG on 3/21/19.
//
import Foundation
public protocol DedicatedErrorHandlingProtocol {
associatedtype ErrorType
func handleDedicatedError(_ error: ErrorType)
}
extension ErrorHandlingProtocol where Self: DedicatedErrorHandlingProtocol {
public func handle(error: Error) {
guard let dedicatedError = error as? ErrorType else { return }
handleDedicatedError(dedicatedError)
}
}
public struct DedicatedErrorHandler<E>: DedicatedErrorHandlingProtocol, ErrorHandlingProtocol {
public typealias ErrorType = E
public typealias Handler = (ErrorType) -> Void
private var handler: Handler
public init(errorType: ErrorType.Type, handler: @escaping Handler) {
self.handler = handler
}
public init(handler: @escaping Handler) {
self.handler = handler
}
public func handleDedicatedError(_ error: ErrorType) {
handler(error)
}
}
| 962376a0c2d0e73dc0e31d2bb89d6bd6 | 24.410256 | 95 | 0.71443 | false | false | false | false |
lxx2014/LXXZB | refs/heads/master | LXXZB/LXXZB/Classes/Tools/Extension/UIBarButtonItem-Extension.swift | mit | 1 | //
// UIBarButtonItem-Extension.swift
// LXXZB
//
// Created by lixiaoxin on 2016/10/18.
// Copyright © 2016年 lixiaoxin. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
convenience init(imageName : String, highImageName : String = "", size : CGSize = CGSize.zero) {
// 1.创建UIButton
let btn = UIButton()
// 2.设置btn的图片
btn.setImage(UIImage(named:imageName), for: UIControlState())
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), for: .highlighted)
}
// 3.设置btn的尺寸
if size == CGSize.zero {
btn.sizeToFit()
}else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
// 4.创建UIBarButtonItem
self.init(customView : btn)
}
}
| e5b906111c99f6080e80c4352a4b2d38 | 21.74359 | 100 | 0.533258 | false | false | false | false |
tapz/MWPhotoBrowserSwift | refs/heads/master | Pod/Classes/ZoomingScrollView.swift | mit | 1 | //
// ZoomingScrollView.swift
// Pods
//
// Created by Tapani Saarinen on 06/09/15.
//
//
import UIKit
import DACircularProgress
public class ZoomingScrollView: UIScrollView, UIScrollViewDelegate, TapDetectingImageViewDelegate, TapDetectingViewDelegate {
public var index = 0
public var mwPhoto: Photo?
public weak var captionView: CaptionView?
public weak var selectedButton: UIButton?
public weak var playButton: UIButton?
private weak var photoBrowser: PhotoBrowser!
private var tapView = TapDetectingView(frame: CGRectZero) // for background taps
private var photoImageView = TapDetectingImageView(frame: CGRectZero)
private var loadingIndicator = DACircularProgressView(frame: CGRectMake(140.0, 30.0, 40.0, 40.0))
private var loadingError: UIImageView?
public init(photoBrowser: PhotoBrowser) {
super.init(frame: CGRectZero)
// Setup
index = Int.max
self.photoBrowser = photoBrowser
// Tap view for background
tapView = TapDetectingView(frame: bounds)
tapView.tapDelegate = self
tapView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
tapView.backgroundColor = UIColor.whiteColor()
addSubview(tapView)
// Image view
photoImageView.tapDelegate = self
photoImageView.contentMode = UIViewContentMode.Center
addSubview(photoImageView)
// Loading indicator
loadingIndicator.userInteractionEnabled = false
loadingIndicator.thicknessRatio = 0.1
loadingIndicator.roundedCorners = 0
loadingIndicator.autoresizingMask =
[.FlexibleLeftMargin, .FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleRightMargin]
addSubview(loadingIndicator)
// Listen progress notifications
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("setProgressFromNotification:"),
name: MWPHOTO_PROGRESS_NOTIFICATION,
object: nil)
// Setup
backgroundColor = UIColor.whiteColor()
delegate = self
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
decelerationRate = UIScrollViewDecelerationRateFast
autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func prepareForReuse() {
hideImageFailure()
photo = nil
captionView = nil
selectedButton = nil
playButton = nil
photoImageView.hidden = false
photoImageView.image = nil
index = Int.max
}
func displayingVideo() -> Bool {
if let p = photo {
return p.isVideo
}
return false
}
public override var backgroundColor: UIColor? {
set(color) {
tapView.backgroundColor = color
super.backgroundColor = color
}
get {
return super.backgroundColor
}
}
var imageHidden: Bool {
set(hidden) {
photoImageView.hidden = hidden
}
get {
return photoImageView.hidden
}
}
//MARK: - Image
var photo: Photo? {
set(p) {
// Cancel any loading on old photo
if mwPhoto != nil && p == nil {
mwPhoto!.cancelAnyLoading()
}
mwPhoto = p
if photoBrowser.imageForPhoto(mwPhoto) != nil {
self.displayImage()
}
else {
// Will be loading so show loading
self.showLoadingIndicator()
}
}
get {
return mwPhoto
}
}
// Get and display image
func displayImage() {
if mwPhoto != nil && photoImageView.image == nil {
// Reset
maximumZoomScale = 1.0
minimumZoomScale = 1.0
zoomScale = 1.0
contentSize = CGSizeMake(0.0, 0.0)
// Get image from browser as it handles ordering of fetching
if let img = photoBrowser.imageForPhoto(photo) {
// Hide indicator
hideLoadingIndicator()
// Set image
photoImageView.image = img
photoImageView.hidden = false
// Setup photo frame
var photoImageViewFrame = CGRectZero
photoImageViewFrame.origin = CGPointZero
photoImageViewFrame.size = img.size
photoImageView.frame = photoImageViewFrame
contentSize = photoImageViewFrame.size
// Set zoom to minimum zoom
setMaxMinZoomScalesForCurrentBounds()
}
else {
// Show image failure
displayImageFailure()
}
setNeedsLayout()
}
}
// Image failed so just show grey!
func displayImageFailure() {
hideLoadingIndicator()
photoImageView.image = nil
// Show if image is not empty
if let p = photo {
if p.emptyImage {
if nil == loadingError {
loadingError = UIImageView()
loadingError!.image = UIImage.imageForResourcePath(
"MWPhotoBrowserSwift.bundle/ImageError",
ofType: "png",
inBundle: NSBundle(forClass: ZoomingScrollView.self))
loadingError!.userInteractionEnabled = false
loadingError!.autoresizingMask =
[.FlexibleLeftMargin, .FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleRightMargin]
loadingError!.sizeToFit()
addSubview(loadingError!)
}
loadingError!.frame = CGRectMake(
floorcgf((bounds.size.width - loadingError!.frame.size.width) / 2.0),
floorcgf((bounds.size.height - loadingError!.frame.size.height) / 2.0),
loadingError!.frame.size.width,
loadingError!.frame.size.height)
}
}
}
private func hideImageFailure() {
if let e = loadingError {
e.removeFromSuperview()
loadingError = nil
}
}
//MARK: - Loading Progress
public func setProgressFromNotification(notification: NSNotification) {
dispatch_async(dispatch_get_main_queue()) {
let dict = notification.object as! [String : AnyObject]
if let photoWithProgress = dict["photo"] as? Photo,
p = self.photo where photoWithProgress.equals(p)
{
if let progress = dict["progress"] as? Float {
self.loadingIndicator.progress = CGFloat(max(min(1.0, progress), 0.0))
}
}
}
}
private func hideLoadingIndicator() {
loadingIndicator.hidden = true
}
private func showLoadingIndicator() {
zoomScale = 0.1
minimumZoomScale = 0.1
maximumZoomScale = 0.1
loadingIndicator.progress = 0.0
loadingIndicator.hidden = false
hideImageFailure()
}
//MARK: - Setup
private func initialZoomScaleWithMinScale() -> CGFloat {
var zoomScale = minimumZoomScale
if let pb = photoBrowser where pb.zoomPhotosToFill {
// Zoom image to fill if the aspect ratios are fairly similar
let boundsSize = self.bounds.size
let imageSize = photoImageView.image != nil ? photoImageView.image!.size : CGSizeMake(0.0, 0.0)
let boundsAR = boundsSize.width / boundsSize.height
let imageAR = imageSize.width / imageSize.height
let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise
let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise
// Zooms standard portrait images on a 3.5in screen but not on a 4in screen.
if (abs(boundsAR - imageAR) < 0.17) {
zoomScale = max(xScale, yScale)
// Ensure we don't zoom in or out too far, just in case
zoomScale = min(max(minimumZoomScale, zoomScale), maximumZoomScale)
}
}
return zoomScale
}
func setMaxMinZoomScalesForCurrentBounds() {
// Reset
maximumZoomScale = 1.0
minimumZoomScale = 1.0
zoomScale = 1.0
// Bail if no image
if photoImageView.image == nil {
return
}
// Reset position
photoImageView.frame = CGRectMake(0, 0, photoImageView.frame.size.width, photoImageView.frame.size.height)
// Sizes
let boundsSize = self.bounds.size
let imageSize = photoImageView.image!.size
// Calculate Min
let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise
let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise
var minScale = min(xScale, yScale) // use minimum of these to allow the image to become fully visible
// Calculate Max
var maxScale = 3.0
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad {
// Let them go a bit bigger on a bigger screen!
maxScale = 4.0
}
// Image is smaller than screen so no zooming!
if xScale >= 1.0 && yScale >= 1.0 {
minScale = 1.0
}
// Set min/max zoom
maximumZoomScale = CGFloat(maxScale)
minimumZoomScale = CGFloat(minScale)
// Initial zoom
zoomScale = initialZoomScaleWithMinScale()
// If we're zooming to fill then centralise
if zoomScale != minScale {
// Centralise
contentOffset = CGPointMake((imageSize.width * zoomScale - boundsSize.width) / 2.0,
(imageSize.height * zoomScale - boundsSize.height) / 2.0)
}
// Disable scrolling initially until the first pinch to fix issues with swiping on an initally zoomed in photo
scrollEnabled = false
// If it's a video then disable zooming
if displayingVideo() {
maximumZoomScale = zoomScale
minimumZoomScale = zoomScale
}
// Layout
setNeedsLayout()
}
//MARK: - Layout
public override func layoutSubviews() {
// Update tap view frame
tapView.frame = bounds
// Position indicators (centre does not seem to work!)
if !loadingIndicator.hidden {
loadingIndicator.frame = CGRectMake(
floorcgf((bounds.size.width - loadingIndicator.frame.size.width) / 2.0),
floorcgf((bounds.size.height - loadingIndicator.frame.size.height) / 2.0),
loadingIndicator.frame.size.width,
loadingIndicator.frame.size.height)
}
if let le = loadingError {
le.frame = CGRectMake(
floorcgf((bounds.size.width - le.frame.size.width) / 2.0),
floorcgf((bounds.size.height - le.frame.size.height) / 2.0),
le.frame.size.width,
le.frame.size.height)
}
// Super
super.layoutSubviews()
// Center the image as it becomes smaller than the size of the screen
let boundsSize = bounds.size
var frameToCenter = photoImageView.frame
// Horizontally
if frameToCenter.size.width < boundsSize.width {
frameToCenter.origin.x = floorcgf((boundsSize.width - frameToCenter.size.width) / 2.0)
}
else {
frameToCenter.origin.x = 0.0
}
// Vertically
if frameToCenter.size.height < boundsSize.height {
frameToCenter.origin.y = floorcgf((boundsSize.height - frameToCenter.size.height) / 2.0)
}
else {
frameToCenter.origin.y = 0.0
}
// Center
if !CGRectEqualToRect(photoImageView.frame, frameToCenter) {
photoImageView.frame = frameToCenter
}
}
//MARK: - UIScrollViewDelegate
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return photoImageView
}
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
photoBrowser.cancelControlHiding()
}
public func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) {
scrollEnabled = true // reset
photoBrowser.cancelControlHiding()
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
photoBrowser.hideControlsAfterDelay()
}
public func scrollViewDidZoom(scrollView: UIScrollView) {
setNeedsLayout()
layoutIfNeeded()
}
//MARK: - Tap Detection
private func handleSingleTap(touchPoint: CGPoint) {
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC))),
dispatch_get_main_queue())
{
self.photoBrowser.toggleControls()
}
}
private func handleDoubleTap(touchPoint: CGPoint) {
// Dont double tap to zoom if showing a video
if displayingVideo() {
return
}
// Cancel any single tap handling
NSObject.cancelPreviousPerformRequestsWithTarget(photoBrowser)
// Zoom
if zoomScale != minimumZoomScale && zoomScale != initialZoomScaleWithMinScale() {
// Zoom out
setZoomScale(minimumZoomScale, animated: true)
}
else {
// Zoom in to twice the size
let newZoomScale = ((maximumZoomScale + minimumZoomScale) / 2.0)
let xsize = bounds.size.width / newZoomScale
let ysize = bounds.size.height / newZoomScale
zoomToRect(CGRectMake(touchPoint.x - xsize / 2.0, touchPoint.y - ysize / 2.0, xsize, ysize), animated: true)
}
// Delay controls
photoBrowser.hideControlsAfterDelay()
}
// Image View
public func singleTapDetectedInImageView(view: UIImageView, touch: UITouch) {
handleSingleTap(touch.locationInView(view))
}
public func doubleTapDetectedInImageView(view: UIImageView, touch: UITouch) {
handleDoubleTap(touch.locationInView(view))
}
public func tripleTapDetectedInImageView(view: UIImageView, touch: UITouch) {
}
// Background View
public func singleTapDetectedInView(view: UIView, touch: UITouch) {
// Translate touch location to image view location
var touchX = touch.locationInView(view).x
var touchY = touch.locationInView(view).y
touchX *= 1.0 / self.zoomScale
touchY *= 1.0 / self.zoomScale
touchX += self.contentOffset.x
touchY += self.contentOffset.y
handleSingleTap(CGPointMake(touchX, touchY))
}
public func doubleTapDetectedInView(view: UIView, touch: UITouch) {
// Translate touch location to image view location
var touchX = touch.locationInView(view).x
var touchY = touch.locationInView(view).y
touchX *= 1.0 / self.zoomScale
touchY *= 1.0 / self.zoomScale
touchX += self.contentOffset.x
touchY += self.contentOffset.y
handleDoubleTap(CGPointMake(touchX, touchY))
}
public func tripleTapDetectedInView(view: UIView, touch: UITouch) {
}
}
| 8192b55fb90003b524d712d864030fe5 | 32.519507 | 125 | 0.580005 | false | false | false | false |
ArnavChawla/InteliChat | refs/heads/master | Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/NluEnrichmentEmotion.swift | mit | 1 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** An object specifying the emotion detection enrichment and related parameters. */
public struct NluEnrichmentEmotion: Codable {
/// When `true`, emotion detection is performed on the entire field.
public var document: Bool?
/// A comma-separated list of target strings that will have any associated emotions detected.
public var targets: [String]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case document = "document"
case targets = "targets"
}
/**
Initialize a `NluEnrichmentEmotion` with member variables.
- parameter document: When `true`, emotion detection is performed on the entire field.
- parameter targets: A comma-separated list of target strings that will have any associated emotions detected.
- returns: An initialized `NluEnrichmentEmotion`.
*/
public init(document: Bool? = nil, targets: [String]? = nil) {
self.document = document
self.targets = targets
}
}
| 1030e414d966639bad8d30db652c1ead | 34.702128 | 115 | 0.713349 | false | false | false | false |
jduquennoy/Log4swift | refs/heads/master | Log4swiftTests/LoggerFactory+loadFromFileTests.swift | apache-2.0 | 1 | //
// LoggerFactory+loadFromFileTests.swift
// Log4swift
//
// Created by Jérôme Duquennoy on 03/07/2015.
// Copyright © 2015 Jérôme Duquennoy. All rights reserved.
//
// Log4swift is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Log4swift is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Foobar. If not, see <http://www.gnu.org/licenses/>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
@testable import Log4swift
class LoggerFactoryLoadFromFileTests: XCTestCase {
var factory = LoggerFactory()
override func setUp() {
factory = LoggerFactory()
}
// MARK: Formatters tests
func testLoadDictionaryWithNoFormatterClassThrowsError() {
let formattersDictionary = [LoggerFactory.DictionaryKey.Identifier.rawValue: "testIdentifier"]
let dictionary = [LoggerFactory.DictionaryKey.Formatters.rawValue: [formattersDictionary]]
// Execute & validate
XCTAssertThrows { try self.factory.readConfiguration(fromDictionary: dictionary) }
}
func testLoadDictionaryWithUnknownFormatterClassThrowsError() {
let formattersDictionary = [LoggerFactory.DictionaryKey.Identifier.rawValue: "testIdentifier",
LoggerFactory.DictionaryKey.ClassName.rawValue: "UnknownFormatterClass"]
let dictionary = [LoggerFactory.DictionaryKey.Formatters.rawValue: [formattersDictionary]]
// Execute & validate
XCTAssertThrows { try self.factory.readConfiguration(fromDictionary: dictionary) }
}
func testLoadDictionaryWithNoFormatterIdentifierThrowsError() {
let formattersDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "PatternFormatter"]
let dictionary = [LoggerFactory.DictionaryKey.Formatters.rawValue: [formattersDictionary]]
// Execute & validate
XCTAssertThrows { try self.factory.readConfiguration(fromDictionary: dictionary) }
}
func testLoadDictionaryWithEmptyFormatterFormatterIdentifierThrowsError() {
let formattersDictionary = [LoggerFactory.DictionaryKey.Identifier.rawValue: "",
LoggerFactory.DictionaryKey.ClassName.rawValue: "PatternFormatter",
PatternFormatter.DictionaryKey.Pattern.rawValue: "test pattern"]
let dictionary = [LoggerFactory.DictionaryKey.Formatters.rawValue: [formattersDictionary]]
// Execute & validate
XCTAssertThrows { try self.factory.readConfiguration(fromDictionary: dictionary) }
}
func testLoadDictionaryWithPatternFormatterClassCreatesRequestedFormatter() {
let formattersDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "PatternFormatter",
LoggerFactory.DictionaryKey.Identifier.rawValue: "patternIdentifier",
PatternFormatter.DictionaryKey.Pattern.rawValue: "test pattern"]
let dictionary = [LoggerFactory.DictionaryKey.Formatters.rawValue: [formattersDictionary]]
// Execute
let (formatters, _, _) = try! factory.readConfigurationToTupple(fromDictionary: dictionary)
// validate
XCTAssertEqual(formatters.count, 1)
XCTAssertEqual(classNameAsString(formatters[0]), "PatternFormatter")
XCTAssertEqual(formatters[0].identifier, "patternIdentifier")
}
func testLoadDictionaryWithMultipleFormattersCreatesRequestedFormatters() {
let formattersDictionary1 = [LoggerFactory.DictionaryKey.ClassName.rawValue: "PatternFormatter",
LoggerFactory.DictionaryKey.Identifier.rawValue: "test pattern formatter 1",
PatternFormatter.DictionaryKey.Pattern.rawValue: "test pattern"]
let formattersDictionary2 = [LoggerFactory.DictionaryKey.ClassName.rawValue: "PatternFormatter",
LoggerFactory.DictionaryKey.Identifier.rawValue: "test pattern formatter 2",
PatternFormatter.DictionaryKey.Pattern.rawValue: "test pattern"]
let dictionary = [LoggerFactory.DictionaryKey.Formatters.rawValue: [formattersDictionary1, formattersDictionary2]]
// Execute
let (formatters, _, _) = try! factory.readConfigurationToTupple(fromDictionary: dictionary)
// validate
XCTAssertEqual(formatters.count, 2)
XCTAssertEqual(formatters[0].identifier, "test pattern formatter 1")
XCTAssertEqual(formatters[1].identifier, "test pattern formatter 2")
}
// MARK: Appenders tests
func testLoadDictionaryWithNoAppenderClassThrowsError() {
let appenderDictionary = [LoggerFactory.DictionaryKey.Identifier.rawValue: "test pattern formatter 2"]
let dictionary = [LoggerFactory.DictionaryKey.Appenders.rawValue: [appenderDictionary]]
// Execute
XCTAssertThrows { _ = try self.factory.readConfigurationToTupple(fromDictionary: dictionary) }
}
func testLoadDictionaryWithUnknownAppenderClassThrowsError() {
let appenderDictionary = [LoggerFactory.DictionaryKey.Identifier.rawValue: "test appender",
LoggerFactory.DictionaryKey.ClassName.rawValue: "UnknownAppenderClass"]
let dictionary = [LoggerFactory.DictionaryKey.Appenders.rawValue: [appenderDictionary]]
// Execute
XCTAssertThrows { _ = try self.factory.readConfigurationToTupple(fromDictionary: dictionary) }
}
func testLoadDictionaryWithNoAppenderIdentifierThrowsError() {
let appenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender",]
let dictionary = [LoggerFactory.DictionaryKey.Appenders.rawValue: [appenderDictionary]]
// Execute
XCTAssertThrows { _ = try self.factory.readConfigurationToTupple(fromDictionary: dictionary) }
}
func testLoadDictionaryWithEmptyAppenderIdentifierThrowsError() {
let appenderDictionary = [LoggerFactory.DictionaryKey.Identifier.rawValue: "",
LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender"]
let dictionary = [LoggerFactory.DictionaryKey.Appenders.rawValue: [appenderDictionary]]
// Execute
XCTAssertThrows { _ = try self.factory.readConfigurationToTupple(fromDictionary: dictionary) }
}
func testLoadDictionaryWithStdOutAppenderAndFormatCreatesRequestedAppender() {
let formattersDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "PatternFormatter",
LoggerFactory.DictionaryKey.Identifier.rawValue: "patternFormatterId",
PatternFormatter.DictionaryKey.Pattern.rawValue: "test pattern"]
let appenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "test appender",
Appender.DictionaryKey.FormatterId.rawValue: "patternFormatterId"]
let dictionary = [LoggerFactory.DictionaryKey.Formatters.rawValue: [formattersDictionary],
LoggerFactory.DictionaryKey.Appenders.rawValue: [appenderDictionary]]
// Execute
let (formatters, appenders, _) = try! factory.readConfigurationToTupple(fromDictionary: dictionary)
// Validate
XCTAssertEqual(appenders.count, 1)
XCTAssertEqual(formatters.count, 1)
XCTAssertEqual(appenders[0].identifier, "test appender")
XCTAssertEqual(appenders[0].formatter!.identifier, formatters[0].identifier)
}
func testLoadDictionaryWithMultipleAppendersAndFormatCreatesRequestedAppender() {
let formattersDictionary1 = [LoggerFactory.DictionaryKey.ClassName.rawValue: "PatternFormatter",
LoggerFactory.DictionaryKey.Identifier.rawValue: "formatter1",
PatternFormatter.DictionaryKey.Pattern.rawValue: "test pattern"]
let formattersDictionary2 = [LoggerFactory.DictionaryKey.ClassName.rawValue: "PatternFormatter",
LoggerFactory.DictionaryKey.Identifier.rawValue: "formatter2",
PatternFormatter.DictionaryKey.Pattern.rawValue: "test pattern"]
let appenderDictionary1 = [LoggerFactory.DictionaryKey.ClassName.rawValue: "FileAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "appender1",
Appender.DictionaryKey.FormatterId.rawValue: "formatter2",
FileAppender.DictionaryKey.FilePath.rawValue: "/test/path"]
let appenderDictionary2 = [LoggerFactory.DictionaryKey.ClassName.rawValue: "NSLoggerAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "appender2",
Appender.DictionaryKey.FormatterId.rawValue: "formatter1",
NSLoggerAppender.DictionaryKey.RemoteHost.rawValue: "remoteHost"]
let dictionary = [LoggerFactory.DictionaryKey.Formatters.rawValue: [formattersDictionary1, formattersDictionary2],
LoggerFactory.DictionaryKey.Appenders.rawValue: [appenderDictionary1, appenderDictionary2]]
// Execute
let (formatters, appenders, _) = try! factory.readConfigurationToTupple(fromDictionary: dictionary)
// Validate
XCTAssertEqual(appenders.count, 2)
XCTAssertEqual(formatters.count, 2)
XCTAssertEqual(appenders[0].identifier, "appender1")
XCTAssertEqual(appenders[0].formatter!.identifier, "formatter2")
XCTAssertEqual(appenders[1].identifier, "appender2")
XCTAssertEqual(appenders[1].formatter!.identifier, "formatter1")
}
func testAppendersClassesGeneratesCorrectObjects() {
let fileAppenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "FileAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "FileAppender",
FileAppender.DictionaryKey.FilePath.rawValue: "/test/path"]
let nsloggerAppenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "NSLoggerAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "NSLoggerAppender",
NSLoggerAppender.DictionaryKey.RemoteHost.rawValue: "remoteHost"]
let stdoutAppenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "StdOutAppender"]
let nslogAppenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "NSLogAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "NSLogAppender"]
let aslAppenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "ASLAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "ASLAppender"]
let dictionary = [LoggerFactory.DictionaryKey.Appenders.rawValue: [fileAppenderDictionary, nsloggerAppenderDictionary, stdoutAppenderDictionary, nslogAppenderDictionary, aslAppenderDictionary]]
// Execute
let (_, appenders, _) = try! factory.readConfigurationToTupple(fromDictionary: dictionary)
XCTAssertEqual(appenders.count, 5)
for currentAppender in appenders {
XCTAssertEqual(currentAppender.identifier, currentAppender.className.components(separatedBy: ".").last!)
}
}
func testAppendersClassesAreCaseInsensitive() throws {
let fileAppenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "FileAPPender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "FileAppender",
FileAppender.DictionaryKey.FilePath.rawValue: "/test/path"]
let nsloggerAppenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "NSLogGerAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "NSLoggerAppender",
NSLoggerAppender.DictionaryKey.RemoteHost.rawValue: "remoteHost"]
let stdoutAppenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdouTappender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "StdOutAppender"]
let nslogAppenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "NSLogappENder",
LoggerFactory.DictionaryKey.Identifier.rawValue: "NSLogAppender"]
let aslAppenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "ASLAppenDEr",
LoggerFactory.DictionaryKey.Identifier.rawValue: "ASLAppender"]
let dictionary = [LoggerFactory.DictionaryKey.Appenders.rawValue: [fileAppenderDictionary, nsloggerAppenderDictionary, stdoutAppenderDictionary, nslogAppenderDictionary, aslAppenderDictionary]]
// Execute
let (_, appenders, _) = try factory.readConfigurationToTupple(fromDictionary: dictionary)
XCTAssertEqual(appenders.count, 5)
for currentAppender in appenders {
XCTAssertEqual(currentAppender.identifier, currentAppender.className.components(separatedBy: ".").last!)
}
}
// MARK: Logger tests
func testReadConfigurationWithNewLoggerAddsItToLoggersPool() {
let appenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "test appender"]
let loggerDictionary:[String: Any] = [LoggerFactory.DictionaryKey.Identifier.rawValue: "test.logger",
Logger.DictionaryKey.AppenderIds.rawValue: ["test appender"],
Logger.DictionaryKey.ThresholdLevel.rawValue: "info"]
let dictionary:[String: Any] = [LoggerFactory.DictionaryKey.Appenders.rawValue: [appenderDictionary],
LoggerFactory.DictionaryKey.Loggers.rawValue: [loggerDictionary]]
// Execute
try! factory.readConfiguration(fromDictionary: dictionary)
// Validate
let logger = factory.getLogger("test.logger")
XCTAssertEqual(logger.thresholdLevel, LogLevel.Info)
XCTAssertEqual(logger.appenders.count, 1)
if(logger.appenders.count > 0) {
XCTAssertEqual(logger.appenders[0].identifier, "test appender")
}
}
func testReadConfigurationWithExistingLoggerUpdatesIt() {
let appenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "test appender"]
let loggerDictionary:[String: Any] = [LoggerFactory.DictionaryKey.Identifier.rawValue: "test.logger",
Logger.DictionaryKey.AppenderIds.rawValue: ["test appender"],
Logger.DictionaryKey.ThresholdLevel.rawValue: "info"]
let existingLogger = Logger(identifier: "test.logger", level: .Error, appenders: [MemoryAppender("MemoryAppender")])
try! factory.registerLogger(existingLogger)
let dictionary:[String: Any] = [LoggerFactory.DictionaryKey.Appenders.rawValue: [appenderDictionary],
LoggerFactory.DictionaryKey.Loggers.rawValue: [loggerDictionary]]
// Execute
try! factory.readConfiguration(fromDictionary: dictionary)
// Validate
let logger = factory.getLogger("test.logger")
XCTAssertTrue(logger === existingLogger)
XCTAssertEqual(logger.thresholdLevel, LogLevel.Info)
XCTAssertEqual(logger.appenders.count, 1)
if(logger.appenders.count > 0) {
XCTAssertEqual(logger.appenders[0].identifier, "test appender")
}
}
func testLoggerFromConfigurationDictionaryInheritsLevelFromParentIfNotSpecified() {
let appender1Dictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "first appender"]
let appender2Dictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "second appender"]
let logger1Dictionary:[String: Any] = [LoggerFactory.DictionaryKey.Identifier.rawValue: "test.parentLogger",
Logger.DictionaryKey.AppenderIds.rawValue: ["first appender"],
Logger.DictionaryKey.ThresholdLevel.rawValue: "info"]
let logger2Dictionary:[String: Any] = [LoggerFactory.DictionaryKey.Identifier.rawValue: "test.parentLogger.sonLogger",
Logger.DictionaryKey.AppenderIds.rawValue: ["second appender"]]
let dictionary:[String: Any] = [LoggerFactory.DictionaryKey.Appenders.rawValue: [appender1Dictionary, appender2Dictionary],
LoggerFactory.DictionaryKey.Loggers.rawValue: [logger1Dictionary, logger2Dictionary]]
// Execute
try! factory.readConfiguration(fromDictionary: dictionary)
// Validate
let sonLogger = factory.getLogger("test.parentLogger.sonLogger")
XCTAssertNil(sonLogger.parent)
XCTAssertEqual(sonLogger.thresholdLevel, LogLevel.Info)
XCTAssertEqual(sonLogger.appenders.count, 1)
if(sonLogger.appenders.count > 0) {
XCTAssertEqual(sonLogger.appenders[0].identifier, "second appender")
}
}
func testLoggerFromConfigurationDictionaryInheritsAppendersFromParentIfNotSpecified() {
let appender1Dictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "first appender"]
let logger1Dictionary:[String: Any] = [LoggerFactory.DictionaryKey.Identifier.rawValue: "test.parentLogger",
Logger.DictionaryKey.AppenderIds.rawValue: ["first appender"],
Logger.DictionaryKey.ThresholdLevel.rawValue: "info"]
let logger2Dictionary = [LoggerFactory.DictionaryKey.Identifier.rawValue: "test.parentLogger.sonLogger",
Logger.DictionaryKey.ThresholdLevel.rawValue: "warning"]
let dictionary:[String: Any] = [LoggerFactory.DictionaryKey.Appenders.rawValue: [appender1Dictionary],
LoggerFactory.DictionaryKey.Loggers.rawValue: [logger1Dictionary, logger2Dictionary]]
// Execute
try! factory.readConfiguration(fromDictionary: dictionary)
// Validate
let sonLogger = factory.getLogger("test.parentLogger.sonLogger")
XCTAssertNil(sonLogger.parent)
XCTAssertEqual(sonLogger.thresholdLevel, LogLevel.Warning)
XCTAssertEqual(sonLogger.appenders.count, 1)
if(sonLogger.appenders.count > 0) {
XCTAssertEqual(sonLogger.appenders[0].identifier, "first appender")
}
}
func testLoggersInheritFromParentEvenIfOutOfOrder() {
let appender1Dictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "first appender"]
let logger1Dictionary:[String: Any] = [LoggerFactory.DictionaryKey.Identifier.rawValue: "test.parentLogger",
Logger.DictionaryKey.AppenderIds.rawValue: ["first appender"],
Logger.DictionaryKey.ThresholdLevel.rawValue: "info"]
let logger2Dictionary = [LoggerFactory.DictionaryKey.Identifier.rawValue: "test.parentLogger.sonLogger"]
let dictionary:[String: Any] = [LoggerFactory.DictionaryKey.Appenders.rawValue: [appender1Dictionary],
LoggerFactory.DictionaryKey.Loggers.rawValue: [logger2Dictionary, logger1Dictionary]]
// Execute
try! factory.readConfiguration(fromDictionary: dictionary)
// Validate
let sonLogger = factory.getLogger("test.parentLogger.sonLogger")
XCTAssertNil(sonLogger.parent)
XCTAssertEqual(sonLogger.thresholdLevel, LogLevel.Info)
XCTAssertEqual(sonLogger.appenders.count, 1)
if(sonLogger.appenders.count > 0) {
XCTAssertEqual(sonLogger.appenders[0].identifier, "first appender")
}
}
func testLoggerConfiguredAsAsynchronousIsAsynchronous() {
let loggersDictionary = [[
LoggerFactory.DictionaryKey.Identifier.rawValue: "test.asyncLogger",
Logger.DictionaryKey.Asynchronous.rawValue: true]]
let dictionary = [
LoggerFactory.DictionaryKey.Loggers.rawValue: loggersDictionary
]
// Execute
try! factory.readConfiguration(fromDictionary: dictionary)
// Validate
let asyncCreatedLogger = factory.getLogger("test.asyncLogger")
XCTAssertTrue(asyncCreatedLogger.asynchronous)
}
// MARK: Root logger tests
func testReadConfigurationWithRootLoggerUpdatesIt() {
let appenderDictionary = [LoggerFactory.DictionaryKey.ClassName.rawValue: "StdOutAppender",
LoggerFactory.DictionaryKey.Identifier.rawValue: "test appender"]
let rootLoggerDictionary:[String: Any] = [Logger.DictionaryKey.AppenderIds.rawValue: ["test appender"],
Logger.DictionaryKey.ThresholdLevel.rawValue: "info"]
factory.rootLogger.thresholdLevel = LogLevel.Error
factory.rootLogger.appenders = [MemoryAppender("MemoryAppender")]
let dictionary:[String: Any] = [LoggerFactory.DictionaryKey.Appenders.rawValue: [appenderDictionary],
LoggerFactory.DictionaryKey.RootLogger.rawValue: rootLoggerDictionary]
// Execute
try! factory.readConfiguration(fromDictionary: dictionary)
// Validate
XCTAssertEqual(factory.rootLogger.thresholdLevel, LogLevel.Info)
XCTAssertEqual(factory.rootLogger.appenders.count, 1)
if(factory.rootLogger.appenders.count > 0) {
XCTAssertEqual(factory.rootLogger.appenders[0].identifier, "test appender")
}
}
func testReadConfigurationWithNonDictionaryRootLoggerThrowsError() {
// Execute & validate
XCTAssertThrows { try self.factory.readConfiguration(fromDictionary: ["RootLogger": "string value"]); }
}
// Mark: Load from file tests
func testLoadValidCompletePlistFile() {
let filePath = Bundle(for: type(of: self)).path(forResource: "ValidCompleteConfiguration", ofType: "plist")
// Execute
_ = XCTAssertNoThrow { try self.factory.readConfiguration(fromPlistFile: filePath!); }
// Validate loggers
XCTAssertEqual(self.factory.rootLogger.thresholdLevel, LogLevel.Info)
XCTAssertEqual(self.factory.loggers.count, 2)
let logger1 = self.factory.getLogger("project.feature.logger1")
let logger2 = self.factory.getLogger("project.feature.logger2")
XCTAssertNil(logger1.parent)
XCTAssertNil(logger2.parent)
XCTAssertEqual(logger1.thresholdLevel, LogLevel.Error)
XCTAssertEqual(logger2.thresholdLevel, LogLevel.Fatal)
// Validate appenders
let logger1Appender1 = logger1.appenders[0]
let logger2Appender1 = logger1.appenders[0]
XCTAssertTrue(logger1Appender1 === logger2Appender1)
}
// Mark: Configuration file observing
func testLoadedConfigFileIsReloadedWhenModifiedIfRequested() {
let configurationFilePath = try! self.createTemporaryFilePath(fileExtension: "plist")
let loggerDictionary = [
LoggerFactory.DictionaryKey.Identifier.rawValue: "test.logger"]
let configuration: NSDictionary = [LoggerFactory.DictionaryKey.Loggers.rawValue: [loggerDictionary]]
NSDictionary().write(toFile: configurationFilePath, atomically: true)
try! self.factory.readConfiguration(fromPlistFile: configurationFilePath, autoReload: true, reloadInterval: 0.5)
RunLoop.current.run(until: Date(timeIntervalSinceNow: 1.0))
// Execute
configuration.write(toFile: configurationFilePath, atomically: true)
RunLoop.current.run(until: Date(timeIntervalSinceNow: 1.0))
// Validate
XCTAssertEqual(self.factory.loggers.count, 1)
XCTAssertNotNil(self.factory.loggers["test.logger"])
}
// MARK: Utility methods
fileprivate func classNameAsString(_ obj: Any) -> String {
return String(describing: type(of: obj))
}
}
| 7dcb88867037ee2a41e6ae48ba202ce0 | 47.560417 | 197 | 0.764855 | false | true | false | false |
rnystrom/WatchKit-by-Tutorials | refs/heads/master | SousChef/SousChefKit/Models/Ingredient.swift | mit | 1 | //
// Ingredient.swift
// SousChef
//
// Created by Ryan Nystrom on 11/24/14.
// Copyright (c) 2014 Ryan Nystrom. All rights reserved.
//
import Foundation
public class Ingredient: NSObject, NSCoding, Equatable {
public let quantity: String
public let name: String
public let type: IngredientType
// MARK: NSCoding
private let QuantityKey = "QuantityKey"
private let NameKey = "NameKey"
private let TypeKey = "TypeKey"
init(quantity: String, name: String, type: IngredientType) {
self.quantity = quantity
self.name = name
self.type = type
}
public required init(coder aDecoder: NSCoder) {
quantity = aDecoder.decodeObjectForKey(QuantityKey) as String
name = aDecoder.decodeObjectForKey(NameKey) as String
type = IngredientType(rawValue: aDecoder.decodeObjectForKey(TypeKey) as String)!
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(quantity, forKey: QuantityKey)
aCoder.encodeObject(name, forKey: NameKey)
aCoder.encodeObject(type.rawValue, forKey: TypeKey)
}
}
public func ==(lhs: Ingredient, rhs: Ingredient) -> Bool {
return lhs.quantity == rhs.quantity &&
lhs.name == rhs.name &&
lhs.type == rhs.type
} | 507d53e5fdd74c0c85834f083d00fe37 | 24.787234 | 84 | 0.71346 | false | false | false | false |
Witcast/witcast-ios | refs/heads/develop | Pods/WKAwesomeMenu/WKAwesomeMenu/ProgressTimer.swift | apache-2.0 | 2 | //
// ProgressTimer.swift
//
//
// Created by Adrian Mateoaea on 30.01.2016.
//
//
import UIKit
class ProgressTimer: NSObject {
var animationDuration: TimeInterval = 0.5
var animationFrom: CGFloat = 0
var animationInverse: Bool = false
var startTime: CFTimeInterval = 0
var callback: ((CGFloat) -> Void)?
static func createWithDuration(_ duration: TimeInterval, from: CGFloat = 0, inverse: Bool = false, callback: @escaping (CGFloat) -> Void) {
let timer = ProgressTimer()
timer.animationDuration = duration
timer.animationFrom = inverse ? 1 - from : from
timer.animationInverse = inverse
timer.callback = callback
timer.start()
}
func start() {
self.startTime = CACurrentMediaTime()
let link = CADisplayLink(target: self, selector: #selector(ProgressTimer.tick(_:)))
link.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
func tick(_ link: CADisplayLink) {
let elapsed = link.timestamp - self.startTime
var percent = self.animationFrom + CGFloat((elapsed / self.animationDuration))
if self.animationInverse {
percent = 1 - percent
if percent <= 0 {
percent = 0
link.invalidate()
}
} else if percent >= 1 {
percent = 1
link.invalidate()
}
self.callback?(percent)
}
}
| b888ae1d769854d470766174c3a4c8db | 25.785714 | 143 | 0.579333 | false | false | false | false |
pointfreeco/swift-web | refs/heads/main | Sources/HttpPipeline/SignedCookies.swift | mit | 1 | import Crypto
import Foundation
extension Response.Header {
/// Computes a signed cookie.
///
/// - Parameters:
/// - key: The name of the cookie.
/// - value: The data of the cookie to sign.
/// - options: (Optional) Extra options to attach to the cookie.
/// - secret: The secret to sign the cookie with. This value must also be provided to verify a signature.
/// - encrypt: (Optional) Further encrypts the signed cookie using the secret provided.
/// - Returns: A `Set-Cookie` header containing the signed cookie.
public static func setSignedCookie(
key: String,
data: Data,
options: Set<CookieOption> = [],
secret: String,
encrypt: Bool = false,
nonce: [UInt8]? = nil
)
-> Response.Header? {
let encodedValue = data.base64EncodedString()
guard let computedDigest = digest(value: encodedValue, secret: secret) else { return nil }
let signedValue = encodedValue + "--" + computedDigest
guard let finalValue = encrypt ? encrypted(text: signedValue, secret: secret, nonce: nonce) : signedValue
else { return nil }
return .some(.setCookie(key, finalValue, options.union([.httpOnly])))
}
/// A helper for creating a signed cookie of a string value.
/// Calls `setSignedCookie(key:data:options:secret)`.
public static func setSignedCookie(
key: String,
value: String,
options: Set<CookieOption> = [],
secret: String,
encrypt: Bool = false,
nonce: [UInt8]? = nil
)
-> Response.Header? {
return setSignedCookie(
key: key, data: Data(value.utf8), options: options, secret: secret, encrypt: encrypt, nonce: nonce
)
}
/// A helper for creating a signed cookie of an encodable value.
/// Calls `setSignedCookie(key:data:options:secret)`.
public static func setSignedCookie<A: Encodable>(
key: String,
value: A,
options: Set<CookieOption> = [],
secret: String,
encrypt: Bool = false,
nonce: [UInt8]? = nil
)
-> Response.Header? {
return (try? JSONEncoder().encode(value))
.flatMap { setSignedCookie(key: key, data: $0, options: options, secret: secret, encrypt: encrypt, nonce: nonce) }
}
/// Verifies signed cookie data using the secret that it was signed with.
///
/// - Parameters:
/// - signedCookieValue: The cookie value that was stored in the signed cookie. It should be of the form
/// "\(data)--\(digest)".
/// - secret: The secret used to sign the cookie.
/// - Returns: The data of the cookie value if the verification was successful, and `nil` otherwise.
public static func verifiedData(signedCookieValue: String, secret: String) -> Data? {
// We can determine if we need to decrypt by checking if the cookie contains the `--` delimeter.
let decrypt = !signedCookieValue.contains("--")
guard let cookieValue = decrypt ? decrypted(text: signedCookieValue, secret: secret) : signedCookieValue
else { return nil }
let parts = cookieValue.components(separatedBy: "--")
guard let encodedValue = parts.first,
let providedDigest = parts.last,
parts.count == 2
else {
return nil
}
let trueDigest = digest(value: encodedValue, secret: secret)
guard trueDigest == providedDigest else { return nil }
guard let value = base64DecodedData(string: encodedValue) else { return nil }
return .some(value)
}
/// Helper function that calls `verifiedData` and then tries converting the data to a string.
public static func verifiedString(signedCookieValue: String, secret: String)
-> String? {
return verifiedData(signedCookieValue: signedCookieValue, secret: secret)
.map { String(decoding: $0, as: UTF8.self) }
}
/// Helper function that calls `verifiedData` and then tries to decode the data into an `A`.
public static func verifiedValue<A: Decodable>(signedCookieValue: String, secret: String) -> A? {
return verifiedData(signedCookieValue: signedCookieValue, secret: secret)
.flatMap { try? JSONDecoder().decode(A.self, from: $0) }
}
}
public func digest(value: String, secret: String) -> String? {
let keyBytes = [UInt8](hex: secret)
let valueBytes = [UInt8](value.utf8)
let key = SymmetricKey(data: keyBytes)
let digestBytes = Crypto.HMAC<SHA256>.authenticationCode(for: valueBytes, using: key)
guard
Crypto.HMAC<SHA256>
.isValidAuthenticationCode(digestBytes, authenticating: valueBytes, using: key)
else { return nil }
return Data(digestBytes).base64EncodedString()
}
public func hexDigest(value: String, asciiSecret: String) -> String? {
let keyBytes = [UInt8](asciiSecret.utf8)
let valueBytes = [UInt8](value.utf8)
let key = SymmetricKey(data: keyBytes)
let digestBytes = Crypto.HMAC<SHA256>.authenticationCode(for: valueBytes, using: key)
guard
Crypto.HMAC<SHA256>
.isValidAuthenticationCode(digestBytes, authenticating: valueBytes, using: key)
else { return nil }
return digestBytes.map { String(format: "%02x", $0) }.joined()
}
public func encrypted(text plainText: String, secret: String, nonce nonceBytes: [UInt8]? = nil) -> String? {
do {
let secretBytes = [UInt8](hex: secret)
let key = SymmetricKey(data: secretBytes)
let plainTextBytes = [UInt8](plainText.utf8)
let nonce = try nonceBytes.map { try AES.GCM.Nonce(data: $0) }
let box = try AES.GCM.seal(plainTextBytes, using: key, nonce: nonce)
guard let data = box.combined
else { return nil }
return data.map { String(format: "%02x", $0) }.joined()
} catch {
return nil
}
}
public func decrypted(text encryptedText: String, secret: String) -> String? {
do {
let secretBytes = [UInt8](hex: secret)
let key = SymmetricKey(data: secretBytes)
let encryptedBytes = [UInt8](hex: encryptedText)
let box = try AES.GCM.SealedBox(combined: encryptedBytes)
let data = try AES.GCM.open(box, using: key)
return String(decoding: data, as: UTF8.self)
} catch {
return _decrypted(text: encryptedText, secret: secret)
}
}
private func base64DecodedData(string: String) -> Data? {
return Data(base64Encoded: Data(string.utf8))
}
extension Array where Element == UInt8 {
public init(hex: String) {
self.init()
self.reserveCapacity(hex.unicodeScalars.lazy.underestimatedCount)
var buffer: UInt8?
var skip = hex.hasPrefix("0x") ? 2 : 0
for char in hex.unicodeScalars.lazy {
guard skip == 0 else {
skip -= 1
continue
}
guard char.value >= 48 && char.value <= 102 else {
removeAll()
return
}
let v: UInt8
let c: UInt8 = UInt8(char.value)
switch c {
case let c where c <= 57:
v = c - 48
case let c where c >= 65 && c <= 70:
v = c - 55
case let c where c >= 97:
v = c - 87
default:
removeAll()
return
}
if let b = buffer {
append(b << 4 | v)
buffer = nil
} else {
buffer = v
}
}
if let b = buffer {
append(b)
}
}
}
| 4041b22fd2a836a39ad7ce08d9ded828 | 33.533981 | 122 | 0.65111 | false | false | false | false |
lexchou/swallow | refs/heads/master | stdlib/core/Int16.swift | bsd-3-clause | 1 | /// A 16-bit signed integer value
/// type.
struct Int16 : SignedIntegerType {
var value: Builtin.Int16
/// A type that can represent the number of steps between pairs of
/// values.
typealias Distance = Int
/// Create an instance initialized to zero.
init() {
//TODO
}
/// Create an instance initialized to `value`.
init(_ value: Int16) {
//TODO
}
/// Creates an integer from its big-endian representation, changing the
/// byte order if necessary.
init(bigEndian value: Int16) {
//TODO
}
/// Creates an integer from its little-endian representation, changing the
/// byte order if necessary.
init(littleEndian value: Int16) {
//TODO
}
init(_builtinIntegerLiteral value: Builtin.Int2048) {
//TODO
}
/// Create an instance initialized to `value`.
init(integerLiteral value: Int16) {
//TODO
}
/// Returns the big-endian representation of the integer, changing the
/// byte order if necessary.
var bigEndian: Int16 {
get {
return 0//TODO
}
}
/// Returns the little-endian representation of the integer, changing the
/// byte order if necessary.
var littleEndian: Int16 {
get {
return 0//TODO
}
}
/// Returns the current integer with the byte order swapped.
var byteSwapped: Int16 {
get {
return 0
}
}
static var max: Int16 {
get {
return 0
}
}
static var min: Int16 {
get {
return 0
}
}
}
extension Int16 : Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// **Note:** the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
var hashValue: Int {
get {
return 0//TODO
}
}
}
extension Int16 : Printable {
/// A textual representation of `self`.
var description: String {
get {
return 0//TODO
}
}
}
extension Int16 : RandomAccessIndexType {
/// Returns the next consecutive value after `self`.
///
/// Requires: the next value is representable.
func successor() -> Int16 {
return 0//TODO
}
/// Returns the previous consecutive value before `self`.
///
/// Requires: the previous value is representable.
func predecessor() -> Int16 {
return 0//TODO
}
/// Return the minimum number of applications of `successor` or
/// `predecessor` required to reach `other` from `self`.
///
/// Complexity: O(1).
func distanceTo(other: Int16) -> Distance {
return 0//TODO
}
/// Return `self` offset by `n` steps.
///
/// :returns: If `n > 0`, the result of applying `successor` to
/// `self` `n` times. If `n < 0`, the result of applying
/// `predecessor` to `self` `-n` times. Otherwise, `self`.
///
/// Complexity: O(1)
func advancedBy(amount: Distance) -> Int16 {
return 0//TODO
}
}
extension Int16 {
/// Add `lhs` and `rhs`, returning a result and a
/// `Bool` that is true iff the operation caused an arithmetic
/// overflow.
static func addWithOverflow(lhs: Int16, _ rhs: Int16) -> (Int16, overflow: Bool) {
return (0, false)//TODO
}
/// Subtract `lhs` and `rhs`, returning a result and a
/// `Bool` that is true iff the operation caused an arithmetic
/// overflow.
static func subtractWithOverflow(lhs: Int16, _ rhs: Int16) -> (Int16, overflow: Bool) {
return (0, false)//TODO
}
/// Multiply `lhs` and `rhs`, returning a result and a
/// `Bool` that is true iff the operation caused an arithmetic
/// overflow.
static func multiplyWithOverflow(lhs: Int16, _ rhs: Int16) -> (Int16, overflow: Bool) {
return (0, false)//TODO
}
/// Divide `lhs` and `rhs`, returning
/// a result and a `Bool`
/// that is true iff the operation caused an arithmetic overflow.
static func divideWithOverflow(lhs: Int16, _ rhs: Int16) -> (Int16, overflow: Bool) {
return (0, false)//TODO
}
/// Divide `lhs` and `rhs`, returning
/// the remainder and a `Bool`
/// that is true iff the operation caused an arithmetic overflow.
static func remainderWithOverflow(lhs: Int16, _ rhs: Int16) -> (Int16, overflow: Bool) {
return (0, false)//TODO
}
/// Represent this number using Swift's widest native signed
/// integer type.
func toIntMax() -> IntMax {
return 0//TODO
}
}
extension Int16 : SignedNumberType {
}
extension Int16 {
init(_ v: UInt8) {
//TODO
}
init(_ v: Int8) {
//TODO
}
init(_ v: UInt16) {
//TODO
}
init(_ v: UInt32) {
//TODO
}
/// Construct a `Int16` having the same bitwise representation as
/// the least significant bits of the provided bit pattern.
///
/// No range or overflow checking occurs.
init(truncatingBitPattern: UInt32) {
//TODO
}
init(_ v: Int32) {
//TODO
}
/// Construct a `Int16` having the same bitwise representation as
/// the least significant bits of the provided bit pattern.
///
/// No range or overflow checking occurs.
init(truncatingBitPattern: Int32) {
//TODO
}
init(_ v: UInt64) {
//TODO
}
/// Construct a `Int16` having the same bitwise representation as
/// the least significant bits of the provided bit pattern.
///
/// No range or overflow checking occurs.
init(truncatingBitPattern: UInt64) {
//TODO
}
init(_ v: Int64) {
//TODO
}
/// Construct a `Int16` having the same bitwise representation as
/// the least significant bits of the provided bit pattern.
///
/// No range or overflow checking occurs.
init(truncatingBitPattern: Int64) {
//TODO
}
init(_ v: UInt) {
//TODO
}
/// Construct a `Int16` having the same bitwise representation as
/// the least significant bits of the provided bit pattern.
///
/// No range or overflow checking occurs.
init(truncatingBitPattern: UInt) {
//TODO
}
init(_ v: Int) {
//TODO
}
/// Construct a `Int16` having the same bitwise representation as
/// the least significant bits of the provided bit pattern.
///
/// No range or overflow checking occurs.
init(truncatingBitPattern: Int) {
//TODO
}
/// Construct a `Int16` having the same memory representation as
/// the `UInt16` `bitPattern`. No range or overflow checking
/// occurs, and the resulting `Int16` may not have the same numeric
/// value as `bitPattern`--it is only guaranteed to use the same
/// pattern of bits.
init(bitPattern: UInt16) {
//TODO
}
}
extension Int16 : BitwiseOperationsType {
/// The empty bitset of type Int16.
static var allZeros: Int16 {
get {
return 0//TODO
}
}
}
extension Int16 {
/// Construct an instance that approximates `other`.
init(_ other: Float) {
//TODO
}
/// Construct an instance that approximates `other`.
init(_ other: Double) {
//TODO
}
/// Construct an instance that approximates `other`.
init(_ other: Float80) {
//TODO
}
}
extension Int16 : Reflectable {
/// Returns a mirror that reflects `self`.
func getMirror() -> MirrorType {
//TODO
}
}
extension Int16 : CVarArgType {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs
func encode() -> [Word] {
return []//TODO
}
}
| 52c8251a34512a2f00c5721d47fd02d2 | 24.322684 | 92 | 0.58327 | false | false | false | false |
breadwallet/breadwallet-ios | refs/heads/master | breadwalletWidget/Services/WidgetDataShareService.swift | mit | 1 | //
// WidgetDataShareService.swift
// breadwallet
//
// Created by stringcode on 21/02/2021.
// Copyright © 2021 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import Foundation
protocol WidgetDataShareService: class {
var sharingEnabled: Bool {get set}
var quoteCurrencyCode: String? {get set}
func updatePortfolio(info: [CurrencyId: Double])
func amount(for currencyId: CurrencyId) -> Double?
}
// MARK: - DefaultWidgetDataShareService
class DefaultWidgetDataShareService: WidgetDataShareService {
var sharingEnabled: Bool {
get {
defaults().bool(forKey: Constant.sharePortfolioKey)
}
set {
defaults().set(newValue, forKey: Constant.sharePortfolioKey)
if !newValue {
defaults().setValue(nil, forKey: Constant.portfolioInfoKey)
}
defaults().synchronize()
}
}
var quoteCurrencyCode: String? {
get {
defaults().string(forKey: Constant.quoteCurrencyCodeKey)
}
set {
defaults().set(newValue, forKey: Constant.quoteCurrencyCodeKey)
defaults().synchronize()
}
}
func updatePortfolio(info: [CurrencyId: Double]) {
let stringInfo = info.map { ($0.rawValue, $1) }
.reduce(into: [String: Double]()) { $0[$1.0] = $1.1 }
defaults().setValue(stringInfo, forKey: Constant.portfolioInfoKey)
defaults().synchronize()
}
func amount(for currencyId: CurrencyId) -> Double? {
guard sharingEnabled else {
return nil
}
guard let info = defaults().value(forKey: Constant.portfolioInfoKey) else {
return nil
}
return (info as? [String: Double])?[currencyId.rawValue]
}
private func defaults() -> UserDefaults {
return Constant.defaults
}
}
// MARK: - Constant
extension DefaultWidgetDataShareService {
enum Constant {
static let portfolioInfoKey = "PortfolioInfo"
static let sharePortfolioKey = "SharePortfolio"
static let quoteCurrencyCodeKey = "QuoteCurrencyCode"
static let appGroupsId = Bundle.main.object(forInfoDictionaryKey: "APP_GROUPS_ID") as? String
static let defaults = UserDefaults(suiteName: appGroupsId ?? "fail")!
}
}
| b0ec721bf166d25d9bc0ba031281a3fc | 27.082353 | 101 | 0.632593 | false | false | false | false |
alblue/swift | refs/heads/master | test/Constraints/diagnostics.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i,
i) // expected-error{{extra argument in call}}
// Position mismatch
f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x }
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}}
return (c: 0, i: g(()))
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { _ in return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}}
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {}
f8(3, f4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{argument type 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x) // expected-error{{unexpected non-void return value in void function}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>( // expected-note {{'myMap' has been explicitly marked unavailable here}}
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{'myMap' is unavailable: call the 'map()' method on the sequence}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
// SR-7599: This should be `cannot_call_non_function_value`
if s.count() == 0 {} // expected-error{{cannot invoke 'count' with no arguments}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}}
// expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{'Int' is not convertible to 'Bool'}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'}}
// expected-note@-1{{chain the optional using '?' to access member 'subscript' only for non-'nil' base values}}{{19-19=?}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}}
_ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'r21553065Protocol' be a class type}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{use of undeclared type 'Nail'}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{type of expression is ambiguous without more context}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer closure type in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
let f8 = f7(2)
_ = f8(1)
f8(10) // expected-warning {{result of call to function returning 'Int' is unused}}
f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{instance member 'method1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter #1 in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing argument for parameter #1 in call}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self) // expected-error {{missing argument for parameter 'b' in call}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {}
static func overload(b : Int) -> Color {}
static func frob(_ a : Int, b : inout Int) -> Color {}
static var svar: Color { return .Red }
}
// FIXME: This used to be better: "'map' produces '[T]', not the expected contextual result type '(Int, Color)'"
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{expression type '((Int) throws -> _) throws -> [_]' is ambiguous without more context}}
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown' expects argument of type '(description: String)'}}
let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{28-28=&}}
let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .svar() // expected-error {{static property 'svar' is not a function}}
someColor = .svar(1) // expected-error {{static property 'svar' is not a function}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{use of extraneous '&'}}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
class GenClass<T> {}
struct GenStruct<T> {}
enum GenEnum<T> {}
func test(_ a : B) {
B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) // expected-error {{missing argument label 'a:' in call}}
a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
func foo1(_ arg: Bool) -> Int {return nil}
func foo2<T>(_ arg: T) -> GenClass<T> {return nil}
func foo3<T>(_ arg: T) -> GenStruct<T> {return nil}
func foo4<T>(_ arg: T) -> GenEnum<T> {return nil}
// expected-error@-4 {{'nil' is incompatible with return type 'Int'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}}
let clsr1: () -> Int = {return nil}
let clsr2: () -> GenClass<Bool> = {return nil}
let clsr3: () -> GenStruct<String> = {return nil}
let clsr4: () -> GenEnum<Double?> = {return nil}
// expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}}
var number = 0
var genClassBool = GenClass<Bool>()
var funcFoo1 = foo1
number = nil
genClassBool = nil
funcFoo1 = nil
// expected-error@-3 {{'nil' cannot be assigned to type 'Int'}}
// expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}}
// expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
_ = MyTuple(42, a) // expected-error {{value of optional type 'String?' must be unwrapped to a value of type 'String'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}}
// expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error{{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}}
// expected-note@-1{{chain the optional }}
// expected-note@-2{{force-unwrap using '!'}}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' must be unwrapped to refer to member 'property' of wrapped base type 'ExampleStruct21890157'}}
// expected-note@-1{{chain the optional }}
// expected-note@-2{{force-unwrap using '!'}}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note@-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{value of type 'UnsafeMutableRawPointer' has no subscripts}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}}
_ = g[12] // expected-error {{'subscript(_:)' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
_ = a + b // expected-error {{unavailable}}
a += a + // expected-error {{binary operator '+=' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+=' exist}}
b
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
postfix operator +++
postfix func +++ <T>(_: inout T) -> T { fatalError() }
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}}
_ = bytes[i+++] // expected-error {{cannot pass immutable value to mutating operator: 'i' is a 'let' constant}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
// FIXME(integers): uncomment these tests once the < is no longer ambiguous
// _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a:' in call}}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: Int?)}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error @+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message)
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : BinaryInteger>() -> T? {
var buffer : T
let n = withUnsafeMutablePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480 // expected-error {{unexpected non-void return value in void function}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}}
// expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}}
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found this candidate}}
func value(y: String) -> String {} // expected-note {{found this candidate}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}}
}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x:' in call}}
r27212391(3, y: 5) // expected-error {{incorrect argument labels in call (have '_:y:', expected 'x:_:')}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} {{11-11=x: 5, }} {{12-18=}}
r27212391(y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'y:x:', expected 'x:_:')}} {{11-12=x}} {{17-20=}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{incorrect argument labels in call (have 'a:_:y:', expected 'a:x:_:')}}
r27212391(1, x: 3, y: 5) // expected-error {{incorrect argument labels in call (have '_:x:y:', expected 'a:x:_:')}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'a:y:x:', expected 'a:x:_:')}} {{17-18=x}} {{23-26=}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} {{17-17=x: 5, }} {{18-24=}}
// SR-1255
func foo1255_1() {
return true || false // expected-error {{unexpected non-void return value in void function}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 3 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
// <rdar://problem/29850459> Swift compiler misreports type error in ternary expression
let r29850459_flag = true
let r29850459_a: Int = 0
let r29850459_b: Int = 1
func r29850459() -> Bool { return false }
let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
// SR-6272: Tailored diagnostics with fixits for numerical conversions
func SR_6272_a() {
enum Foo: Int {
case bar
}
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{35-35=Int(}} {{43-43=)}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
let _: Int = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{18-18=Float(}} {{34-34=)}}
// expected-note@+1 {{expected an argument list of type '(Float, Float)'}}
let _: Float = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
Foo.bar.rawValue * Float(0)
}
func SR_6272_b() {
let lhs = Float(3)
let rhs = Int(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{24-24=Float(}} {{27-27=)}}
// expected-note@+1 {{expected an argument list of type '(Float, Float)'}}
let _: Float = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{16-16=Int(}} {{19-19=)}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
let _: Int = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
lhs * rhs
}
func SR_6272_c() {
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'String'}} {{none}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
Int(3) * "0"
struct S {}
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'S'}} {{none}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
Int(10) * S()
}
struct SR_6272_D: ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
init(integerLiteral: Int) {}
static func +(lhs: SR_6272_D, rhs: Int) -> Float { return 42.0 } // expected-note {{found this candidate}}
}
func SR_6272_d() {
let x: Float = 1.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (SR_6272_D, Int), (Float, Float)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Double'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (SR_6272_D, Int), (Double, Double)}}
let _: Float = SR_6272_D(integerLiteral: 42) + 42.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (SR_6272_D, Int), (Float, Float)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x + 1.0
}
// Ambiguous overload inside a trailing closure
func ambiguousCall() -> Int {} // expected-note {{found this candidate}}
func ambiguousCall() -> Float {} // expected-note {{found this candidate}}
func takesClosure(fn: () -> ()) {}
takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}}
// SR-4692: Useless diagnostics calling non-static method
class SR_4692_a {
private static func foo(x: Int, y: Bool) {
self.bar(x: x)
// expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}}
}
private func bar(x: Int) {
}
}
class SR_4692_b {
static func a() {
self.f(x: 3, y: true)
// expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}}
}
private func f(a: Int, b: Bool, c: String) {
self.f(x: a, y: b)
}
private func f(x: Int, y: Bool) {
}
}
// rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful
struct R32101765 { let prop32101765 = 0 }
let _: KeyPath<R32101765, Float> = \.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
// rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement
for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider changing to 'let' constant}} {{5-9=}}
_ = i + 1
}
// rdar://problem/32726044 - shrink reduced domains too far
public protocol P_32726044 {}
extension Int: P_32726044 {}
extension Float: P_32726044 {}
public func *(lhs: P_32726044, rhs: P_32726044) -> Double {
fatalError()
}
func rdar32726044() -> Float {
var f: Float = 0
f = Float(1) * 100 // Ok
let _: Float = Float(42) + 0 // Ok
return f
}
// SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error
func sr5045() {
let doubles: [Double] = [1, 2, 3]
return doubles.reduce(0, +)
// expected-error@-1 {{unexpected non-void return value in void function}}
}
// rdar://problem/32934129 - QoI: misleading diagnostic
class L_32934129<T : Comparable> {
init(_ value: T) { self.value = value }
init(_ value: T, _ next: L_32934129<T>?) {
self.value = value
self.next = next
}
var value: T
var next: L_32934129<T>? = nil
func length() -> Int {
func inner(_ list: L_32934129<T>?, _ count: Int) {
guard let list = list else { return count } // expected-error {{unexpected non-void return value in void function}}
return inner(list.next, count + 1)
}
return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}}
}
}
// rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type
class C_31671195 {
var name: Int { fatalError() }
func name(_: Int) { fatalError() }
}
C_31671195().name(UInt(0))
// expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
// rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type
class AST_28456467 {
var hasStateDef: Bool { return false }
}
protocol Expr_28456467 {}
class ListExpr_28456467 : AST_28456467, Expr_28456467 {
let elems: [Expr_28456467]
init(_ elems:[Expr_28456467] ) {
self.elems = elems
}
override var hasStateDef: Bool {
return elems.first(where: { $0.hasStateDef }) != nil
// expected-error@-1 {{value of type 'Expr_28456467' has no member 'hasStateDef'}}
}
}
// rdar://problem/31849281 - Let's play "bump the argument"
struct rdar31849281 { var foo, a, b, c: Int }
_ = rdar31849281(a: 101, b: 102, c: 103, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(a: 101, c: 103, b: 102, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, a: 101, c: 103, b: 102) // expected-error {{argument 'b' must precede argument 'c'}} {{36-36=b: 102, }} {{42-50=}}
_ = rdar31849281(b: 102, c: 103, a: 101, foo: 104) // expected-error {{incorrect argument labels in call (have 'b:c:a:foo:', expected 'foo:a:b:c:')}} {{18-19=foo}} {{26-27=a}} {{34-35=b}} {{42-45=c}}
_ = rdar31849281(foo: 104, b: 102, c: 103, a: 101) // expected-error {{argument 'a' must precede argument 'b'}} {{28-28=a: 101, }} {{42-50=}}
func var_31849281(_ a: Int, _ b: Int..., c: Int) {}
var_31849281(1, c: 10, 3, 4, 5, 6, 7, 8, 9) // expected-error {{unnamed argument #3 must precede argument 'c'}} {{17-17=3, 4, 5, 6, 7, 8, 9, }} {{22-43=}}
func fun_31849281(a: (Bool) -> Bool, b: (Int) -> (String), c: [Int?]) {}
fun_31849281(c: [nil, 42], a: { !$0 }, b: { (num: Int) -> String in return "\(num)" })
// expected-error @-1 {{incorrect argument labels in call (have 'c:a:b:', expected 'a:b:c:')}} {{14-15=a}} {{28-29=b}} {{40-41=c}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { (num: Int) -> String in return String(describing: num) })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { (num: Int) -> String in return String(describing: num) }, }} {{38-101=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { "\($0)" })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { "\\($0)" }, }} {{38-54=}}
func f_31849281(x: Int, y: Int, z: Int) {}
f_31849281(42, y: 10, x: 20) // expected-error {{incorrect argument labels in call (have '_:y:x:', expected 'x:y:z:')}} {{12-12=x: }} {{23-24=z}}
func sr5081() {
var a = ["1", "2", "3", "4", "5"]
var b = [String]()
b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}}
}
func rdar17170728() {
var i: Int? = 1
var j: Int?
var k: Int? = 2
let _ = [i, j, k].reduce(0 as Int?) {
$0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil))
// expected-error@-1 {{ambiguous use of operator '+'}}
}
}
// https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad
// generic constraints
func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {} // expected-note {{where 'U' = 'T'}}
func platypus<T>(a: [T]) {
_ = elephant(a) // expected-error {{global function 'elephant' requires that 'T' conform to 'Hashable'}}
}
// Another case of the above.
func badTypes() {
let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }}
let array = [Int](sequence)
// expected-error@-1 {{initializer 'init(_:)' requires the types 'Int' and '[Int]' be equivalent}}
}
// rdar://34357545
func unresolvedTypeExistential() -> Bool {
return (Int.self==_{})
// expected-error@-1 {{ambiguous reference to member '=='}}
}
func rdar43525641(_ a: Int, _ b: Int = 0, c: Int = 0, _ d: Int) {}
rdar43525641(1, c: 2, 3) // Ok
| c434a96c211f9e14c10bef8f38a7690f | 44.367987 | 210 | 0.663278 | false | false | false | false |
Xiomara7/bookiao-ios | refs/heads/master | bookiao-ios/AppointmentsViewController.swift | mit | 1 | //
// AppointmentsViewController.swift
// bookiao-ios
//
// Created by Xiomara on 10/2/14.
// Copyright (c) 2014 UPRRP. All rights reserved.
//
import UIKit
import CoreData
class AppointmentsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let application = UIApplication.sharedApplication().delegate as AppDelegate
var names: NSArray! = []
var tableView: UITableView!
var dataSource: [[String: String]] = []
var refreshControl:UIRefreshControl!
var customDesign = CustomDesign()
var requests = HTTPrequests()
override func viewDidLoad() {
self.view = UIView(frame: self.view.bounds)
self.view.backgroundColor = UIColor.whiteColor()
let tableAppearance = UITableView.appearance()
tableView = UITableView(frame: CGRectMake(0, -40, self.view.frame.width, self.view.frame.height), style: .Grouped)
tableView.delegate = self
tableView.dataSource = self
tableView.tintColor = UIColor.whiteColor()
tableView.separatorColor = UIColor.grayColor()
tableView.backgroundColor = customDesign.UIColorFromRGB(0xE4E4E4)
tableView.showsVerticalScrollIndicator = true
self.view.addSubview(tableView)
self.tabBarController?.navigationItem.title = DataManager.sharedManager.dateLabel
self.refreshControl = UIRefreshControl()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refersh")
self.refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refreshControl)
}
func refresh() {
// let ut = DataManager.sharedManager.userInfo["userType"] as String
// let id = DataManager.sharedManager.userInfo["id"] as Int
//
// if ut == "client" {
// self.requests.getClientAppointments(id)
// self.requests.getClientAppointmentsPerDay(id, date: DataManager.sharedManager.date)
// }
// if ut == "employee" {
// self.requests.getEmployeeAppointments(id)
// self.requests.getEmployeeAppointmentsPerDay(id, date: DataManager.sharedManager.date)
// }
}
override func viewWillAppear(animated: Bool) {
self.tabBarController?.navigationItem.title = DataManager.sharedManager.dateLabel
self.tabBarController?.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.tabBarItem.setTitlePositionAdjustment(UIOffsetMake(0, -50))
}
// MARK: - Private Methods
func updateDataSource() {
tableView.reloadData()
}
// MARK: - UITableViewDataSource Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let ut = DataManager.sharedManager.userInfo["userType"] as String!
let eAppointments = DataManager.sharedManager.employeeAppointmentsPerDay
let cAppointments = DataManager.sharedManager.clientAppointmentsPerDay
if eAppointments.count == 0 {
return 1
}
if cAppointments.count == 0 {
return 1
}
if ut == "employee" {
return eAppointments.count
}
if ut == "client" {
return cAppointments.count
}
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
let ut = DataManager.sharedManager.userInfo["userType"] as String!
let eAppointments = DataManager.sharedManager.employeeAppointmentsPerDay as NSArray!
let cAppointments = DataManager.sharedManager.clientAppointmentsPerDay as NSArray!
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as CustomCell!
if cell == nil {
cell = CustomCell(reuseIdentifier: "Cell")
}
let cellFrame = self.view.bounds
if ut == "employee" {
if eAppointments.count == 0 && cAppointments.count == 0 {
cell.sTitle.text = DataManager.sharedManager.Title
cell.status.text = DataManager.sharedManager.status
}
else {
let day = eAppointments[indexPath.row]["day"] as String!
let time = eAppointments[indexPath.row]["time"] as String!
let serv = eAppointments[indexPath.row]["services"] as NSArray!
cell.priceLabel.text = serv[0] as? String
cell.titleLabel.text = eAppointments[indexPath.row]["client"] as String!
cell.phoneLabel.text = DataManager.sharedManager.userInfo["phone_number"] as String!
cell.stitleLabel.text = "\(DataManager.sharedManager.phrase) \(time)"
}
}
else if ut! == "client" {
if cAppointments.count == 0 && eAppointments.count == 0 {
cell.sTitle.text = DataManager.sharedManager.Title
cell.status.text = DataManager.sharedManager.status
}
else {
let day = cAppointments[indexPath.row]["day"] as String!
let time = cAppointments[indexPath.row]["time"] as String!
let serv = cAppointments[indexPath.row]["services"] as NSArray!
cell.priceLabel.text = serv[0] as? String
cell.titleLabel.text = cAppointments[indexPath.row]["employee"] as String!
cell.phoneLabel.text = DataManager.sharedManager.userInfo["phone_number"] as String!
cell.stitleLabel.text = "\(DataManager.sharedManager.phrase) \(time)"
}
}
cell.selectionStyle = .Default
cell.accessoryType = .None
cell.frame.origin.y = 4
cell.setNeedsUpdateConstraints()
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 140.0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("Hello")
}
func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!){
println(item)
}
func post() {
let newPost = newAppointmentViewController()
self.presentViewController(newPost, animated: true, completion: nil)
}
}
| e3a2a0c6adf23a453817ef7fdb9d380f | 37.774566 | 122 | 0.63059 | false | false | false | false |
analuizaferrer/TrocaComigo | refs/heads/master | Example/SwapIt/DepartmentViewController.swift | mit | 1 | //
// DepartmentViewController.swift
// Koloda
//
// Created by Ana Luiza Ferrer on 6/17/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
class DepartmentViewController: UIViewController {
var productImages = [NSData]()
var category: String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func women(sender: AnyObject) {
self.category = "women"
performSegueWithIdentifier("segueToCategoriesViewController", sender: self)
}
@IBAction func men(sender: AnyObject) {
self.category = "men"
performSegueWithIdentifier("segueToCategoriesViewController", sender: self)
}
@IBAction func kids(sender: AnyObject) {
self.category = "kids"
performSegueWithIdentifier("segueToCategoriesViewController", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "segueToCategoriesViewController") {
let categoriesVC = segue.destinationViewController as! CategoriesViewController
categoriesVC.category = self.category
categoriesVC.productImages = self.productImages
}
}
}
| 2a8b7c326b0f377389c82f2a7696659c | 26.849057 | 91 | 0.662602 | false | false | false | false |
BalestraPatrick/Tweetometer | refs/heads/master | Carthage/Checkouts/Whisper/Source/WhistleFactory.swift | mit | 4 | import UIKit
public enum WhistleAction {
case present
case show(TimeInterval)
}
let whistleFactory = WhistleFactory()
open class WhistleFactory: UIViewController {
open lazy var whistleWindow: UIWindow = UIWindow()
public struct Dimensions {
static var notchHeight: CGFloat {
if UIApplication.shared.statusBarFrame.height > 20 {
return 32.0
} else {
return 0.0
}
}
}
open lazy var titleLabelHeight = CGFloat(20.0)
open lazy var titleLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
return label
}()
open fileprivate(set) lazy var tapGestureRecognizer: UITapGestureRecognizer = { [unowned self] in
let gesture = UITapGestureRecognizer()
gesture.addTarget(self, action: #selector(WhistleFactory.handleTapGestureRecognizer))
return gesture
}()
open fileprivate(set) var murmur: Murmur?
open var viewController: UIViewController?
open var hideTimer = Timer()
private weak var previousKeyWindow: UIWindow?
// MARK: - Initializers
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nil, bundle: nil)
setupWindow()
view.clipsToBounds = true
view.addSubview(titleLabel)
view.addGestureRecognizer(tapGestureRecognizer)
NotificationCenter.default.addObserver(self, selector: #selector(WhistleFactory.orientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
// MARK: - Configuration
open func whistler(_ murmur: Murmur, action: WhistleAction) {
self.murmur = murmur
titleLabel.text = murmur.title
titleLabel.font = murmur.font
titleLabel.textColor = murmur.titleColor
view.backgroundColor = murmur.backgroundColor
whistleWindow.backgroundColor = murmur.backgroundColor
moveWindowToFront()
setupFrames()
switch action {
case .show(let duration):
show(duration: duration)
default:
present()
}
}
// MARK: - Setup
open func setupWindow() {
whistleWindow.addSubview(self.view)
whistleWindow.clipsToBounds = true
moveWindowToFront()
}
func moveWindowToFront() {
whistleWindow.windowLevel = view.isiPhoneX ? UIWindowLevelNormal : UIWindowLevelStatusBar
setNeedsStatusBarAppearanceUpdate()
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
return UIApplication.shared.statusBarStyle
}
open func setupFrames() {
whistleWindow = UIWindow()
setupWindow()
let labelWidth = UIScreen.main.bounds.width
let defaultHeight = titleLabelHeight
if let text = titleLabel.text {
let neededDimensions =
NSString(string: text).boundingRect(
with: CGSize(width: labelWidth, height: CGFloat.infinity),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSAttributedStringKey.font: titleLabel.font],
context: nil
)
titleLabelHeight = CGFloat(neededDimensions.size.height)
titleLabel.numberOfLines = 0 // Allows unwrapping
if titleLabelHeight < defaultHeight {
titleLabelHeight = defaultHeight
}
} else {
titleLabel.sizeToFit()
}
whistleWindow.frame = CGRect(x: 0, y: 0,
width: labelWidth,
height: titleLabelHeight + Dimensions.notchHeight)
view.frame = whistleWindow.bounds
titleLabel.frame = CGRect(
x: 0.0,
y: Dimensions.notchHeight,
width: view.bounds.width,
height: titleLabelHeight
)
}
// MARK: - Movement methods
public func show(duration: TimeInterval) {
present()
calm(after: duration)
}
public func present() {
hideTimer.invalidate()
if UIApplication.shared.keyWindow != whistleWindow {
previousKeyWindow = UIApplication.shared.keyWindow
}
let initialOrigin = whistleWindow.frame.origin.y
whistleWindow.frame.origin.y = initialOrigin - titleLabelHeight - Dimensions.notchHeight
whistleWindow.isHidden = false
UIView.animate(withDuration: 0.2, animations: {
self.whistleWindow.frame.origin.y = initialOrigin
})
}
public func hide() {
let finalOrigin = view.frame.origin.y - titleLabelHeight - Dimensions.notchHeight
UIView.animate(withDuration: 0.2, animations: {
self.whistleWindow.frame.origin.y = finalOrigin
}, completion: { _ in
if let window = self.previousKeyWindow {
window.isHidden = false
self.whistleWindow.windowLevel = UIWindowLevelNormal - 1
self.previousKeyWindow = nil
window.rootViewController?.setNeedsStatusBarAppearanceUpdate()
}
})
}
public func calm(after: TimeInterval) {
hideTimer.invalidate()
hideTimer = Timer.scheduledTimer(timeInterval: after, target: self, selector: #selector(WhistleFactory.timerDidFire), userInfo: nil, repeats: false)
}
// MARK: - Timer methods
@objc public func timerDidFire() {
hide()
}
@objc func orientationDidChange() {
if whistleWindow.isKeyWindow {
setupFrames()
hide()
}
}
// MARK: - Gesture methods
@objc fileprivate func handleTapGestureRecognizer() {
guard let murmur = murmur else { return }
murmur.action?()
}
}
| 31fe5d9db2f6ce47adad1aa1f9c28d6c | 26.160194 | 175 | 0.685255 | false | false | false | false |
arvedviehweger/swift | refs/heads/master | stdlib/public/core/Builtin.swift | apache-2.0 | 4 | //===----------------------------------------------------------------------===//
//
// 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
// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.
@available(*, unavailable, message: "use MemoryLayout<T>.size instead.")
public func sizeof<T>(_:T.Type) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "MemoryLayout.size(ofValue:)")
public func sizeofValue<T>(_:T) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "use MemoryLayout<T>.alignment instead.")
public func alignof<T>(_:T.Type) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "MemoryLayout.alignment(ofValue:)")
public func alignofValue<T>(_:T) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "use MemoryLayout<T>.stride instead.")
public func strideof<T>(_:T.Type) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "MemoryLayout.stride(ofValue:)")
public func strideofValue<T>(_:T) -> Int {
Builtin.unreachable()
}
// This function is the implementation of the `_roundUp` overload set. It is
// marked `@inline(__always)` to make primary `_roundUp` entry points seem
// cheap enough for the inliner.
@_versioned
@inline(__always)
internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt {
_sanityCheck(alignment > 0)
_sanityCheck(_isPowerOf2(alignment))
// Note, given that offset is >= 0, and alignment > 0, we don't
// need to underflow check the -1, as it can never underflow.
let x = offset + UInt(bitPattern: alignment) &- 1
// Note, as alignment is a power of 2, we'll use masking to efficiently
// get the aligned value
return x & ~(UInt(bitPattern: alignment) &- 1)
}
@_versioned
internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt {
return _roundUpImpl(offset, toAlignment: alignment)
}
@_versioned
internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int {
_sanityCheck(offset >= 0)
return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment))
}
/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.
@_transparent
public // @testable
func _canBeClass<T>(_: T.Type) -> Int8 {
return Int8(Builtin.canBeClass(T.self))
}
/// Returns the bits of the given instance, interpreted as having the specified
/// type.
///
/// Only use this function to convert the instance passed as `x` to a
/// layout-compatible type when the conversion is not possible through other
/// means. Common conversions that are supported by the standard library
/// include the following:
///
/// - To convert an integer value from one type to another, use an initializer
/// or the `numericCast(_:)` function.
/// - To perform a bitwise conversion of an integer value to a different type,
/// use an `init(bitPattern:)` or `init(truncatingBitPattern:)` initializer.
/// - To convert between a pointer and an integer value with that bit pattern,
/// or vice versa, use the `init(bitPattern:)` initializer for the
/// destination type.
/// - To perform a reference cast, use the casting operators (`as`, `as!`, or
/// `as?`) or the `unsafeDowncast(_:to:)` function. Do not use
/// `unsafeBitCast(_:to:)` with class or pointer types; doing so may
/// introduce undefined behavior.
///
/// - Warning: Calling this function breaks the guarantees of Swift's type
/// system; use with extreme care.
///
/// - Parameters:
/// - x: The instance to cast to `type`.
/// - type: The type to cast `x` to. `type` and the type of `x` must have the
/// same size of memory representation and compatible memory layout.
/// - Returns: A new instance of type `U`, cast from `x`.
@_transparent
public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
_precondition(MemoryLayout<T>.size == MemoryLayout<U>.size,
"can't unsafeBitCast between types of different sizes")
return Builtin.reinterpretCast(x)
}
/// `unsafeBitCast` something to `AnyObject`.
@_transparent
internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {
return unsafeBitCast(x, to: AnyObject.self)
}
@_inlineable
@_versioned
@_transparent
func == (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_inlineable
@_versioned
@_transparent
func != (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return !(lhs == rhs)
}
@_inlineable
@_versioned
@_transparent
func == (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_inlineable
@_versioned
@_transparent
func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
}
/// Returns `true` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
@_inlineable
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
return unsafeBitCast(t0, to: Int.self) == unsafeBitCast(t1, to: Int.self)
}
/// Returns `false` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
@_inlineable
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}
/// Tell the optimizer that this code is unreachable if condition is
/// known at compile-time to be true. If condition is false, or true
/// but not a compile-time constant, this call has no effect.
@_transparent
internal func _unreachable(_ condition: Bool = true) {
if condition {
// FIXME: use a parameterized version of Builtin.unreachable when
// <rdar://problem/16806232> is closed.
Builtin.unreachable()
}
}
/// Tell the optimizer that this code is unreachable if this builtin is
/// reachable after constant folding build configuration builtins.
@_versioned @_transparent internal
func _conditionallyUnreachable() -> Never {
Builtin.conditionallyUnreachable()
}
@_versioned
@_silgen_name("_swift_isClassOrObjCExistentialType")
func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool
/// Returns `true` iff `T` is a class type or an `@objc` existential such as
/// `AnyObject`.
@_versioned
@inline(__always)
internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool {
switch _canBeClass(x) {
// Is not a class.
case 0:
return false
// Is a class.
case 1:
return true
// Maybe a class.
default:
return _swift_isClassOrObjCExistentialType(x)
}
}
/// Returns an `UnsafePointer` to the storage used for `object`. There's
/// not much you can do with this other than use it to identify the
/// object.
@available(*, unavailable, message: "Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.")
public func unsafeAddress(of object: AnyObject) -> UnsafeRawPointer {
Builtin.unreachable()
}
@available(*, unavailable, message: "Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.")
public func unsafeAddressOf(_ object: AnyObject) -> UnsafeRawPointer {
Builtin.unreachable()
}
/// Converts a reference of type `T` to a reference of type `U` after
/// unwrapping one level of Optional.
///
/// Unwrapped `T` and `U` must be convertible to AnyObject. They may
/// be either a class or a class protocol. Either T, U, or both may be
/// optional references.
@_transparent
public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
/// - returns: `x as T`.
///
/// - Precondition: `x is T`. In particular, in -O builds, no test is
/// performed to ensure that `x` actually has dynamic type `T`.
///
/// - Warning: Trades safety for performance. Use `unsafeDowncast`
/// only when `x as! T` has proven to be a performance problem and you
/// are confident that, always, `x is T`. It is better than an
/// `unsafeBitCast` because it's more restrictive, and because
/// checking is still performed in debug builds.
@_transparent
public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to: T.Type) -> T {
_debugPrecondition(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@inline(__always)
public func _getUnsafePointerToStoredProperties(_ x: AnyObject)
-> UnsafeMutableRawPointer {
let storedPropertyOffset = _roundUp(
MemoryLayout<_HeapObject>.size,
toAlignment: MemoryLayout<Optional<AnyObject>>.alignment)
return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) +
storedPropertyOffset
}
//===----------------------------------------------------------------------===//
// Branch hints
//===----------------------------------------------------------------------===//
// Use @_semantics to indicate that the optimizer recognizes the
// semantics of these function calls. This won't be necessary with
// mandatory generic inlining.
@_versioned
@_transparent
@_semantics("branchhint")
internal func _branchHint(_ actual: Bool, expected: Bool) -> Bool {
return Bool(Builtin.int_expect_Int1(actual._value, expected._value))
}
/// Optimizer hint that `x` is expected to be `true`.
@_transparent
@_semantics("fastpath")
public func _fastPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: true)
}
/// Optimizer hint that `x` is expected to be `false`.
@_transparent
@_semantics("slowpath")
public func _slowPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: false)
}
/// Optimizer hint that the code where this function is called is on the fast
/// path.
@_transparent
public func _onFastPath() {
Builtin.onFastPath()
}
//===--- Runtime shim wrappers --------------------------------------------===//
/// Returns `true` iff the class indicated by `theClass` uses native
/// Swift reference-counting.
#if _runtime(_ObjC)
// Declare it here instead of RuntimeShims.h, because we need to specify
// the type of argument to be AnyClass. This is currently not possible
// when using RuntimeShims.h
@_versioned
@_silgen_name("swift_objc_class_usesNativeSwiftReferenceCounting")
func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool
#else
@_versioned
@inline(__always)
func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool {
return true
}
#endif
@_silgen_name("swift_class_getInstanceExtents")
func swift_class_getInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@_silgen_name("swift_objc_class_unknownGetInstanceExtents")
func swift_objc_class_unknownGetInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
/// - Returns:
@inline(__always)
internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int {
#if _runtime(_ObjC)
return Int(swift_objc_class_unknownGetInstanceExtents(theClass).positive)
#else
return Int(swift_class_getInstanceExtents(theClass).positive)
#endif
}
//===--- Builtin.BridgeObject ---------------------------------------------===//
#if arch(i386) || arch(arm)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0003 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#elseif arch(x86_64)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0006 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 1 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0001 }
}
#elseif arch(arm64)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0000 }
}
#elseif arch(powerpc64) || arch(powerpc64le)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0000_0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#elseif arch(s390x)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0000_0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#endif
/// Extract the raw bits of `x`.
@_versioned
@inline(__always)
internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
/// Extract the raw spare bits of `x`.
@_versioned
@inline(__always)
internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return _bitPattern(x) & _objectPointerSpareBits
}
@_versioned
@inline(__always)
internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool {
return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0
}
/// Create a `BridgeObject` around the given `nativeObject` with the
/// given spare bits.
///
/// Reference-counting and other operations on this
/// object will have access to the knowledge that it is native.
///
/// - Precondition: `bits & _objectPointerIsObjCBit == 0`,
/// `bits & _objectPointerSpareBits == bits`.
@_versioned
@inline(__always)
internal func _makeNativeBridgeObject(
_ nativeObject: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(
(bits & _objectPointerIsObjCBit) == 0,
"BridgeObject is treated as non-native when ObjC bit is set"
)
return _makeBridgeObject(nativeObject, bits)
}
/// Create a `BridgeObject` around the given `objCObject`.
@inline(__always)
public // @testable
func _makeObjCBridgeObject(
_ objCObject: AnyObject
) -> Builtin.BridgeObject {
return _makeBridgeObject(
objCObject,
_isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)
}
/// Create a `BridgeObject` around the given `object` with the
/// given spare bits.
///
/// - Precondition:
///
/// 1. `bits & _objectPointerSpareBits == bits`
/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,
/// `object` is either a native object, or `bits ==
/// _objectPointerIsObjCBit`.
@_versioned
@inline(__always)
internal func _makeBridgeObject(
_ object: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(object) || bits == 0,
"Tagged pointers cannot be combined with bits")
_sanityCheck(
_isObjCTaggedPointer(object)
|| _usesNativeSwiftReferenceCounting(type(of: object))
|| bits == _objectPointerIsObjCBit,
"All spare bits must be set in non-native, non-tagged bridge objects"
)
_sanityCheck(
bits & _objectPointerSpareBits == bits,
"Can't store non-spare bits into Builtin.BridgeObject")
return Builtin.castToBridgeObject(
object, bits._builtinWordValue
)
}
@_versioned
@_silgen_name("_swift_class_getSuperclass")
internal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass?
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// a root class or class protocol.
@inline(__always)
public // @testable
func _getSuperclass(_ t: AnyClass) -> AnyClass? {
return _swift_class_getSuperclass(t)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// not a class, is a root class, or is a class protocol.
@inline(__always)
public // @testable
func _getSuperclass(_ t: Any.Type) -> AnyClass? {
return (t as? AnyClass).flatMap { _getSuperclass($0) }
}
//===--- Builtin.IsUnique -------------------------------------------------===//
// _isUnique functions must take an inout object because they rely on
// Builtin.isUnique which requires an inout reference to preserve
// source-level copies in the presence of ARC optimization.
//
// Taking an inout object makes sense for two additional reasons:
//
// 1. You should only call it when about to mutate the object.
// Doing so otherwise implies a race condition if the buffer is
// shared across threads.
//
// 2. When it is not an inout function, self is passed by
// value... thus bumping the reference count and disturbing the
// result we are trying to observe, Dr. Heisenberg!
//
// _isUnique and _isUniquePinned cannot be made public or the compiler
// will attempt to generate generic code for the transparent function
// and type checking will fail.
/// Returns `true` if `object` is uniquely referenced.
@_versioned
@_transparent
internal func _isUnique<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUnique(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
@_versioned
@_transparent
internal func _isUniqueOrPinned<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUniqueOrPinned(&object))
}
/// Returns `true` if `object` is uniquely referenced.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUnique_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero, so
// force cast it to BridgeObject and check the spare bits.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUnique_native(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUniqueOrPinned_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUniqueOrPinned_native(&object))
}
/// Returns `true` if type is a POD type. A POD type is a type that does not
/// require any special handling on copying or destruction.
@_transparent
public // @testable
func _isPOD<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.ispod(type))
}
/// Returns `true` if type is nominally an Optional type.
@_transparent
public // @testable
func _isOptional<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isOptional(type))
}
@available(*, unavailable, message: "Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.")
public func unsafeUnwrap<T>(_ nonEmpty: T?) -> T {
Builtin.unreachable()
}
/// Extract an object reference from an Any known to contain an object.
internal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject {
_sanityCheck(type(of: any) is AnyObject.Type
|| type(of: any) is AnyObject.Protocol,
"Any expected to contain object reference")
// With a SIL instruction, we could more efficiently grab the object reference
// out of the Any's inline storage.
// On Linux, bridging isn't supported, so this is a force cast.
#if _runtime(_ObjC)
return any as AnyObject
#else
return any as! AnyObject
#endif
}
// Game the SIL diagnostic pipeline by inlining this into the transparent
// definitions below after the stdlib's diagnostic passes run, so that the
// `staticReport`s don't fire while building the standard library, but do
// fire if they ever show up in code that uses the standard library.
@inline(__always)
public // internal with availability
func _trueAfterDiagnostics() -> Builtin.Int1 {
return true._value
}
/// Returns the dynamic type of a value.
///
/// You can use the `type(of:)` function to find the dynamic type of a value,
/// particularly when the dynamic type is different from the static type. The
/// *static type* of a value is the known, compile-time type of the value. The
/// *dynamic type* of a value is the value's actual type at run-time, which
/// may be nested inside its concrete type.
///
/// In the following code, the `count` variable has the same static and dynamic
/// type: `Int`. When `count` is passed to the `printInfo(_:)` function,
/// however, the `value` parameter has a static type of `Any`, the type
/// declared for the parameter, and a dynamic type of `Int`.
///
/// func printInfo(_ value: Any) {
/// let type = type(of: value)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// let count: Int = 5
/// printInfo(count)
/// // '5' of type 'Int'
///
/// The dynamic type returned from `type(of:)` is a *concrete metatype*
/// (`T.Type`) for a class, structure, enumeration, or other non-protocol type
/// `T`, or an *existential metatype* (`P.Type`) for a protocol or protocol
/// composition `P`. When the static type of the value passed to `type(of:)`
/// is constrained to a class or protocol, you can use that metatype to access
/// initializers or other static members of the class or protocol.
///
/// For example, the parameter passed as `value` to the `printSmileyInfo(_:)`
/// function in the example below is an instance of the `Smiley` class or one
/// of its subclasses. The function uses `type(of:)` to find the dynamic type
/// of `value`, which itself is an instance of the `Smiley.Type` metatype.
///
/// class Smiley {
/// class var text: String {
/// return ":)"
/// }
/// }
///
/// class EmojiSmiley : Smiley {
/// override class var text: String {
/// return "😀"
/// }
/// }
///
/// func printSmileyInfo(_ value: Smiley) {
/// let smileyType = type(of: value)
/// print("Smile!", smileyType.text)
/// }
///
/// let emojiSmiley = EmojiSmiley()
/// printSmileyInfo(emojiSmiley)
/// // Smile! 😀
///
/// In this example, accessing the `text` property of the `smileyType` metatype
/// retrieves the overridden value from the `EmojiSmiley` subclass, instead of
/// the `Smiley` class's original definition.
///
/// Normally, you don't need to be aware of the difference between concrete and
/// existential metatypes, but calling `type(of:)` can yield unexpected
/// results in a generic context with a type parameter bound to a protocol. In
/// a case like this, where a generic parameter `T` is bound to a protocol
/// `P`, the type parameter is not statically known to be a protocol type in
/// the body of the generic function, so `type(of:)` can only produce the
/// concrete metatype `P.Protocol`.
///
/// The following example defines a `printGenericInfo(_:)` function that takes
/// a generic parameter and declares the `String` type's conformance to a new
/// protocol `P`. When `printGenericInfo(_:)` is called with a string that has
/// `P` as its static type, the call to `type(of:)` returns `P.self` instead
/// of the dynamic type inside the parameter, `String.self`.
///
/// func printGenericInfo<T>(_ value: T) {
/// let type = type(of: value)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// protocol P {}
/// extension String: P {}
///
/// let stringAsP: P = "Hello!"
/// printGenericInfo(stringAsP)
/// // 'Hello!' of type 'P'
///
/// This unexpected result occurs because the call to `type(of: value)` inside
/// `printGenericInfo(_:)` must return a metatype that is an instance of
/// `T.Type`, but `String.self` (the expected dynamic type) is not an instance
/// of `P.Type` (the concrete metatype of `value`). To get the dynamic type
/// inside `value` in this generic context, cast the parameter to `Any` when
/// calling `type(of:)`.
///
/// func betterPrintGenericInfo<T>(_ value: T) {
/// let type = type(of: value as Any)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// betterPrintGenericInfo(stringAsP)
/// // 'Hello!' of type 'String'
///
/// - Parameter value: The value to find the dynamic type of.
/// - Returns: The dynamic type, which is a value of metatype type.
@_transparent
@_semantics("typechecker.type(of:)")
public func type<T, Metatype>(of value: T) -> Metatype {
// This implementation is never used, since calls to `Swift.type(of:)` are
// resolved as a special case by the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'type(of:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
/// Allows a nonescaping closure to temporarily be used as if it were allowed
/// to escape.
///
/// You can use this function to call an API that takes an escaping closure in
/// a way that doesn't allow the closure to escape in practice. The examples
/// below demonstrate how to use `withoutActuallyEscaping(_:do:)` in
/// conjunction with two common APIs that use escaping closures: lazy
/// collection views and asynchronous operations.
///
/// The following code declares an `allValues(in:match:)` function that checks
/// whether all the elements in an array match a predicate. The function won't
/// compile as written, because a lazy collection's `filter(_:)` method
/// requires an escaping closure. The lazy collection isn't persisted, so the
/// `predicate` closure won't actually escape the body of the function, but
/// even so it can't be used in this way.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return array.lazy.filter { !predicate($0) }.isEmpty
/// }
/// // error: closure use of non-escaping parameter 'predicate'...
///
/// `withoutActuallyEscaping(_:do:)` provides a temporarily-escapable copy of
/// `predicate` that _can_ be used in a call to the lazy view's `filter(_:)`
/// method. The second version of `allValues(in:match:)` compiles without
/// error, with the compiler guaranteeing that the `escapablePredicate`
/// closure doesn't last beyond the call to `withoutActuallyEscaping(_:do:)`.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return withoutActuallyEscaping(predicate) { escapablePredicate in
/// array.lazy.filter { !escapablePredicate($0) }.isEmpty
/// }
/// }
///
/// Asynchronous calls are another type of API that typically escape their
/// closure arguments. The following code declares a
/// `perform(_:simultaneouslyWith:)` function that uses a dispatch queue to
/// execute two closures concurrently.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: f)
/// queue.async(execute: g)
/// queue.sync(flags: .barrier) {}
/// }
/// // error: passing non-escaping parameter 'f'...
/// // error: passing non-escaping parameter 'g'...
///
/// The `perform(_:simultaneouslyWith:)` function ends with a call to the
/// `sync(flags:execute:)` method using the `.barrier` flag, which forces the
/// function to wait until both closures have completed running before
/// returning. Even though the barrier guarantees that neither closure will
/// escape the function, the `async(execute:)` method still requires that the
/// closures passed be marked as `@escaping`, so the first version of the
/// function does not compile. To resolve this, you can use
/// `withoutActuallyEscaping(_:do:)` to get copies of `f` and `g` that can be
/// passed to `async(execute:)`.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// withoutActuallyEscaping(f) { escapableF in
/// withoutActuallyEscaping(g) { escapableG in
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: escapableF)
/// queue.async(execute: escapableG)
/// queue.sync(flags: .barrier) {}
/// }
/// }
/// }
///
/// - Important: The escapable copy of `closure` passed as `body` is only valid
/// during the call to `withoutActuallyEscaping(_:do:)`. It is undefined
/// behavior for the escapable closure to be stored, referenced, or executed
/// after the function returns.
///
/// - Parameter closure: A non-escaping closure value that will be made
/// escapable for the duration of the execution of the `body` closure. If
/// `body` has a return value, it is used as the return value for the
/// `withoutActuallyEscaping(_:do:)` function.
/// - Parameter body: A closure that will be immediately executed, receiving an
/// escapable copy of `closure` as an argument.
/// - Returns: The return value of the `body` closure, if any.
@_transparent
@_semantics("typechecker.withoutActuallyEscaping(_:do:)")
public func withoutActuallyEscaping<ClosureType, ResultType>(
_ closure: ClosureType,
do body: (_ escapingClosure: ClosureType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
@_transparent
@_semantics("typechecker._openExistential(_:do:)")
public func _openExistential<ExistentialType, ContainedType, ResultType>(
_ existential: ExistentialType,
do body: (_ escapingClosure: ContainedType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift._openExistential(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: '_openExistential(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
| 6cc871c329098197924da1a092808a6a | 35.449766 | 110 | 0.686164 | false | false | false | false |
tectijuana/patrones | refs/heads/master | Bloque1SwiftArchivado/PracticasSwift/PalaciosArlette/Ejercicio13.swift | gpl-3.0 | 1 | /*
Palacios Lee Arlette 12211431
Programa para resolver el siguiente problema:
13. Determinar el área de un triángulo tomando un medio del producto de dos lados por el seno del ángulo comprendido.
*/
//Librería para utilizar funciones trigonométricas
import Foundation
//Declaración de variables
var a1: Float = 3 //Tamaño de uno de los lados
var b1: Float = 5 //Mitad del tamaño del lado más largo de triángulo
var ang1: Float = 60 //Ángulo formado por los lados
//Operaciones para calcular el área
var seno = sin(60.0 * Float.pi / 180) //Cálculo de seno del ángulo
var area = (1/2) * a1 * b1 * seno //Cálculo del área
//En una variable se guarda el problema y datos para imprimirlos posteriormente
var Problema = "\n" + "Problema:" + "\n" +
"13. Determinar el área de un triángulo tomando un medio del producto de dos lados por el seno del ángulo comprendido."
var Datos = "\n \n" + "Datos:" + "\n" + "Lado A: \(String(format:"%.0f", a1)) " + "\n" + "Lado B: \(String(format:"%.0f", b1))" + "\n" + "Ángulo: \(String(format:"%.0f", ang1))"
var Resultado ="\n \n" + "Resultado:" + "\n" + "(1/2) * \(String(format:"%.0f", a1)) * \(String(format:"%.0f", b1)) * Sen(\(String(format:"%.0f", ang1))) = \(area)cm^2"
//Despliegue de resultados
print(Problema, Datos, Resultado);
| 3430f35f32f7f4e9270d38362af8b977 | 44.37931 | 177 | 0.660334 | false | false | false | false |
DroidsOnRoids/PhotosHelper | refs/heads/master | PhotosHelper.swift | mit | 1 | //
// PhotosHelper.swift
//
import Photos
/**
Enum containing results of `getAssets(...)`, `getImages(...)` etc. calls. Depending on options can contain an array of assets or a single asset. Contains an empty error if something goes wrong.
- Assets: Contains an array of assets. Will be called only once.
- Asset: Contains a single asset. If options.synchronous is set to `false` can be called multiple times by the system.
- Error: Error fetching images.
*/
public enum AssetFetchResult<T> {
case Assets([T])
case Asset(T)
case Error
}
/**
* A set of methods to create albums, save and retrieve images using the Photos Framework.
*/
public struct PhotosHelper {
/**
* Define order, amount of assets and - if set - a target size. When count is set to zero all assets will be fetched. When size is not set original assets will be fetched.
*/
public struct FetchOptions {
public var count: Int
public var newestFirst: Bool
public var size: CGSize?
public init() {
self.count = 0
self.newestFirst = true
self.size = nil
}
}
/// Default options to pass when fetching images. Fetches only images from the device (not from iCloud), synchronously and in best quality.
public static var defaultImageFetchOptions: PHImageRequestOptions {
let options = PHImageRequestOptions()
options.version = .Original
options.deliveryMode = .HighQualityFormat
options.resizeMode = .None
options.networkAccessAllowed = false
options.synchronous = true
return options
}
/**
Create and return an album in the Photos app with a specified name. Won't overwrite if such an album already exist.
- parameter named: Name of the album.
- parameter completion: Called in the background when an album was created.
*/
public static func createAlbum(named: String, completion: (album: PHAssetCollection?) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
var placeholder: PHObjectPlaceholder?
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(named)
placeholder = createAlbumRequest.placeholderForCreatedAssetCollection
}) { success, error in
var album: PHAssetCollection?
if success {
let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([placeholder?.localIdentifier ?? ""], options: nil)
album = collectionFetchResult.firstObject as? PHAssetCollection
}
completion(album: album)
}
}
}
/**
Retrieve an album from the Photos app with a specified name. If no such album exists, creates and returns a new one.
- parameter named: Name of the album.
- parameter completion: Called in the background when an album was retrieved.
*/
public static func getAlbum(named: String, completion: (album: PHAssetCollection?) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", named)
let collections = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
if let album = collections.firstObject as? PHAssetCollection {
completion(album: album)
} else {
PhotosHelper.createAlbum(named) { album in
completion(album: album)
}
}
}
}
/**
Try to save an image to a Photos album with a specified name. If no such album exists, creates a new one.
- Important: The `error` parameter is only forwarded from the framework, if the image fails to save due to other reasons, even if the error is `nil` look at the `success` parameter which will be set to `false`.
- parameter image: Image to save.
- parameter named: Name of the album.
- parameter completion: Called in the background when the image was saved or in case of any error.
*/
public static func saveImage(image: UIImage, toAlbum named: String, completion: ((success: Bool, error: NSError?) -> ())? = nil) {
PhotosHelper.getAlbum(named, completion: { album in
guard let album = album else { completion?(success: false, error: nil); return; }
PhotosHelper.saveImage(image, to: album, completion: completion)
})
}
/**
Try to save an image to a Photos album.
- Important: The `error` parameter is only forwarded from the framework, if the image fails to save due to other reasons, even if the error is `nil` look at the `success` parameter which will be set to `false`.
- parameter image: Image to save.
- parameter completion: Called in the background when the image was saved or in case of any error.
*/
public static func saveImage(image: UIImage, to album: PHAssetCollection, completion: ((success: Bool, error: NSError?) -> ())? = nil) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
let placeholder = assetRequest.placeholderForCreatedAsset
guard let _placeholder = placeholder else { completion?(success: false, error: nil); return; }
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: album)
albumChangeRequest?.addAssets([_placeholder])
}) { success, error in
completion?(success: success, error: error)
}
}
}
/**
Try to retrieve images from a Photos album with a specified name.
- parameter named: Name of the album.
- parameter options: Define how the images will be fetched.
- parameter fetchOptions: Define order and amount of images.
- parameter completion: Called in the background when images were retrieved or in case of any error.
*/
public static func getImagesFromAlbum(named: String, options: PHImageRequestOptions = defaultImageFetchOptions, fetchOptions: FetchOptions = FetchOptions(), completion: (result: AssetFetchResult<UIImage>) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let albumFetchOptions = PHFetchOptions()
albumFetchOptions.predicate = NSPredicate(format: "(estimatedAssetCount > 0) AND (localizedTitle == %@)", named)
let albums = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: albumFetchOptions)
guard let album = albums.firstObject as? PHAssetCollection else { return completion(result: .Error) }
PhotosHelper.getImagesFromAlbum(album, options: options, completion: completion)
}
}
/**
Try to retrieve images from a Photos album.
- parameter options: Define how the images will be fetched.
- parameter fetchOptions: Define order and amount of images.
- parameter completion: Called in the background when images were retrieved or in case of any error.
*/
public static func getImagesFromAlbum(album: PHAssetCollection, options: PHImageRequestOptions = defaultImageFetchOptions, fetchOptions: FetchOptions = FetchOptions(), completion: (result: AssetFetchResult<UIImage>) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
PhotosHelper.getAssetsFromAlbum(album, fetchOptions: fetchOptions, completion: { result in
switch result {
case .Asset: ()
case .Error: completion(result: .Error)
case .Assets(let assets):
let imageManager = PHImageManager.defaultManager()
assets.forEach { asset in
imageManager.requestImageForAsset(
asset,
targetSize: fetchOptions.size ?? CGSize(width: asset.pixelWidth, height: asset.pixelHeight),
contentMode: .AspectFill,
options: options,
resultHandler: { image, _ in
guard let image = image else { return }
completion(result: .Asset(image))
})
}
}
})
}
}
/**
Try to retrieve assets from a Photos album.
- parameter options: Define how the assets will be fetched.
- parameter fetchOptions: Define order and amount of assets. Size is ignored.
- parameter completion: Called in the background when assets were retrieved or in case of any error.
*/
public static func getAssetsFromAlbum(album: PHAssetCollection, fetchOptions: FetchOptions = FetchOptions(), completion: (result: AssetFetchResult<PHAsset>) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let assetsFetchOptions = PHFetchOptions()
assetsFetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: !fetchOptions.newestFirst)]
var assets = [PHAsset]()
let fetchedAssets = PHAsset.fetchAssetsInAssetCollection(album, options: assetsFetchOptions)
let rangeLength = min(fetchedAssets.count, fetchOptions.count)
let range = NSRange(location: 0, length: fetchOptions.count != 0 ? rangeLength : fetchedAssets.count)
let indexes = NSIndexSet(indexesInRange: range)
fetchedAssets.enumerateObjectsAtIndexes(indexes, options: []) { asset, index, stop in
guard let asset = asset as? PHAsset else { return completion(result: .Error) }
assets.append(asset)
}
completion(result: .Assets(assets))
}
}
/**
Retrieve all albums from the Photos app.
- parameter completion: Called in the background when all albums were retrieved.
*/
public static func getAlbums(completion: (albums: [PHAssetCollection]) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "localizedTitle", ascending: true)]
let albums = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
let smartAlbums = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .Any, options: fetchOptions)
var result = Set<PHAssetCollection>()
[albums, smartAlbums].forEach {
$0.enumerateObjectsUsingBlock { collection, index, stop in
guard let album = collection as? PHAssetCollection else { return }
result.insert(album)
}
}
completion(albums: Array<PHAssetCollection>(result))
}
}
/**
Retrieve all user created albums from the Photos app.
- parameter completion: Called in the background when all albums were retrieved.
*/
public static func getUserCreatedAlbums(completion: (albums: [PHAssetCollection]) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "localizedTitle", ascending: true)]
let albums = PHCollectionList.fetchTopLevelUserCollectionsWithOptions(fetchOptions)
var result = [PHAssetCollection]()
albums.enumerateObjectsUsingBlock { collection, index, stop in
guard let album = collection as? PHAssetCollection else { return }
result.append(album)
}
completion(albums: result)
}
}
/**
Retrieve camera roll album the Photos app.
- parameter completion: Called in the background when the album was retrieved.
*/
public static func getCameraRollAlbum(completion: (album: PHAssetCollection?) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let albums = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .AlbumMyPhotoStream, options: nil)
completion(album: albums.firstObject as? PHAssetCollection)
}
}
}
| 64c8743de6f6919013862b19d29dc07e | 47.259928 | 228 | 0.631433 | false | false | false | false |
Bunn/firefox-ios | refs/heads/master | Sync/SyncTelemetryUtils.swift | mpl-2.0 | 2 | /* 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 Account
import Storage
import SwiftyJSON
import SyncTelemetry
fileprivate let log = Logger.syncLogger
public let PrefKeySyncEvents = "sync.telemetry.events"
public enum SyncReason: String {
case startup = "startup"
case scheduled = "scheduled"
case backgrounded = "backgrounded"
case user = "user"
case syncNow = "syncNow"
case didLogin = "didLogin"
case push = "push"
case engineEnabled = "engineEnabled"
case clientNameChanged = "clientNameChanged"
}
public enum SyncPingReason: String {
case shutdown = "shutdown"
case schedule = "schedule"
case idChanged = "idchanged"
}
public protocol Stats {
func hasData() -> Bool
}
private protocol DictionaryRepresentable {
func asDictionary() -> [String: Any]
}
public struct SyncUploadStats: Stats {
var sent: Int = 0
var sentFailed: Int = 0
public func hasData() -> Bool {
return sent > 0 || sentFailed > 0
}
}
extension SyncUploadStats: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
return [
"sent": sent,
"failed": sentFailed
]
}
}
public struct SyncDownloadStats: Stats {
var applied: Int = 0
var succeeded: Int = 0
var failed: Int = 0
var newFailed: Int = 0
var reconciled: Int = 0
public func hasData() -> Bool {
return applied > 0 ||
succeeded > 0 ||
failed > 0 ||
newFailed > 0 ||
reconciled > 0
}
}
extension SyncDownloadStats: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
return [
"applied": applied,
"succeeded": succeeded,
"failed": failed,
"newFailed": newFailed,
"reconciled": reconciled
]
}
}
public struct ValidationStats: Stats, DictionaryRepresentable {
let problems: [ValidationProblem]
let took: Int64
let checked: Int?
public func hasData() -> Bool {
return !problems.isEmpty
}
func asDictionary() -> [String: Any] {
var dict: [String: Any] = [
"problems": problems.map { $0.asDictionary() },
"took": took
]
if let checked = self.checked {
dict["checked"] = checked
}
return dict
}
}
public struct ValidationProblem: DictionaryRepresentable {
let name: String
let count: Int
func asDictionary() -> [String: Any] {
return ["name": name, "count": count]
}
}
public class StatsSession {
var took: Int64 = 0
var when: Timestamp?
private var startUptimeNanos: UInt64?
public func start(when: UInt64 = Date.now()) {
self.when = when
self.startUptimeNanos = DispatchTime.now().uptimeNanoseconds
}
public func hasStarted() -> Bool {
return startUptimeNanos != nil
}
public func end() -> Self {
guard let startUptime = startUptimeNanos else {
assertionFailure("SyncOperationStats called end without first calling start!")
return self
}
// Casting to Int64 should be safe since we're using uptime since boot in both cases.
// Convert to milliseconds as stated in the sync ping format
took = (Int64(DispatchTime.now().uptimeNanoseconds) - Int64(startUptime)) / 1000000
return self
}
}
// Stats about a single engine's sync.
public class SyncEngineStatsSession: StatsSession {
public var validationStats: ValidationStats?
private(set) var uploadStats: SyncUploadStats
private(set) var downloadStats: SyncDownloadStats
public init(collection: String) {
self.uploadStats = SyncUploadStats()
self.downloadStats = SyncDownloadStats()
}
public func recordDownload(stats: SyncDownloadStats) {
self.downloadStats.applied += stats.applied
self.downloadStats.succeeded += stats.succeeded
self.downloadStats.failed += stats.failed
self.downloadStats.newFailed += stats.newFailed
self.downloadStats.reconciled += stats.reconciled
}
public func recordUpload(stats: SyncUploadStats) {
self.uploadStats.sent += stats.sent
self.uploadStats.sentFailed += stats.sentFailed
}
}
extension SyncEngineStatsSession: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
var dict: [String: Any] = [
"took": took,
]
if downloadStats.hasData() {
dict["incoming"] = downloadStats.asDictionary()
}
if uploadStats.hasData() {
dict["outgoing"] = uploadStats.asDictionary()
}
if let validation = self.validationStats, validation.hasData() {
dict["validation"] = validation.asDictionary()
}
return dict
}
}
// Stats and metadata for a sync operation.
public class SyncOperationStatsSession: StatsSession {
public let why: SyncReason
public var uid: String?
public var deviceID: String?
fileprivate let didLogin: Bool
public init(why: SyncReason, uid: String, deviceID: String?) {
self.why = why
self.uid = uid
self.deviceID = deviceID
self.didLogin = (why == .didLogin)
}
}
extension SyncOperationStatsSession: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
let whenValue = when ?? 0
return [
"when": whenValue,
"took": took,
"didLogin": didLogin,
"why": why.rawValue
]
}
}
public enum SyncPingError: MaybeErrorType {
case failedToRestoreScratchpad
public var description: String {
switch self {
case .failedToRestoreScratchpad: return "Failed to restore Scratchpad from prefs"
}
}
}
public enum SyncPingFailureReasonName: String {
case httpError = "httperror"
case unexpectedError = "unexpectederror"
case sqlError = "sqlerror"
case otherError = "othererror"
}
public protocol SyncPingFailureFormattable {
var failureReasonName: SyncPingFailureReasonName { get }
}
public struct SyncPing: SyncTelemetryPing {
public private(set) var payload: JSON
public static func from(result: SyncOperationResult,
account: Account.FirefoxAccount,
remoteClientsAndTabs: RemoteClientsAndTabs,
prefs: Prefs,
why: SyncPingReason) -> Deferred<Maybe<SyncPing>> {
// Grab our token so we can use the hashed_fxa_uid and clientGUID from our scratchpad for
// our ping's identifiers
return account.syncAuthState.token(Date.now(), canBeExpired: false) >>== { (token, kSync) in
let scratchpadPrefs = prefs.branch("sync.scratchpad")
guard let scratchpad = Scratchpad.restoreFromPrefs(scratchpadPrefs, syncKeyBundle: KeyBundle.fromKSync(kSync)) else {
return deferMaybe(SyncPingError.failedToRestoreScratchpad)
}
var ping: [String: Any] = pingCommonData(
why: why,
hashedUID: token.hashedFxAUID,
hashedDeviceID: (scratchpad.clientGUID + token.hashedFxAUID).sha256.hexEncodedString
)
// TODO: We don't cache our sync pings so if it fails, it fails. Once we add
// some kind of caching we'll want to make sure we don't dump the events if
// the ping has failed.
let pickledEvents = prefs.arrayForKey(PrefKeySyncEvents) as? [Data] ?? []
let events = pickledEvents.compactMap(Event.unpickle).map { $0.toArray() }
ping["events"] = events
prefs.setObject(nil, forKey: PrefKeySyncEvents)
return dictionaryFrom(result: result, storage: remoteClientsAndTabs, token: token) >>== { syncDict in
// TODO: Split the sync ping metadata from storing a single sync.
ping["syncs"] = [syncDict]
return deferMaybe(SyncPing(payload: JSON(ping)))
}
}
}
static func pingCommonData(why: SyncPingReason, hashedUID: String, hashedDeviceID: String) -> [String: Any] {
return [
"version": 1,
"why": why.rawValue,
"uid": hashedUID,
"deviceID": hashedDeviceID,
"os": [
"name": "iOS",
"version": UIDevice.current.systemVersion,
"locale": Locale.current.identifier
]
]
}
// Generates a single sync ping payload that is stored in the 'syncs' list in the sync ping.
private static func dictionaryFrom(result: SyncOperationResult,
storage: RemoteClientsAndTabs,
token: TokenServerToken) -> Deferred<Maybe<[String: Any]>> {
return connectedDevices(fromStorage: storage, token: token) >>== { devices in
guard let stats = result.stats else {
return deferMaybe([String: Any]())
}
var dict = stats.asDictionary()
if let engineResults = result.engineResults.successValue {
dict["engines"] = SyncPing.enginePingDataFrom(engineResults: engineResults)
} else if let failure = result.engineResults.failureValue {
var errorName: SyncPingFailureReasonName
if let formattableFailure = failure as? SyncPingFailureFormattable {
errorName = formattableFailure.failureReasonName
} else {
errorName = .unexpectedError
}
dict["failureReason"] = [
"name": errorName.rawValue,
"error": "\(type(of: failure))",
]
}
dict["devices"] = devices
return deferMaybe(dict)
}
}
// Returns a list of connected devices formatted for use in the 'devices' property in the sync ping.
private static func connectedDevices(fromStorage storage: RemoteClientsAndTabs,
token: TokenServerToken) -> Deferred<Maybe<[[String: Any]]>> {
func dictionaryFrom(client: RemoteClient) -> [String: Any]? {
var device = [String: Any]()
if let os = client.os {
device["os"] = os
}
if let version = client.version {
device["version"] = version
}
if let guid = client.guid {
device["id"] = (guid + token.hashedFxAUID).sha256.hexEncodedString
}
return device
}
return storage.getClients() >>== { deferMaybe($0.compactMap(dictionaryFrom)) }
}
private static func enginePingDataFrom(engineResults: EngineResults) -> [[String: Any]] {
return engineResults.map { result in
let (name, status) = result
var engine: [String: Any] = [
"name": name
]
// For complete/partial results, extract out the collect stats
// and add it to engine information. For syncs that were not able to
// start, return why and a reason.
switch status {
case .completed(let stats):
engine.merge(with: stats.asDictionary())
case .partial(let stats):
engine.merge(with: stats.asDictionary())
case .notStarted(let reason):
engine.merge(with: [
"status": reason.telemetryId
])
}
return engine
}
}
}
| e3f4637b02d3f02a396cd395ff89a12b | 31.221622 | 129 | 0.595789 | false | false | false | false |
ObjectAlchemist/OOUIKit | refs/heads/master | Sources/View/Basic/ViewActivityIndicator.swift | mit | 1 | //
// ViewActivityIndicator.swift
// OOSwift
//
// Created by Karsten Litsche on 01.09.17.
//
//
import UIKit
import OOBase
/**
A view displaying an activity indicator.
*/
public final class ViewActivityIndicator: OOView {
// MARK: init
public init(action: OOExecutable = DoNothing(), shouldRun: OOBool = BoolConst(true), color: OOColor = ColorWhite, large: OOBool = BoolConst(true)) {
self.action = action
self.shouldRun = shouldRun
self.color = color
self.large = large
}
// MARK: protocol OOView
private var _ui: UIActivityIndicatorView?
public var ui: UIView {
if _ui == nil { _ui = createView() }
return _ui!
}
public func setNeedsRefresh() {
if _ui != nil { update(view: _ui!) }
_ui?.setNeedsLayout()
}
// MARK: private
private let action: OOExecutable
private let shouldRun: OOBool
private let color: OOColor
private let large: OOBool
private func createView() -> UIActivityIndicatorView {
let view = UIActivityIndicatorView(style: large.value ? .whiteLarge : .white)
update(view: view)
return view
}
private func update(view: UIActivityIndicatorView) {
view.style = large.value ? .whiteLarge : .white
view.color = color.value
if shouldRun.value {
view.startAnimating()
action.execute()
} else {
view.stopAnimating()
}
}
}
| f4c5e5760cc235e025417802be0805bf | 23.111111 | 152 | 0.596445 | false | false | false | false |
danielpi/Swift-Playgrounds | refs/heads/master | Swift-Playgrounds/Blogs/Swift Blog/2014-07-23-AccessControl.playground/section-1.swift | mit | 2 | // Playground - noun: a place where people can play
import Cocoa
import Foundation
public class ListItem {
// Public properties.
public var text: String
public var isComplete: Bool
// Readable throughout the module, but only writable from within this file.
private(set) var UUID: NSUUID
public init(text: String, completed: Bool, UUID: NSUUID) {
self.text = text
self.isComplete = completed
self.UUID = UUID
}
// Usable within the framework target, but not by other targets.
func refreshIdentity() {
self.UUID = NSUUID()
}
public func isEqual(object: AnyObject?) -> Bool {
if let item = object as? ListItem {
return self.UUID == item.UUID
}
return false
}
}
let item1 = ListItem(text: "Item 1", completed: false, UUID: NSUUID())
| beae6f5034568543780edd0cde383bb2 | 24.676471 | 79 | 0.619702 | false | false | false | false |
criticalmaps/criticalmaps-ios | refs/heads/main | CriticalMapsKit/Sources/SharedModels/NextRideFeature/Ride.swift | mit | 1 | import CoreLocation
import Foundation
import Helpers
import MapKit
public struct Ride: Hashable, Codable, Identifiable {
public let id: Int
public let slug: String?
public let title: String
public let description: String?
public let dateTime: Date
public let location: String?
public let latitude: Double?
public let longitude: Double?
public let estimatedParticipants: Int?
public let estimatedDistance: Double?
public let estimatedDuration: Double?
public let enabled: Bool
public let disabledReason: String?
public let disabledReasonMessage: String?
public let rideType: RideType?
public init(
id: Int,
slug: String? = nil,
title: String,
description: String? = nil,
dateTime: Date,
location: String? = nil,
latitude: Double? = nil,
longitude: Double? = nil,
estimatedParticipants: Int? = nil,
estimatedDistance: Double? = nil,
estimatedDuration: Double? = nil,
enabled: Bool,
disabledReason: String? = nil,
disabledReasonMessage: String? = nil,
rideType: Ride.RideType? = nil
) {
self.id = id
self.slug = slug
self.title = title
self.description = description
self.dateTime = dateTime
self.location = location
self.latitude = latitude
self.longitude = longitude
self.estimatedParticipants = estimatedParticipants
self.estimatedDistance = estimatedDistance
self.estimatedDuration = estimatedDuration
self.enabled = enabled
self.disabledReason = disabledReason
self.disabledReasonMessage = disabledReasonMessage
self.rideType = rideType
}
}
public extension Ride {
var coordinate: Coordinate? {
guard let lat = latitude, let lng = longitude else {
return nil
}
return Coordinate(latitude: lat, longitude: lng)
}
var titleAndTime: String {
let titleWithoutDate = title.removedDatePattern()
return """
\(titleWithoutDate)
\(rideDateAndTime)
"""
}
var rideDateAndTime: String {
"\(dateTime.humanReadableDate) - \(dateTime.humanReadableTime)"
}
var shareMessage: String {
guard let location = location else {
return titleAndTime
}
return """
\(titleAndTime)
\(location)
"""
}
}
public extension Ride {
func openInMaps(_ options: [String: Any] = [
MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDefault
]) {
guard let coordinate = coordinate else {
debugPrint("Coordinte is nil")
return
}
let placemark = MKPlacemark(coordinate: coordinate.asCLLocationCoordinate, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = location
mapItem.openInMaps(launchOptions: options)
}
}
public extension Ride {
enum RideType: String, CaseIterable, Codable {
case criticalMass = "CRITICAL_MASS"
case kidicalMass = "KIDICAL_MASS"
case nightride = "NIGHT_RIDE"
case lunchride = "LUNCH_RIDE"
case dawnride = "DAWN_RIDE"
case duskride = "DUSK_RIDE"
case demonstration = "DEMONSTRATION"
case alleycat = "ALLEYCAT"
case tour = "TOUR"
case event = "EVENT"
public var title: String {
rawValue
.replacingOccurrences(of: "_", with: " ")
.capitalized
}
}
}
| 511ac689ae03718c229fdc03339bec3a | 25.414634 | 102 | 0.687904 | false | false | false | false |
prolificinteractive/Caishen | refs/heads/master | Pod/Classes/Localization.swift | mit | 1 | //
// Localization.swift
// Pods
//
// Created by Shiyuan Jiang on 4/7/16.
//
//
import Foundation
/**
Enum to provide constants for localized strings in caishen, as well as convenience methods to localize the respective strings.
*/
internal enum Localization: String {
case StringsFileName = "Localizable"
case AccessoryButtonAccessibilityLabel = "ACCESSORY_BUTTON_ACCESSIBILITY_LABEL"
case NumberInputTextFieldAccessibilityLabel = "NUMBER_INPUT_TEXTFIELD_ACCESSIBILITY_LABEL"
case MonthInputTextFieldAccessibilityLabel = "MONTH_INPUT_TEXTFIELD_ACCESSIBILITY_LABEL"
case YearInputTextFieldAccessibilityLabel = "YEAR_INPUT_TEXTFIELD_ACCESSIBILITY_LABEL"
case CVCInputTextFieldAccessibilityLabel = "CVC_TEXTFIELD_ACCESSIBILITY_LABEL"
case InvalidCardNumber = "INVALID_CARD_NUMBER"
case InvalidExpirationDate = "INVALID_EXPIRATION_DATE"
case CardType = "CARD_TYPE"
/**
- parameter textField: The text field whose accessibility label should be retreived.
- parameter comment: An optional comment for the localization.
- returns: The accessibility label for the provided text field.
*/
static func accessibilityLabel(for textField: UITextField, with comment: String? = nil) -> String? {
switch textField {
case is NumberInputTextField:
return Localization.NumberInputTextFieldAccessibilityLabel.localizedStringWithComment(comment)
case is CVCInputTextField:
return Localization.CVCInputTextFieldAccessibilityLabel.localizedStringWithComment(comment)
case is MonthInputTextField:
return Localization.MonthInputTextFieldAccessibilityLabel.localizedStringWithComment(comment)
case is YearInputTextField:
return Localization.YearInputTextFieldAccessibilityLabel.localizedStringWithComment(comment)
default:
return nil
}
}
/**
- parameter comment: An optional comment for the localization.
- returns: The localized string for the raw value of `self` in the Caishen bundle.
*/
func localizedStringWithComment(_ comment: String?) -> String {
return NSLocalizedString(self.rawValue,
tableName: Localization.StringsFileName.rawValue,
bundle: Bundle(for: CardTextField.self),
comment: comment ?? "")
}
}
| 0ad96066118bc6a66c3efdb791e2aaf7 | 41.068966 | 127 | 0.706148 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat.ShareExtension/Compose/SEComposeHeaderViewController.swift | mit | 1 | //
// SEComposeViewController.swift
// Rocket.Chat.ShareExtension
//
// Created by Matheus Cardoso on 3/1/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
class SEComposeHeaderViewController: SEViewController {
@IBOutlet weak var doneButton: UIBarButtonItem!
@IBOutlet weak var destinationContainerView: UIView!
@IBOutlet weak var destinationLabel: UILabel!
@IBOutlet weak var destinationToLabel: UILabel!
@IBOutlet weak var containerView: UIView!
var viewModel = SEComposeHeaderViewModel.emptyState {
didSet {
title = viewModel.title
destinationLabel.text = viewModel.destinationText
doneButton.title = viewModel.doneButtonTitle
navigationItem.hidesBackButton = !viewModel.backButtonEnabled
if viewModel.showsActivityIndicator {
activityIndicator.isHidden = false
activityIndicator.startAnimating()
} else {
activityIndicator.isHidden = true
activityIndicator.stopAnimating()
}
}
}
override func viewDidLoad() {
avoidsKeyboard = false
}
override func stateUpdated(_ state: SEState) {
super.stateUpdated(state)
viewModel = SEComposeHeaderViewModel(state: state)
}
@IBAction func doneButtonPressed(_ sender: Any) {
switch viewModel.doneButtonState {
case .send:
store.dispatch(submitContent)
case .cancel:
store.dispatch(cancelSubmittingContent)
}
}
}
| 2a2bbd01c0fd0fb2c564f1234218432c | 29.442308 | 73 | 0.654454 | false | false | false | false |
adamkaplan/swifter | refs/heads/master | Swifter/PartialFunctionPlayground.playground/section-1.swift | apache-2.0 | 1 | // Playground - noun: a place where people can play
//
// PartialFunction.swift
// Swifter
//
// Created by Adam Kaplan on 6/3/14.
// Copyright (c) 2014 Yahoo!. All rights reserved.
//
import Foundation
enum DefinedResult<Z> {
case Defined(Z)
case Undefined
}
@objc class PartialFunction<A,B> {
typealias PF = PartialFunction<A,B>
typealias Z = B // The final return type, provided to be overriden
typealias DefaultPF = PartialFunction<A,Z>
let applyOrCheck: (A, Bool) -> DefinedResult<Z>
init(f: (A, Bool) -> DefinedResult<Z>) {
self.applyOrCheck = f
}
func apply(a: A) -> B? {
switch applyOrCheck(a, false) {
case .Defined(let p):
return p
case .Undefined:
return nil
}
}
/* Applies this PartialFunction to `a`, and in the case that 'a' is undefined
* for the function, applies defaultPF to `a`. */
func applyOrElse(a: A, defaultPF: DefaultPF) -> Z? {
switch applyOrCheck(a, false) {
case .Defined(let p):
return p
default:
return defaultPF.apply(a)
}
}
/* Returns true if this PartialFunction can be applied to `a` */
func isDefinedAt(a: A) -> Bool {
switch applyOrCheck(a, true) {
case .Defined(_):
return true
case .Undefined:
return false
}
}
func orElse(otherPF: PF) -> PF {
return OrElse(f1: self, f2: otherPF)
}
func andThen<C>(nextPF: PartialFunction<B,C>) -> PartialFunction<A,C> {
return AndThen<A,B,C>(f1: self, f2: nextPF)
}
// // class constants are not yet available with generic classes
// class let null: PartialFunction<Any,Any> = PartialFunction( { _ in .Undefined } )
// class let iden: PartialFunction<A,A> = PartialFunction( { .Defined($0.0) } )
}
/* TODO: make this private. Apple has promised Swift will get access modifiers */
class OrElse<A,B> : PartialFunction<A,B> {
let f1, f2: PF
init(f1: PF, f2: PF) {
self.f1 = f1
self.f2 = f2
super.init( { [unowned self] (a, checkOnly) in
let result1 = self.f1.applyOrCheck(a, checkOnly)
switch result1 {
case .Defined(_):
return result1
case .Undefined:
return self.f2.applyOrCheck(a, checkOnly)
}
})
}
override func isDefinedAt(a: A) -> Bool {
return f1.isDefinedAt(a) || f2.isDefinedAt(a)
}
override func orElse(f3: PF) -> PF {
return OrElse(f1: f1, f2: f2.orElse(f3))
}
override func applyOrElse(a: A, defaultPF: PF) -> B? {
switch f1.applyOrCheck(a, false) {
case .Defined(let result1):
return result1
default:
return f2.applyOrElse(a, defaultPF: defaultPF)
}
}
override func andThen<C>(nextPF: PartialFunction<B,C>) -> PartialFunction<A,C> {
return OrElse<A,C>(
f1: AndThen<A,B,C>(f1: f1, f2: nextPF),
f2: AndThen<A,B,C>(f1: f2, f2: nextPF))
}
}
/* TODO: make this private. Apple has promised Swift will get access modifiers */
class AndThen<A,B,C> : PartialFunction<A,C> {
typealias NextPF = PartialFunction<B,C>
typealias Z = C
let f1: PartialFunction<A,B>
let f2: NextPF
init(f1: PartialFunction<A,B>, f2: NextPF) {
self.f1 = f1
self.f2 = f2
super.init( { [unowned self] (a, checkOnly) in
let result1 = self.f1.applyOrCheck(a, checkOnly)
switch result1 {
case .Defined(let r1):
let result2 = f2.applyOrCheck(r1, checkOnly)
switch result2 {
case .Defined(_):
return result2
case .Undefined:
return .Undefined
}
case .Undefined:
return .Undefined
}
})
}
override func applyOrElse(a: A, defaultPF: DefaultPF) -> Z? {
switch self.applyOrCheck(a, false) {
case .Defined(let result):
return result
case .Undefined:
return defaultPF.apply(a)
}
}
}
/* Creates a PartialFunction from body for a specific domain. */
operator infix =|= {precedence 255}
@infix func =|= <A,B> (domain: ((a: A) -> Bool), body: ((a: A) -> B)) -> PartialFunction<A,B> {
return PartialFunction<A,B>( { (a: A, _) in
if domain(a:a) {
return .Defined(body(a: a))
} else {
return .Undefined
}
})
}
/* Joins two PartialFunctions via PartialFunction.andThen(). */
operator infix => {precedence 128 associativity left}
@infix func => <A,B,C> (pf: PartialFunction<A, B>, nextPF: PartialFunction<B,C>) -> PartialFunction<A,C>{
return pf.andThen(nextPF)
}
/* Joins two PartialFunctions via PartialFunction.orElse(). */
operator infix | {precedence 64 associativity left}
@infix func | <A,B> (pf: PartialFunction<A,B>, otherPF: PartialFunction<A,B>) -> PartialFunction<A,B> {
return pf.orElse(otherPF)
}
/* Applies a value to the PartialFunction. */
operator infix ~|> {precedence 32}
@infix func ~|> <A,B> (value: A, pf: PartialFunction<A,B>) -> B? {
return pf.apply(value)
}
extension Array {
func collect<B>(pf: PartialFunction<T,B>) -> Array<B> {
return (self.filter(pf.isDefinedAt)).map { pf.apply($0)! }
}
}
let sample = [0, 1, 2, 3, 4, 5, 6, 7, 8]
let acceptEven = PartialFunction<Int, Int> { (i: Int, _) in
if i % 2 == 0 {
return .Defined(i)
} else {
return .Undefined
}
}
sample.filter(acceptEven.isDefinedAt)
sample.collect(acceptEven)
let acceptOdd = PartialFunction<Int, Int> { (i: Int, _) in
if i % 2 != 0 {
return .Defined(i)
} else {
return .Undefined
}
}
sample.filter(acceptOdd.isDefinedAt)
let acceptNaturalNumbers = acceptEven.orElse(acceptOdd)
sample.filter(acceptNaturalNumbers.isDefinedAt)
let acceptNoNaturalNumbers = acceptEven.andThen(acceptOdd);
sample.filter(acceptNoNaturalNumbers.isDefinedAt)
sample.collect(acceptNoNaturalNumbers)
operator infix /~ {}
@infix func /~ (num: Int, denom: Int) -> Int? {
let divide = PartialFunction<(Int, Int), Int>( { (ints: (Int, Int), _) in
let (num, denom) = ints
if denom != 0 {
return .Defined(num/denom)
} else {
return .Undefined
}
})
return divide.apply(num, denom)
}
6 /~ 00
6 /~ 05
6 /~ 15
// match with
// | n when n % 2 == 0 && n <= 10 -> Some +n
// | n when n % 2 != 0 && n <= 10 -> Some -n
// | _ -> None
let patt1: PartialFunction<Int,Int> = { $0 % 2 == 0 && $0 <= 10 } =|= { +$0 }
let patt2: PartialFunction<Int,Int> = { $0 % 2 != 0 && $0 <= 10 } =|= { -$0 }
-5 ~|> patt1 | patt2
04 ~|> patt1 | patt2
10 ~|> patt1 | patt2
11 ~|> patt1 | patt2
| ed5a0cd4fae6341d2b52516447667823 | 25.97318 | 105 | 0.560511 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-duplicates/06274-swift-constraints-constraintsystem-getfixedtyperecursive.swift | mit | 11 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b<f = f : e(f<T where T) -> {
enum e {
class B == {
println(f<T where h: Int -> U)"\() { p(T.c>
func b
let i: NSManagedObject {
func e<T where T.b<T where g: B<Q
S<I : T.h == {
var f = b
}
var f {
switch x }
1
| 76625a22517ab0f54f53cfc3200d33da | 21.588235 | 87 | 0.643229 | false | true | false | false |
Pretz/SwiftGraphics | refs/heads/develop | Demos/SwiftGraphics_OSX_Scratch/Scratch.swift | bsd-2-clause | 2 | //
// Scratch.swift
// SwiftGraphics
//
// Created by Jonathan Wight on 1/26/15.
// Copyright (c) 2015 schwa.io. All rights reserved.
//
import SwiftGraphics
import SwiftUtilities
// MARK: -
var kUserInfoKey: Int = 0
extension NSToolbarItem {
var userInfo: AnyObject? {
get {
return getAssociatedObject(self, key: &kUserInfoKey)
}
set {
// TODO: What about nil
setAssociatedObject(self, key: &kUserInfoKey, value: newValue!)
}
}
}
extension NSMenuItem {
var userInfo: AnyObject? {
get {
return getAssociatedObject(self, key: &kUserInfoKey)
}
set {
// TODO: What about nil
setAssociatedObject(self, key: &kUserInfoKey, value: newValue!)
}
}
}
// MARK: -
extension NSGestureRecognizerState: CustomStringConvertible {
public var description: String {
switch self {
case .Possible:
return "Possible"
case .Began:
return "Began"
case .Changed:
return "Changed"
case .Ended:
return "Ended"
case .Cancelled:
return "Cancelled"
case .Failed:
return "Failed"
}
}
}
// MARK: -
extension Array {
func isSorted(isEqual: (T, T) -> Bool, isOrderedBefore: (T, T) -> Bool) -> Bool {
let sortedCopy = sort(isOrderedBefore)
for (lhs, rhs) in Zip2(self, sortedCopy) {
if isEqual(lhs, rhs) == false {
return false
}
}
return true
}
mutating func insert(newElement: T, orderedBefore: (T, T) -> Bool) {
for (index, element) in self.enumerate() {
if orderedBefore(newElement, element) {
insert(newElement, atIndex: index)
return
}
}
append(newElement)
}
}
//extension Array {
// mutating func removeObjectsAtIndices(indices: NSIndexSet) {
// var index = indices.lastIndex
//
// while index != NSNotFound {
// removeAtIndex(index)
// index = indices.indexLessThanIndex(index)
// }
// }
//}
// MARK: -
extension NSIndexSet {
func with <T>(array: Array <T>, maxCount: Int = 512, block: Array <T> -> Void) {
with(maxCount) {
(buffer: UnsafeBufferPointer<Int>) -> Void in
var items: Array <T> = []
for index in buffer {
items.append(array[index])
}
block(items)
}
}
func with(maxCount: Int = 512, block: UnsafeBufferPointer <Int> -> Void) {
var range = NSMakeRange(0, count)
var indices = Array <Int> (count: maxCount, repeatedValue: NSNotFound)
indices.withUnsafeMutableBufferPointer() {
(inout buffer: UnsafeMutableBufferPointer<Int>) -> Void in
var count = 0
repeat {
count = self.getIndexes(buffer.baseAddress, maxCount: maxCount, inIndexRange: &range)
if count > 0 {
let constrained_buffer = UnsafeBufferPointer<Int> (start: buffer.baseAddress, count: count)
block(constrained_buffer)
}
}
while count > 0
}
}
} | 96d2efeca807ab823358e5f6f4a30cc3 | 25.03876 | 111 | 0.533055 | false | false | false | false |
paulo17/Find-A-Movie-iOS | refs/heads/master | Try.playground/Contents.swift | gpl-2.0 | 1 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
struct MovieDbApi {
let apiKey = "061aa72cb2da19956a42cf429bbe0e0d"
let apiUrl = "http://api.themoviedb.org/3/"
func baseUrl() -> NSURL {
return NSURL(string: "\(apiUrl)")!
}
}
import XCPlayground
let genre = NSURL(string: "genre/movie/list?api_key=\(MovieDbApi().apiKey)", relativeToURL: MovieDbApi().baseUrl())!
let request = NSMutableURLRequest(URL: genre)
request.addValue("application/json", forHTTPHeaderField: "Accept")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) in
if error != nil {
// Handle error...
return
}
print(error)
print(response)
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
}
task.resume()
func doubler(i: Int) -> Int {
return i * 2
}
let numbers = [1,2,3,4,5]
let doubleFunction = doubler
let doubledNumbers = numbers.map(doubleFunction)
// using closure
let tripledNumbers = numbers.map({ (i: Int) -> Int in return i * 3})
// Closure Shorthand Syntax
let tripleFunction = { (i: Int) -> Int in return i * 3 }
numbers.map(tripleFunction)
//////////////////////////////
// Closure Shorthand Syntax //
//////////////////////////////
// Rule #1
[1,2,3,4,5].map({ (i: Int) -> Int in return i * 3 })
// Rule #2: Infering Type from Context
[1,2,3,4,5].map({i in return i * 3})
// Rule #3: Implicit Return from Single Expression Closures
[1,2,3,4,5].map({i in i * 3})
// Rule #4: Shorthand Argument Names
[1,2,3,4,5].map({$0 * 3})
// Rule #5: Trailing Closures
[1,2,3,4,5].map() {$0 * 3}
// Rule #6: Ignoring Parentheses
[1,2,3,4,5].map {$0 * 3}
var arrayTest = [12,25,33,40,25]
if !arrayTest.contains(1222){
print("yes")
}
arrayTest.indexOf(33)
print(arrayTest)
var genres = [222,32,176,9,7]
var test = genres.generate()
test.next()
test.next()
test.next()
var genresString: [String] = []
for genre in genres {
genresString.append(String(genre))
}
genresString.joinWithSeparator(",")
func testparam(name: String = "Paul") -> String {
return name
}
testparam("adrien")
var current_page = 3
var max_page = 7
let page = (++current_page <= max_page) ? current_page : 1
NSBundle.mainBundle().objectForInfoDictionaryKey("api_base_url")
| 4a2b79104a32b8e6e023af88f06aa7a7 | 17.744186 | 116 | 0.637304 | false | true | false | false |
ps2/rileylink_ios | refs/heads/dev | OmniKitUI/Views/DesignElements/LeadingImage.swift | mit | 1 | //
// LeadingImage.swift
// OmniKit
//
// Created by Pete Schwamb on 3/12/20.
// Copyright © 2021 LoopKit Authors. All rights reserved.
//
import SwiftUI
struct LeadingImage: View {
var name: String
static let compactScreenImageHeight: CGFloat = 70
static let regularScreenImageHeight: CGFloat = 150
@Environment(\.verticalSizeClass) var verticalSizeClass
init(_ name: String) {
self.name = name
}
var body: some View {
Image(frameworkImage: self.name, decorative: true)
.resizable()
.aspectRatio(contentMode: ContentMode.fit)
.frame(height: self.verticalSizeClass == .compact ? LeadingImage.compactScreenImageHeight : LeadingImage.regularScreenImageHeight)
.padding(.vertical, self.verticalSizeClass == .compact ? 0 : nil)
}
}
struct LeadingImage_Previews: PreviewProvider {
static var previews: some View {
LeadingImage("Pod")
}
}
| 100e1e36df6c867ed67ea8ac6ed81044 | 25.297297 | 142 | 0.659815 | false | false | false | false |
kirthika/AuthenticationLibrary | refs/heads/master | Carthage/Checkouts/KeychainAccess/Examples/Example-iOS/Example-iOS/InputViewController.swift | mit | 2 | //
// InputViewController.swift
// Example
//
// Created by kishikawa katsumi on 2014/12/26.
// Copyright (c) 2014 kishikawa katsumi. 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 UIKit
import KeychainAccess
class InputViewController: UITableViewController {
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var cancelButton: UIBarButtonItem!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var serviceField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 44.0
tableView.estimatedRowHeight = 44.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK:
@IBAction func cancelAction(sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
@IBAction func saveAction(sender: UIBarButtonItem) {
let keychain: Keychain
if let service = serviceField.text, !service.isEmpty {
keychain = Keychain(service: service)
} else {
keychain = Keychain()
}
keychain[usernameField.text!] = passwordField.text
dismiss(animated: true, completion: nil)
}
@IBAction func editingChanged(sender: UITextField) {
switch (usernameField.text, passwordField.text) {
case let (username?, password?):
saveButton.isEnabled = !username.isEmpty && !password.isEmpty
case (_?, nil):
saveButton.isEnabled = false
case (nil, _?):
saveButton.isEnabled = false
case (nil, nil):
saveButton.isEnabled = false
}
}
}
| 282a8addadbb0ea0f2d1190ef0f39e0c | 33.7125 | 80 | 0.693554 | false | false | false | false |
danger/danger-swift | refs/heads/master | Sources/Danger/GitLabDSL.swift | mit | 1 | import Foundation
// swiftlint:disable nesting
public struct GitLab: Decodable {
public enum CodingKeys: String, CodingKey {
case mergeRequest = "mr"
case metadata
}
public let mergeRequest: MergeRequest
public let metadata: Metadata
}
public extension GitLab {
struct Metadata: Decodable, Equatable {
public let pullRequestID: String
public let repoSlug: String
}
}
public extension GitLab {
struct MergeRequest: Decodable, Equatable {
public enum State: String, Decodable {
case closed
case locked
case merged
case opened
}
public struct Milestone: Decodable, Equatable {
public enum ParentIdentifier: Equatable {
case group(Int)
case project(Int)
// MARK: Local error enum
enum Error: LocalizedError {
case validKeyNotFound
// MARK: LocalizedError
var errorDescription: String? {
"Not able to find `group_id` or `project_id` from the raw JSON"
}
}
// MARK: Helpers
public var id: Int {
switch self {
case let .group(id), let .project(id):
return id
}
}
public var isGroup: Bool {
if case .group = self {
return true
} else {
return false
}
}
public var isProject: Bool {
!isGroup
}
}
public enum CodingKeys: String, CodingKey {
case createdAt = "created_at"
case description
case dueDate = "due_date"
case id
case iid
case projectId = "project_id"
case groupId = "group_id"
case startDate = "start_date"
case state
case title
case updatedAt = "updated_at"
case webUrl = "web_url"
}
public enum State: String, Decodable {
case active
case closed
}
public let createdAt: Date
public let description: String
public let dueDate: Date?
public let id: Int
public let iid: Int
/// An unified identifier for [project milestone](https://docs.gitlab.com/ee/api/milestones.html)'s `project_id` \
/// and [group milestone](https://docs.gitlab.com/ee/api/group_milestones.html)'s `group_id`.
public let parent: ParentIdentifier
public let startDate: Date?
public let state: State
public let title: String
public let updatedAt: Date
public let webUrl: String
}
public struct TimeStats: Decodable, Equatable {
public enum CodingKeys: String, CodingKey {
case humanTimeEstimate = "human_time_estimate"
case humanTimeSpent = "human_total_time_spent"
case timeEstimate = "time_estimate"
case totalTimeSpent = "total_time_spent"
}
public let humanTimeEstimate: Int?
public let humanTimeSpent: Int?
public let timeEstimate: Int
public let totalTimeSpent: Int
}
struct UserMergeData: Decodable, Equatable {
enum CodingKeys: String, CodingKey {
case canMerge = "can_merge"
}
let canMerge: Bool
}
public struct DiffRefs: Decodable, Equatable {
enum CodingKeys: String, CodingKey {
case baseSha = "base_sha"
case headSha = "head_sha"
case startSha = "start_sha"
}
let baseSha: String
let headSha: String
let startSha: String
}
public struct Pipeline: Decodable, Equatable {
public enum Status: String, Decodable {
case canceled
case failed
case pending
case running
case skipped
case success
}
public enum CodingKeys: String, CodingKey {
case id
case ref
case sha
case status
case webUrl = "web_url"
}
public let id: Int
public let ref: String
public let sha: String
public let status: Status
public let webUrl: String
}
public enum CodingKeys: String, CodingKey {
case allowCollaboration = "allow_collaboration"
case allowMaintainerToPush = "allow_maintainer_to_push"
case approvalsBeforeMerge = "approvals_before_merge"
case assignee
case assignees
case author
case changesCount = "changes_count"
case closedAt = "closed_at"
case closedBy = "closed_by"
case description
case diffRefs = "diff_refs"
case downvotes
case firstDeployedToProductionAt = "first_deployed_to_production_at"
case forceRemoveSourceBranch = "force_remove_source_branch"
case id
case iid
case latestBuildStartedAt = "latest_build_started_at"
case latestBuildFinishedAt = "latest_build_finished_at"
case labels
case mergeCommitSha = "merge_commit_sha"
case mergedAt = "merged_at"
case mergedBy = "merged_by"
case mergeOnPipelineSuccess = "merge_when_pipeline_succeeds"
case milestone
case pipeline
case projectId = "project_id"
case sha
case shouldRemoveSourceBranch = "should_remove_source_branch"
case sourceBranch = "source_branch"
case sourceProjectId = "source_project_id"
case state
case subscribed
case targetBranch = "target_branch"
case targetProjectId = "target_project_id"
case timeStats = "time_stats"
case title
case upvotes
case userMergeData = "user"
case userNotesCount = "user_notes_count"
case webUrl = "web_url"
case workInProgress = "work_in_progress"
}
public let allowCollaboration: Bool?
public let allowMaintainerToPush: Bool?
public let approvalsBeforeMerge: Int?
public let assignee: User?
public let assignees: [User]?
public let author: User
public let changesCount: String
public let closedAt: Date?
public let closedBy: User?
public let description: String
public let diffRefs: DiffRefs
public let downvotes: Int
public let firstDeployedToProductionAt: Date?
public let forceRemoveSourceBranch: Bool?
public let id: Int
public let iid: Int
public let latestBuildFinishedAt: Date?
public let latestBuildStartedAt: Date?
public let labels: [String]
public let mergeCommitSha: String?
public let mergedAt: Date?
public let mergedBy: User?
public let mergeOnPipelineSuccess: Bool
public let milestone: Milestone?
public let pipeline: Pipeline?
public let projectId: Int
public let sha: String
public let shouldRemoveSourceBranch: Bool?
public let sourceBranch: String
public let sourceProjectId: Int
public let state: State
public let subscribed: Bool
public let targetBranch: String
public let targetProjectId: Int
public let timeStats: TimeStats
public let title: String
public let upvotes: Int
public let userNotesCount: Int
public let webUrl: String
public let workInProgress: Bool
let userMergeData: UserMergeData
public var userCanMerge: Bool {
userMergeData.canMerge
}
}
}
public extension GitLab {
struct User: Decodable, Equatable {
public enum CodingKeys: String, CodingKey {
case avatarUrl = "avatar_url"
case id
case name
case state
case username
case webUrl = "web_url"
}
public enum State: String, Decodable {
case active
case blocked
}
public let avatarUrl: String?
public let id: Int
public let name: String
public let state: State
public let username: String
public let webUrl: String
}
}
// MARK: Custom decoder for Milestone
public extension GitLab.MergeRequest.Milestone {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let id = try container.decodeIfPresent(Int.self, forKey: .groupId) {
parent = .group(id)
} else if let id = try container.decodeIfPresent(Int.self, forKey: .projectId) {
parent = .project(id)
} else {
throw ParentIdentifier.Error.validKeyNotFound
}
createdAt = try container.decode(Date.self, forKey: .createdAt)
description = try container.decode(String.self, forKey: .description)
dueDate = try container.decode(Date?.self, forKey: .dueDate)
id = try container.decode(Int.self, forKey: .id)
iid = try container.decode(Int.self, forKey: .iid)
startDate = try container.decode(Date?.self, forKey: .startDate)
state = try container.decode(State.self, forKey: .state)
title = try container.decode(String.self, forKey: .title)
updatedAt = try container.decode(Date.self, forKey: .updatedAt)
webUrl = try container.decode(String.self, forKey: .webUrl)
}
}
| 4bd68ec633425da52d97b2d70554d729 | 32.299674 | 126 | 0.552578 | false | false | false | false |
taoguan/firefox-ios | refs/heads/master | Client/Frontend/Browser/URLBarView.swift | mpl-2.0 | 2 | /* 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 SnapKit
private struct URLBarViewUX {
static let TextFieldBorderColor = UIColor(rgb: 0xBBBBBB)
static let TextFieldActiveBorderColor = UIColor(rgb: 0x4A90E2)
static let TextFieldContentInset = UIOffsetMake(9, 5)
static let LocationLeftPadding = 5
static let LocationHeight = 28
static let LocationContentOffset: CGFloat = 8
static let TextFieldCornerRadius: CGFloat = 3
static let TextFieldBorderWidth: CGFloat = 1
// offset from edge of tabs button
static let URLBarCurveOffset: CGFloat = 14
static let URLBarCurveOffsetLeft: CGFloat = -10
// buffer so we dont see edges when animation overshoots with spring
static let URLBarCurveBounceBuffer: CGFloat = 8
static let TabsButtonRotationOffset: CGFloat = 1.5
static let TabsButtonHeight: CGFloat = 18.0
static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
static func backgroundColorWithAlpha(alpha: CGFloat) -> UIColor {
return UIConstants.AppBackgroundColor.colorWithAlphaComponent(alpha)
}
}
protocol URLBarDelegate: class {
func urlBarDidPressTabs(urlBar: URLBarView)
func urlBarDidPressReaderMode(urlBar: URLBarView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool
func urlBarDidPressStop(urlBar: URLBarView)
func urlBarDidPressReload(urlBar: URLBarView)
func urlBarDidEnterOverlayMode(urlBar: URLBarView)
func urlBarDidLeaveOverlayMode(urlBar: URLBarView)
func urlBarDidLongPressLocation(urlBar: URLBarView)
func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]?
func urlBarDidPressScrollToTop(urlBar: URLBarView)
func urlBar(urlBar: URLBarView, didEnterText text: String)
func urlBar(urlBar: URLBarView, didSubmitText text: String)
}
class URLBarView: UIView {
weak var delegate: URLBarDelegate?
weak var browserToolbarDelegate: BrowserToolbarDelegate?
var helper: BrowserToolbarHelper?
var isTransitioning: Bool = false {
didSet {
if isTransitioning {
// Cancel any pending/in-progress animations related to the progress bar
self.progressBar.setProgress(1, animated: false)
self.progressBar.alpha = 0.0
}
}
}
var toolbarIsShowing = false
/// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown,
/// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode
/// is *not* tied to the location text field's editing state; for instance, when selecting
/// a panel, the first responder will be resigned, yet the overlay mode UI is still active.
var inOverlayMode = false
lazy var locationView: BrowserLocationView = {
let locationView = BrowserLocationView()
locationView.translatesAutoresizingMaskIntoConstraints = false
locationView.readerModeState = ReaderModeState.Unavailable
locationView.delegate = self
return locationView
}()
private lazy var locationTextField: ToolbarTextField = {
let locationTextField = ToolbarTextField()
locationTextField.translatesAutoresizingMaskIntoConstraints = false
locationTextField.autocompleteDelegate = self
locationTextField.keyboardType = UIKeyboardType.WebSearch
locationTextField.autocorrectionType = UITextAutocorrectionType.No
locationTextField.autocapitalizationType = UITextAutocapitalizationType.None
locationTextField.returnKeyType = UIReturnKeyType.Go
locationTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
locationTextField.backgroundColor = UIColor.whiteColor()
locationTextField.font = UIConstants.DefaultMediumFont
locationTextField.accessibilityIdentifier = "address"
locationTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.")
locationTextField.attributedPlaceholder = self.locationView.placeholder
return locationTextField
}()
private lazy var locationContainer: UIView = {
let locationContainer = UIView()
locationContainer.translatesAutoresizingMaskIntoConstraints = false
// Enable clipping to apply the rounded edges to subviews.
locationContainer.clipsToBounds = true
locationContainer.layer.borderColor = URLBarViewUX.TextFieldBorderColor.CGColor
locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius
locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth
return locationContainer
}()
private lazy var tabsButton: UIButton = {
let tabsButton = InsetButton()
tabsButton.translatesAutoresizingMaskIntoConstraints = false
tabsButton.setTitle("0", forState: UIControlState.Normal)
tabsButton.setTitleColor(URLBarViewUX.backgroundColorWithAlpha(1), forState: UIControlState.Normal)
tabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor
tabsButton.titleLabel?.layer.cornerRadius = 2
tabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold
tabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
tabsButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
tabsButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the tabs button in the browser toolbar")
return tabsButton
}()
private lazy var progressBar: UIProgressView = {
let progressBar = UIProgressView()
progressBar.progressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1)
progressBar.alpha = 0
progressBar.hidden = true
return progressBar
}()
private lazy var cancelButton: UIButton = {
let cancelButton = InsetButton()
cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
let cancelTitle = NSLocalizedString("Cancel", comment: "Button label to cancel entering a URL or search query")
cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal)
cancelButton.titleLabel?.font = UIConstants.DefaultMediumFont
cancelButton.addTarget(self, action: "SELdidClickCancel", forControlEvents: UIControlEvents.TouchUpInside)
cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12)
cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
return cancelButton
}()
private lazy var curveShape: CurveView = { return CurveView() }()
private lazy var scrollToTopButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: "SELtappedScrollToTopArea", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
lazy var shareButton: UIButton = { return UIButton() }()
lazy var bookmarkButton: UIButton = { return UIButton() }()
lazy var forwardButton: UIButton = { return UIButton() }()
lazy var backButton: UIButton = { return UIButton() }()
lazy var stopReloadButton: UIButton = { return UIButton() }()
lazy var actionButtons: [UIButton] = {
return [self.shareButton, self.bookmarkButton, self.forwardButton, self.backButton, self.stopReloadButton]
}()
// Used to temporarily store the cloned button so we can respond to layout changes during animation
private weak var clonedTabsButton: InsetButton?
private var rightBarConstraint: Constraint?
private let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer
var currentURL: NSURL? {
get {
return locationView.url
}
set(newURL) {
locationView.url = newURL
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = URLBarViewUX.backgroundColorWithAlpha(0)
addSubview(curveShape)
addSubview(scrollToTopButton)
addSubview(progressBar)
addSubview(tabsButton)
addSubview(cancelButton)
addSubview(shareButton)
addSubview(bookmarkButton)
addSubview(forwardButton)
addSubview(backButton)
addSubview(stopReloadButton)
locationContainer.addSubview(locationView)
locationContainer.addSubview(locationTextField)
addSubview(locationContainer)
helper = BrowserToolbarHelper(toolbar: self)
setupConstraints()
// Make sure we hide any views that shouldn't be showing in non-overlay mode.
updateViewsForOverlayModeAndToolbarChanges()
self.locationTextField.hidden = !inOverlayMode
}
private func setupConstraints() {
scrollToTopButton.snp_makeConstraints { make in
make.top.equalTo(self)
make.left.right.equalTo(self.locationContainer)
}
progressBar.snp_makeConstraints { make in
make.top.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
locationView.snp_makeConstraints { make in
make.edges.equalTo(self.locationContainer)
}
cancelButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
}
tabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(URLBarViewUX.TabsButtonHeight)
}
tabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.width.height.equalTo(UIConstants.ToolbarHeight)
}
curveShape.snp_makeConstraints { make in
make.top.left.bottom.equalTo(self)
self.rightBarConstraint = make.right.equalTo(self).constraint
self.rightBarConstraint?.updateOffset(defaultRightOffset)
}
locationTextField.snp_makeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
backButton.snp_makeConstraints { make in
make.left.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
forwardButton.snp_makeConstraints { make in
make.left.equalTo(self.backButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
stopReloadButton.snp_makeConstraints { make in
make.left.equalTo(self.forwardButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
shareButton.snp_makeConstraints { make in
make.right.equalTo(self.bookmarkButton.snp_left)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
bookmarkButton.snp_makeConstraints { make in
make.right.equalTo(self.tabsButton.snp_left).offset(URLBarViewUX.URLBarCurveOffsetLeft)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
}
override func updateConstraints() {
super.updateConstraints()
if inOverlayMode {
// In overlay mode, we always show the location view full width
self.locationContainer.snp_remakeConstraints { make in
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.cancelButton.snp_leading)
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
} else {
self.locationContainer.snp_remakeConstraints { make in
if self.toolbarIsShowing {
// If we are showing a toolbar, show the text field next to the forward button
make.leading.equalTo(self.stopReloadButton.snp_trailing)
make.trailing.equalTo(self.shareButton.snp_leading)
} else {
// Otherwise, left align the location view
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.tabsButton.snp_leading).offset(-14)
}
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
}
}
// Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without
// However, switching views dynamically at runtime is a difficult. For now, we just use one view
// that can show in either mode.
func setShowToolbar(shouldShow: Bool) {
toolbarIsShowing = shouldShow
setNeedsUpdateConstraints()
// when we transition from portrait to landscape, calling this here causes
// the constraints to be calculated too early and there are constraint errors
if !toolbarIsShowing {
updateConstraintsIfNeeded()
}
updateViewsForOverlayModeAndToolbarChanges()
}
func updateAlphaForSubviews(alpha: CGFloat) {
self.tabsButton.alpha = alpha
self.locationContainer.alpha = alpha
self.backgroundColor = URLBarViewUX.backgroundColorWithAlpha(1 - alpha)
self.actionButtons.forEach { $0.alpha = alpha }
}
func updateTabCount(count: Int) {
updateTabCount(count, animated: true)
}
func updateTabCount(count: Int, animated: Bool) {
if let _ = self.clonedTabsButton {
self.clonedTabsButton?.layer.removeAllAnimations()
self.clonedTabsButton?.removeFromSuperview()
self.tabsButton.layer.removeAllAnimations()
}
// make a 'clone' of the tabs button
let newTabsButton = InsetButton()
self.clonedTabsButton = newTabsButton
newTabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
newTabsButton.setTitleColor(UIConstants.AppBackgroundColor, forState: UIControlState.Normal)
newTabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor
newTabsButton.titleLabel?.layer.cornerRadius = 2
newTabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold
newTabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
newTabsButton.setTitle(count.description, forState: .Normal)
addSubview(newTabsButton)
newTabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(URLBarViewUX.TabsButtonHeight)
}
newTabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
newTabsButton.frame = tabsButton.frame
// Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be
// a rotation around a non-origin point
if let labelFrame = newTabsButton.titleLabel?.frame {
let halfTitleHeight = CGRectGetHeight(labelFrame) / 2
var newFlipTransform = CATransform3DIdentity
newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0)
newFlipTransform.m34 = -1.0 / 200.0 // add some perspective
newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-M_PI_2), 1.0, 0.0, 0.0)
newTabsButton.titleLabel?.layer.transform = newFlipTransform
var oldFlipTransform = CATransform3DIdentity
oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0)
oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective
oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(M_PI_2), 1.0, 0.0, 0.0)
let animate = {
newTabsButton.titleLabel?.layer.transform = CATransform3DIdentity
self.tabsButton.titleLabel?.layer.transform = oldFlipTransform
self.tabsButton.titleLabel?.layer.opacity = 0
}
let completion: (Bool) -> Void = { finished in
// remove the clone and setup the actual tab button
newTabsButton.removeFromSuperview()
self.tabsButton.titleLabel?.layer.opacity = 1
self.tabsButton.titleLabel?.layer.transform = CATransform3DIdentity
self.tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) browser toolbar")
if finished {
self.tabsButton.setTitle(count.description, forState: UIControlState.Normal)
self.tabsButton.accessibilityValue = count.description
}
}
if animated {
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: animate, completion: completion)
} else {
completion(true)
}
}
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: !isTransitioning)
UIView.animateWithDuration(1.5, animations: {
self.progressBar.alpha = 0.0
}, completion: { finished in
if finished {
self.progressBar.setProgress(0.0, animated: false)
}
})
} else {
if self.progressBar.alpha < 1.0 {
self.progressBar.alpha = 1.0
}
self.progressBar.setProgress(progress, animated: (progress > progressBar.progress) && !isTransitioning)
}
}
func updateReaderModeState(state: ReaderModeState) {
locationView.readerModeState = state
}
func setAutocompleteSuggestion(suggestion: String?) {
locationTextField.setAutocompleteSuggestion(suggestion)
}
func enterOverlayMode(locationText: String?, pasted: Bool) {
// Show the overlay mode UI, which includes hiding the locationView and replacing it
// with the editable locationTextField.
animateToOverlayState(overlayMode: true)
delegate?.urlBarDidEnterOverlayMode(self)
// Bug 1193755 Workaround - Calling becomeFirstResponder before the animation happens
// won't take the initial frame of the label into consideration, which makes the label
// look squished at the start of the animation and expand to be correct. As a workaround,
// we becomeFirstResponder as the next event on UI thread, so the animation starts before we
// set a first responder.
if pasted {
// Clear any existing text, focus the field, then set the actual pasted text.
// This avoids highlighting all of the text.
self.locationTextField.text = ""
dispatch_async(dispatch_get_main_queue()) {
self.locationTextField.becomeFirstResponder()
self.locationTextField.text = locationText
}
} else {
// Copy the current URL to the editable text field, then activate it.
self.locationTextField.text = locationText
dispatch_async(dispatch_get_main_queue()) {
self.locationTextField.becomeFirstResponder()
}
}
}
func leaveOverlayMode(didCancel cancel: Bool = false) {
locationTextField.resignFirstResponder()
animateToOverlayState(overlayMode: false, didCancel: cancel)
delegate?.urlBarDidLeaveOverlayMode(self)
}
func prepareOverlayAnimation() {
// Make sure everything is showing during the transition (we'll hide it afterwards).
self.bringSubviewToFront(self.locationContainer)
self.cancelButton.hidden = false
self.progressBar.hidden = false
self.shareButton.hidden = !self.toolbarIsShowing
self.bookmarkButton.hidden = !self.toolbarIsShowing
self.forwardButton.hidden = !self.toolbarIsShowing
self.backButton.hidden = !self.toolbarIsShowing
self.stopReloadButton.hidden = !self.toolbarIsShowing
}
func transitionToOverlay(didCancel: Bool = false) {
self.cancelButton.alpha = inOverlayMode ? 1 : 0
self.progressBar.alpha = inOverlayMode || didCancel ? 0 : 1
self.shareButton.alpha = inOverlayMode ? 0 : 1
self.bookmarkButton.alpha = inOverlayMode ? 0 : 1
self.forwardButton.alpha = inOverlayMode ? 0 : 1
self.backButton.alpha = inOverlayMode ? 0 : 1
self.stopReloadButton.alpha = inOverlayMode ? 0 : 1
let borderColor = inOverlayMode ? URLBarViewUX.TextFieldActiveBorderColor : URLBarViewUX.TextFieldBorderColor
locationContainer.layer.borderColor = borderColor.CGColor
if inOverlayMode {
self.cancelButton.transform = CGAffineTransformIdentity
let tabsButtonTransform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, 0)
self.tabsButton.transform = tabsButtonTransform
self.clonedTabsButton?.transform = tabsButtonTransform
self.rightBarConstraint?.updateOffset(URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width)
// Make the editable text field span the entire URL bar, covering the lock and reader icons.
self.locationTextField.snp_remakeConstraints { make in
make.leading.equalTo(self.locationContainer).offset(URLBarViewUX.LocationContentOffset)
make.top.bottom.trailing.equalTo(self.locationContainer)
}
} else {
self.tabsButton.transform = CGAffineTransformIdentity
self.clonedTabsButton?.transform = CGAffineTransformIdentity
self.cancelButton.transform = CGAffineTransformMakeTranslation(self.cancelButton.frame.width, 0)
self.rightBarConstraint?.updateOffset(defaultRightOffset)
// Shrink the editable text field back to the size of the location view before hiding it.
self.locationTextField.snp_remakeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
}
}
func updateViewsForOverlayModeAndToolbarChanges() {
self.cancelButton.hidden = !inOverlayMode
self.progressBar.hidden = inOverlayMode
self.shareButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.bookmarkButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.forwardButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.backButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.stopReloadButton.hidden = !self.toolbarIsShowing || inOverlayMode
}
func animateToOverlayState(overlayMode overlay: Bool, didCancel cancel: Bool = false) {
prepareOverlayAnimation()
layoutIfNeeded()
inOverlayMode = overlay
locationView.urlTextField.hidden = inOverlayMode
locationTextField.hidden = !inOverlayMode
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { _ in
self.transitionToOverlay(cancel)
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
}, completion: { _ in
self.updateViewsForOverlayModeAndToolbarChanges()
})
}
func SELdidClickAddTab() {
delegate?.urlBarDidPressTabs(self)
}
func SELdidClickCancel() {
leaveOverlayMode(didCancel: true)
}
func SELtappedScrollToTopArea() {
delegate?.urlBarDidPressScrollToTop(self)
}
}
extension URLBarView: BrowserToolbarProtocol {
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateForwardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateBookmarkStatus(isBookmarked: Bool) {
bookmarkButton.selected = isBookmarked
}
func updateReloadStatus(isLoading: Bool) {
if isLoading {
stopReloadButton.setImage(helper?.ImageStop, forState: .Normal)
stopReloadButton.setImage(helper?.ImageStopPressed, forState: .Highlighted)
} else {
stopReloadButton.setImage(helper?.ImageReload, forState: .Normal)
stopReloadButton.setImage(helper?.ImageReloadPressed, forState: .Highlighted)
}
}
func updatePageStatus(isWebPage isWebPage: Bool) {
bookmarkButton.enabled = isWebPage
stopReloadButton.enabled = isWebPage
shareButton.enabled = isWebPage
}
override var accessibilityElements: [AnyObject]? {
get {
if inOverlayMode {
return [locationTextField, cancelButton]
} else {
if toolbarIsShowing {
return [backButton, forwardButton, stopReloadButton, locationView, shareButton, bookmarkButton, tabsButton, progressBar]
} else {
return [locationView, tabsButton, progressBar]
}
}
}
set {
super.accessibilityElements = newValue
}
}
}
extension URLBarView: BrowserLocationViewDelegate {
func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool {
return delegate?.urlBarDidLongPressReaderMode(self) ?? false
}
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) {
enterOverlayMode(locationView.url?.absoluteString, pasted: false)
}
func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidLongPressLocation(self)
}
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReload(self)
}
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressStop(self)
}
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReaderMode(self)
}
func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? {
return delegate?.urlBarLocationAccessibilityActions(self)
}
}
extension URLBarView: AutocompleteTextFieldDelegate {
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool {
guard let text = locationTextField.text else { return true }
delegate?.urlBar(self, didSubmitText: text)
return true
}
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String) {
delegate?.urlBar(self, didEnterText: text)
}
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) {
autocompleteTextField.highlightAll()
}
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didEnterText: "")
return true
}
}
/* Code for drawing the urlbar curve */
// Curve's aspect ratio
private let ASPECT_RATIO = 0.729
// Width multipliers
private let W_M1 = 0.343
private let W_M2 = 0.514
private let W_M3 = 0.49
private let W_M4 = 0.545
private let W_M5 = 0.723
// Height multipliers
private let H_M1 = 0.25
private let H_M2 = 0.5
private let H_M3 = 0.72
private let H_M4 = 0.961
/* Code for drawing the urlbar curve */
private class CurveView: UIView {
private lazy var leftCurvePath: UIBezierPath = {
var leftArc = UIBezierPath(arcCenter: CGPoint(x: 5, y: 5), radius: CGFloat(5), startAngle: CGFloat(-M_PI), endAngle: CGFloat(-M_PI_2), clockwise: true)
leftArc.addLineToPoint(CGPoint(x: 0, y: 0))
leftArc.addLineToPoint(CGPoint(x: 0, y: 5))
leftArc.closePath()
return leftArc
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.opaque = false
self.contentMode = .Redraw
}
private func getWidthForHeight(height: Double) -> Double {
return height * ASPECT_RATIO
}
private func drawFromTop(path: UIBezierPath) {
let height: Double = Double(UIConstants.ToolbarHeight)
let width = getWidthForHeight(height)
let from = (Double(self.frame.width) - width * 2 - Double(URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer), Double(0))
path.moveToPoint(CGPoint(x: from.0, y: from.1))
path.addCurveToPoint(CGPoint(x: from.0 + width * W_M2, y: from.1 + height * H_M2),
controlPoint1: CGPoint(x: from.0 + width * W_M1, y: from.1),
controlPoint2: CGPoint(x: from.0 + width * W_M3, y: from.1 + height * H_M1))
path.addCurveToPoint(CGPoint(x: from.0 + width, y: from.1 + height),
controlPoint1: CGPoint(x: from.0 + width * W_M4, y: from.1 + height * H_M3),
controlPoint2: CGPoint(x: from.0 + width * W_M5, y: from.1 + height * H_M4))
}
private func getPath() -> UIBezierPath {
let path = UIBezierPath()
self.drawFromTop(path)
path.addLineToPoint(CGPoint(x: self.frame.width, y: UIConstants.ToolbarHeight))
path.addLineToPoint(CGPoint(x: self.frame.width, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: 0))
path.closePath()
return path
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextClearRect(context, rect)
CGContextSetFillColorWithColor(context, URLBarViewUX.backgroundColorWithAlpha(1).CGColor)
getPath().fill()
leftCurvePath.fill()
CGContextDrawPath(context, CGPathDrawingMode.Fill)
CGContextRestoreGState(context)
}
}
private class ToolbarTextField: AutocompleteTextField {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| bd1ea4d241160f57cdd8b7f5ef5cfcc2 | 40.655716 | 207 | 0.682271 | false | false | false | false |
SanctionCo/pilot-ios | refs/heads/master | pilot/AuthenticationHelper.swift | mit | 1 | //
// KeychainHelper.swift
// pilot
//
// Created by Rohan Nagar on 1/14/18.
// Copyright © 2018 sanction. All rights reserved.
//
import Foundation
import LocalAuthentication
import Locksmith
struct AuthenticationHelper {
let context = LAContext()
let authenticationReasonString = "Sign in to Pilot"
/// Saves the given email and password to keychain for the account "Pilot".
func saveToKeychain(email: String, password: String) {
if isNewValue(email: email, password: password) {
do {
try Locksmith.updateData(data: ["email": email, "password": password],
forUserAccount: "Pilot")
print("Saved")
} catch {
print("Unable to save data to keychain")
}
}
}
/// Gets the saved email and password from keychain.
/// Returns (email, password) as a tuple.
func getFromKeychain() -> (String, String)? {
if let dictionary = Locksmith.loadDataForUserAccount(userAccount: "Pilot"),
let email = dictionary["email"] as? String,
let password = dictionary["password"] as? String {
return (email, password)
}
return nil
}
/// Determines which biometric type is available on the device.
/// Returns the type. Either none, TouchID, or FaceID
func biometricType() -> BiometricType {
switch context.biometryType {
case .none:
return .none
case .touchID:
return .touchID
case .faceID:
return .faceID
}
}
/// Returns true if the device can use biometrics, false otherwise
func canUseBiometrics() -> Bool {
return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
}
/// Attempts to authenticate using biometrics
/// If successfully authenticates, calls the onSuccess method on the main thread (DispatchQueue.main)
/// If a failure occurs, calls onFailure method with the reason for failure in a String
func authenticationWithBiometrics(onSuccess: @escaping () -> Void,
onFailure: @escaping (FallbackType, String) -> Void) {
context.localizedFallbackTitle = "Use Password"
var authError: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) {
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
localizedReason: authenticationReasonString) {success, evaluateError in
if success {
// Successful authentication
onSuccess()
} else {
// User did not authenticate successfully
guard let error = evaluateError else {
onFailure(.fallbackWithError, "An unknown error occurred. Please login with your credentials.")
return
}
let (fallbackType, reason) = self.evaluateAuthenticationError(errorCode: error._code)
onFailure(fallbackType, reason)
}
}
} else {
// Authentication is either locked out or not available on device
guard let error = authError else {
onFailure(.fallbackWithError, "An unknown error occurred. Please login with your credentials.")
return
}
let (fallbackType, reason) = self.evaluateAuthenticationPolicyError(errorCode: error.code)
onFailure(fallbackType, reason)
}
}
/// Determines the authentication error. Use this method when checking error
/// after user has attempted to authenticate
private func evaluateAuthenticationError(errorCode: Int) -> (FallbackType, String) {
switch errorCode {
case LAError.authenticationFailed.rawValue:
return (.fallbackWithError, "Too many incorrect attempts. Please use your password.")
case LAError.appCancel.rawValue:
return (.fallbackWithoutError, "Authentication was cancelled by application")
case LAError.invalidContext.rawValue:
return (.fallbackWithoutError, "The context is invalid")
case LAError.notInteractive.rawValue:
return (.fallbackWithoutError, "Not interactive")
case LAError.passcodeNotSet.rawValue:
return (.fallbackWithoutError, "Passcode is not set on the device")
case LAError.systemCancel.rawValue:
return (.fallbackWithoutError, "Authentication was cancelled by the system")
case LAError.userCancel.rawValue:
return (.fallbackWithoutError, "The user did cancel")
case LAError.userFallback.rawValue:
return (.fallbackWithoutError, "The user chose to use the fallback")
default:
return (.fallbackWithError, "An unknown error occurred. Please login with your credentials.")
}
}
/// Determines the authentication policy error. Use this method when checking error
/// given before authentication could even take place
private func evaluateAuthenticationPolicyError(errorCode: Int) -> (FallbackType, String) {
switch errorCode {
case LAError.biometryNotAvailable.rawValue:
return (.fallbackWithoutError,
"Authentication could not start because the device does not support biometric authentication.")
case LAError.biometryLockout.rawValue:
return (.fallbackWithoutError,
"The user has been locked out of biometric authentication, due to failing authentication too many times.")
case LAError.biometryNotEnrolled.rawValue:
return (.fallbackWithoutError,
"Authentication could not start because the user has not enrolled in biometric authentication.")
// Fall back to other method to continue checking error code
default:
return evaluateAuthenticationError(errorCode: errorCode)
}
}
/// Check if the given email and password are different from the ones stored in keychain
/// If different, this returns true. If they are the same, this returns false.
private func isNewValue(email: String, password: String) -> Bool {
if let result = getFromKeychain() {
let existingEmail = result.0
let existingPassword = result.1
return existingEmail == email && existingPassword == password ? false : true
}
return true
}
}
enum BiometricType: String {
case none
case touchID = "TouchID"
case faceID = "FaceID"
}
enum FallbackType: String {
case fallbackWithError
case fallbackWithoutError
}
| 495f5d92cb3957ed7e24b93562c1c3c3 | 34.556818 | 120 | 0.69495 | false | false | false | false |
djwbrown/swift | refs/heads/master | test/decl/func/default-values-swift4.swift | apache-2.0 | 3 | // RUN: %target-typecheck-verify-swift -swift-version 4
// RUN: %target-typecheck-verify-swift -swift-version 4 -enable-testing
private func privateFunction() {}
// expected-note@-1 4{{global function 'privateFunction()' is not public}}
fileprivate func fileprivateFunction() {}
// expected-note@-1 4{{global function 'fileprivateFunction()' is not public}}
func internalFunction() {}
// expected-note@-1 4{{global function 'internalFunction()' is not public}}
@_versioned func versionedFunction() {}
public func publicFunction() {}
func internalIntFunction() -> Int {}
// expected-note@-1 2{{global function 'internalIntFunction()' is not public}}
func internalFunctionWithDefaultValue(
x: Int = {
struct Nested {}
// OK
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// OK
fileprivateFunction()
// OK
privateFunction()
// OK
return 0
}(),
y: Int = internalIntFunction()) {}
@_versioned func versionedFunctionWithDefaultValue(
x: Int = {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a default argument value}}
// FIXME: Some errors below are diagnosed twice
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 2{{global function 'internalFunction()' is internal and cannot be referenced from a default argument value}}
fileprivateFunction()
// expected-error@-1 2{{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a default argument value}}
privateFunction()
// expected-error@-1 2{{global function 'privateFunction()' is private and cannot be referenced from a default argument value}}
return 0
}(),
y: Int = internalIntFunction()) {}
// expected-error@-1 {{global function 'internalIntFunction()' is internal and cannot be referenced from a default argument value}}
public func publicFunctionWithDefaultValue(
x: Int = {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a default argument value}}
// FIXME: Some errors below are diagnosed twice
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 2{{global function 'internalFunction()' is internal and cannot be referenced from a default argument value}}
fileprivateFunction()
// expected-error@-1 2{{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a default argument value}}
privateFunction()
// expected-error@-1 2{{global function 'privateFunction()' is private and cannot be referenced from a default argument value}}
return 0
}(),
y: Int = internalIntFunction()) {}
// expected-error@-1 {{global function 'internalIntFunction()' is internal and cannot be referenced from a default argument value}}
| 04acff7a64d7e4a1e425e2ba1e296e42 | 36.375 | 141 | 0.678595 | false | false | false | false |
hooliooo/Rapid | refs/heads/master | Source/Classes/Collections/SynchronizedArray.swift | mit | 1 | //
// Kio
// Copyright (c) Julio Miguel Alorro
//
// Licensed under the MIT license. See LICENSE file.
//
//
import class Foundation.DispatchQueue
import struct Foundation.DispatchWorkItemFlags
public class SynchronizedArray<Element> {
/**
The initializer
- parameter dict: Array instance to be managed
*/
init(elements: [Element]) {
self.elements = elements
}
// MARK: Stored Properties
/**
The queue that handles the read/writes to the array instance.
*/
private let _queue: DispatchQueue = DispatchQueue(
label: "SynchronizedArray",
attributes: [DispatchQueue.Attributes.concurrent]
)
/**
The array instance.
*/
private var elements: [Element]
// MARK: - Computed Properties
/**
The DispatchQueue instance used by the SynchronizedArray instance
*/
public var queue: DispatchQueue {
return self._queue
}
}
// MARK: Read Properties & Methods
public extension SynchronizedArray {
/**
Synchronous read of the array's count property.
*/
var count: Int {
var count: Int = 0
self._queue.sync {
count = self.elements.count
}
return count
}
/**
Synchronous read of the array's description property.
*/
var description: String {
var description: String = ""
self._queue.sync {
description = self.elements.description
}
return description
}
/**
Synchronous read of the array's first property.
*/
var first: Element? {
var first: Element?
self._queue.sync {
first = self.elements.first
}
return first
}
/**
Synchronous read of the array's isEmpty property.
*/
var isEmpty: Bool {
var isEmpty: Bool = true
self._queue.sync {
isEmpty = self.elements.isEmpty
}
return isEmpty
}
/**
Synchronous read of the array's last property.
*/
var last: Element? {
var last: Element?
self._queue.sync {
last = self.elements.last
}
return last
}
/**
Synchronous read of the array's contains method
*/
func contains(where predicate: (Element) throws -> Bool) rethrows -> Bool {
var result: Bool = false
try self._queue.sync {
result = try self.elements.contains(where: predicate)
}
return result
}
/**
Synchronous read of the array's first method.
*/
func first(where predicate: (Element) throws -> Bool) rethrows -> Element? {
var result: Element?
try self._queue.sync {
result = try self.elements.first(where: predicate)
}
return result
}
/**
Synchronous read of the array's filter method.
*/
func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element] {
var result: [Element] = []
try self._queue.sync {
result = try self.elements.filter(isIncluded)
}
return result
}
/**
Synchronous read of the array's flatMap<SegmentOfResult> method
*/
func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Iterator.Element] where SegmentOfResult: Sequence {
var result: [SegmentOfResult.Iterator.Element] = []
try self._queue.sync {
result = try self.elements.flatMap(transform)
}
return result
}
/**
Synchronous read of the array's flatMap<ElementOfResult> method
*/
func flatMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
var result: [ElementOfResult] = []
try self._queue.sync {
result = try self.elements.compactMap(transform)
}
return result
}
/**
Synchronous read of the array's forEach method
*/
func forEach(_ body: (Element) -> Void) {
return self._queue.sync {
return self.elements.forEach(body)
}
}
/**
Synchronous read of the array's firstIndex method
*/
func firstIndex(where predicate: (Element) -> Bool) -> Int? {
var index: Int?
self._queue.sync {
index = self.elements.firstIndex(where: predicate)
}
return index
}
/**
Synchronous read of the array's map method
*/
func map<T>(_ transform: (Element) throws -> T) rethrows -> [T] {
var result: [T] = []
try self._queue.sync {
result = try self.elements.map(transform)
}
return result
}
/**
Synchronous read of the array's reduce method
*/
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result {
var result: Result = initialResult
try self._queue.sync {
result = try self.elements.reduce(initialResult, nextPartialResult)
}
return result
}
/**
Synchronous read of the array's sorted method
*/
func sorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> [Element] {
var result: [Element] = []
self._queue.sync {
result = self.elements.sorted(by: areInIncreasingOrder)
}
return result
}
}
// MARK: - Write Methods
public extension SynchronizedArray {
/**
Asynchronous write of the array's append method for a single Element
*/
func append(_ newElement: Element) {
self._queue.async(flags: DispatchWorkItemFlags.barrier) {
self.elements.append(newElement)
}
}
/**
Asynchronous write of the array's append method for an array of Elements
*/
func append<S>(contentsOf newElements: S) where S: Sequence, S.Iterator.Element == Element {
self._queue.async(flags: DispatchWorkItemFlags.barrier) {
self.elements.append(contentsOf: newElements)
}
}
/**
Asynchronous write of the array's insert(_, at:) method
*/
func insert(_ newElement: Element, at i: Int) {
self._queue.async(flags: DispatchWorkItemFlags.barrier) {
self.elements.insert(newElement, at: i)
}
}
/**
Asynchronous write of the array's remove(at:) method
*/
func remove(at index: Int, callback: @escaping (Element) -> Void) {
self._queue.async(flags: DispatchWorkItemFlags.barrier) {
DispatchQueue.main.async {
callback(self.elements.remove(at: index))
}
}
}
/**
Asynchronous write of the array's remove(where:) method
*/
func remove(where predicate: @escaping (Element) -> Bool, callback: ((Element) -> Void)? = nil) {
self._queue.async(flags: DispatchWorkItemFlags.barrier) {
guard let index = self.elements.firstIndex(where: predicate) else { return }
let element = self.elements.remove(at: index)
DispatchQueue.main.async {
callback?(element)
}
}
}
/**
Asynchronous write of the array's removeAll method
*/
func removeAll(callback: (([Element]) -> Void)? = nil) {
self._queue.async(flags: DispatchWorkItemFlags.barrier) {
let elements: [Element] = self.elements
self.elements.removeAll()
DispatchQueue.main.async {
callback?(elements)
}
}
}
}
public extension SynchronizedArray where Element: Equatable {
/**
Synchronous read of the array's contains method
*/
func contains(_ element: Element) -> Bool {
var result: Bool = false
self._queue.sync {
result = self.elements.contains(element)
}
return result
}
}
| b98d87180dc82c81557c5d44381a8bc3 | 26.161512 | 164 | 0.586412 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Analytics/Sources/AnalyticsKit/Providers/Nabu/Network/Client/APIClient.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Foundation
protocol EventSendingAPI {
func publish<Events: Encodable>(
events: Events,
token: String?
) -> AnyPublisher<Never, URLError>
}
final class APIClient: EventSendingAPI {
// MARK: - Types
private enum Path {
static let publishEvents = "/events/publish"
}
// MARK: - Properties
private let requestBuilder: RequestBuilderAPI
private let networkAdapter: NetworkAdapterAPI
private let jsonEncoder: JSONEncoder
// MARK: - Setup
convenience init(basePath: String, userAgent: String) {
self.init(requestBuilder: RequestBuilder(basePath: basePath, userAgent: userAgent))
}
init(
networkAdapter: NetworkAdapterAPI = NetworkAdapter(),
requestBuilder: RequestBuilderAPI,
jsonEncoder: JSONEncoder = {
let jsonEncoder = JSONEncoder()
jsonEncoder.dateEncodingStrategy = .iso8601
return jsonEncoder
}()
) {
self.networkAdapter = networkAdapter
self.requestBuilder = requestBuilder
self.jsonEncoder = jsonEncoder
}
// MARK: - Methods
func publish<Events: Encodable>(
events: Events,
token: String?
) -> AnyPublisher<Never, URLError> {
var headers = [String: String]()
if let token = token {
headers["Authorization"] = "Bearer \(token)"
}
let request = requestBuilder.post(
path: Path.publishEvents,
body: try? jsonEncoder.encode(events),
headers: headers
)
return networkAdapter.performRequest(request: request)
}
}
| 300ddeb1d561fe20254e702f2323c51d | 25.84375 | 91 | 0.630966 | false | false | false | false |
SusanDoggie/Doggie | refs/heads/main | Sources/DoggieGPU/CoreImage/ConvolveKernel.swift | mit | 1 | //
// ConvolveKernel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
#if canImport(CoreImage) && canImport(MetalPerformanceShaders)
extension CIImage {
private class ConvolveKernel: CIImageProcessorKernel {
override class var synchronizeInputs: Bool {
return false
}
override class func roi(forInput input: Int32, arguments: [String: Any]?, outputRect: CGRect) -> CGRect {
guard let orderX = arguments?["orderX"] as? Int else { return outputRect }
guard let orderY = arguments?["orderY"] as? Int else { return outputRect }
let inset_x = -(orderX + 1) / 2
let inset_y = -(orderY + 1) / 2
return outputRect.insetBy(dx: CGFloat(inset_x), dy: CGFloat(inset_y))
}
override class func process(with inputs: [CIImageProcessorInput]?, arguments: [String: Any]?, output: CIImageProcessorOutput) throws {
guard let commandBuffer = output.metalCommandBuffer else { return }
guard let input = inputs?.first else { return }
guard let source = input.metalTexture else { return }
guard let destination = output.metalTexture else { return }
guard let orderX = arguments?["orderX"] as? Int, orderX > 0 else { return }
guard let orderY = arguments?["orderY"] as? Int, orderY > 0 else { return }
guard let matrix = arguments?["matrix"] as? [Double], orderX * orderY == matrix.count else { return }
guard let bias = arguments?["bias"] as? Double else { return }
let kernel = MPSImageConvolution(device: commandBuffer.device, kernelWidth: orderX, kernelHeight: orderY, weights: matrix.map { Float($0) })
kernel.offset.x = Int(output.region.minX - input.region.minX)
kernel.offset.y = Int(output.region.minY - input.region.minY)
kernel.bias = Float(bias)
kernel.encode(commandBuffer: commandBuffer, sourceTexture: source, destinationTexture: destination)
}
}
public func convolve(_ matrix: [Double], _ bias: Double, _ orderX: Int, _ orderY: Int) -> CIImage {
if extent.isEmpty { return .empty() }
guard orderX > 0 && orderY > 0 && orderX * orderY == matrix.count else { return self }
if orderX > 1 && orderY > 1, let (horizontal, vertical) = separate_convolution_filter(matrix, orderX, orderY) {
return self.convolve(horizontal, 0, orderX, 1).convolve(vertical, bias, 1, orderY)
}
let matrix = Array(matrix.chunks(ofCount: orderX).lazy.map { $0.reversed() }.joined())
let _orderX = orderX | 1
let _orderY = orderY | 1
guard _orderX <= 9 && _orderY <= 9 else { return self }
let append_x = _orderX - orderX
let append_y = _orderY - orderY
var _matrix = Array(matrix.chunks(ofCount: orderX).joined(separator: repeatElement(0, count: append_x)))
_matrix.append(contentsOf: repeatElement(0, count: append_x + _orderX * append_y))
let inset_x = -(_orderX + 1) / 2
let inset_y = -(_orderY + 1) / 2
let extent = self.extent.insetBy(dx: CGFloat(inset_x), dy: CGFloat(inset_y))
let _extent = extent.isInfinite ? extent : extent.insetBy(dx: .random(in: -1..<0), dy: .random(in: -1..<0))
var rendered = try? ConvolveKernel.apply(withExtent: _extent, inputs: [self], arguments: ["matrix": _matrix, "bias": bias, "orderX": _orderX, "orderY": _orderY])
if !extent.isInfinite {
rendered = rendered?.cropped(to: extent)
}
return rendered ?? .empty()
}
}
#endif
| f175992ffc1f05ecdcb014b861a5f486 | 47.27451 | 169 | 0.627945 | false | false | false | false |
zning1994/practice | refs/heads/master | Swift学习/code4xcode6/ch15/15.1从一个实例开始.playground/section-1.swift | gpl-2.0 | 1 | // 本书网站:http://www.51work6.com/swift.php
// 智捷iOS课堂在线课堂:http://v.51work6.com
// 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973
// 智捷iOS课堂微信公共账号:智捷iOS课堂
// 作者微博:http://weibo.com/516inc
// 官方csdn博客:http://blog.csdn.net/tonny_guan
// Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected]
import UIKit
class Person {
var name : String
var age : Int
func description() -> String {
return "\(name) 年龄是: \(age)"
}
init () {
name = ""
age = 1
}
}
class Student : Person {
var school : String
override init () {
school = ""
super.init()
age = 8
}
}
let student = Student()
println("学生: \(student.description())")
| 933160ee7e63a0675fbfff81fd40b135 | 19.314286 | 62 | 0.583685 | false | false | false | false |
ACChe/eidolon | refs/heads/master | Kiosk/Bid Fulfillment/LoadingViewModel.swift | mit | 1 | import Foundation
import ARAnalytics
import ReactiveCocoa
/// Encapsulates activities of the LoadingViewController.
class LoadingViewModel: NSObject {
let placingBid: Bool
let bidderNetworkModel: BidderNetworkModel
lazy var placeBidNetworkModel: PlaceBidNetworkModel = {
return PlaceBidNetworkModel(fulfillmentController: self.bidderNetworkModel.fulfillmentController)
}()
lazy var bidCheckingModel: BidCheckingNetworkModel = {
return BidCheckingNetworkModel(fulfillmentController: self.bidderNetworkModel.fulfillmentController)
}()
dynamic var createdNewBidder = false
dynamic var bidIsResolved = false
dynamic var isHighestBidder = false
dynamic var reserveNotMet = false
var bidDetails: BidDetails {
return bidderNetworkModel.fulfillmentController.bidDetails
}
init(bidNetworkModel: BidderNetworkModel, placingBid: Bool, actionsCompleteSignal: RACSignal) {
self.bidderNetworkModel = bidNetworkModel
self.placingBid = placingBid
super.init()
RAC(self, "createdNewBidder") <~ bidderNetworkModel.createdNewUser.takeUntil(actionsCompleteSignal)
RAC(self, "bidIsResolved") <~ RACObserve(bidCheckingModel, "bidIsResolved").takeUntil(actionsCompleteSignal)
RAC(self, "isHighestBidder") <~ RACObserve(bidCheckingModel, "isHighestBidder").takeUntil(actionsCompleteSignal)
RAC(self, "reserveNotMet") <~ RACObserve(bidCheckingModel, "reserveNotMet").takeUntil(actionsCompleteSignal)
}
/// Encapsulates essential activities of the LoadingViewController, including:
/// - Registering new users
/// - Placing bids for users
/// - Polling for bid results
func performActions() -> RACSignal {
return bidderNetworkModel.createOrGetBidder().then { [weak self] () -> RACSignal in
if self?.placingBid == false {
ARAnalytics.event("Registered New User Only")
return RACSignal.empty()
}
if let strongSelf = self {
ARAnalytics.event("Started Placing Bid")
return strongSelf.placeBidNetworkModel.bidSignal().ignore(nil)
} else {
return RACSignal.empty()
}
}.flattenMap { [weak self] (position) in
if self == nil || self?.placingBid == false {
return RACSignal.empty()
}
return self!.bidCheckingModel.waitForBidResolution(position as! String)
}
}
}
| 8500685d4862271cbead71f195cf6bca | 38.484375 | 120 | 0.682232 | false | false | false | false |
PlutoNetwork/Pluto-iOS | refs/heads/master | Pluto/SearchController.swift | gpl-3.0 | 1 | //
// SearchController.swift
// Pluto
//
// Created by Faisal M. Lalani on 6/11/17.
// Copyright © 2017 Faisal M. Lalani. All rights reserved.
//
import UIKit
import GooglePlaces
class SearchController: UIViewController {
var resultsViewController: GMSAutocompleteResultsViewController?
var searchController: UISearchController?
var resultView: UITextView?
override func viewDidLoad() {
super.viewDidLoad()
resultsViewController = GMSAutocompleteResultsViewController()
resultsViewController?.delegate = self
searchController = UISearchController(searchResultsController: resultsViewController)
searchController?.searchResultsUpdater = resultsViewController
// Add the search bar to the right of the nav bar,
// use a popover to display the results.
// Set an explicit size as we don't want to use the entire nav bar.
searchController?.searchBar.frame = (CGRect(x: 0, y: 0, width: 250.0, height: 44.0))
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: (searchController?.searchBar)!)
// When UISearchController presents the results view, present it in
// this view controller, not one further up the chain.
definesPresentationContext = true
// Keep the navigation bar visible.
searchController?.hidesNavigationBarDuringPresentation = false
searchController?.modalPresentationStyle = .popover
}
}
// Handle the user's selection.
extension SearchController: GMSAutocompleteResultsViewControllerDelegate {
func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
didAutocompleteWith place: GMSPlace) {
searchController?.isActive = false
// Do something with the selected place.
print("Place name: \(place.name)")
print("Place address: \(place.formattedAddress)")
print("Place attributions: \(place.attributions)")
}
func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
didFailAutocompleteWithError error: Error){
// TODO: handle the error.
print("Error: ", error.localizedDescription)
}
// Turn the network activity indicator on and off again.
func didRequestAutocompletePredictions(forResultsController resultsController: GMSAutocompleteResultsViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictions(forResultsController resultsController: GMSAutocompleteResultsViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
| 7394719d941134047c4d1c845f3ef541 | 39.720588 | 122 | 0.706753 | false | false | false | false |
jarrodparkes/DominoKit | refs/heads/master | Sources/DominoSet.swift | mit | 1 | //
// DominoSet.swift
// DominoKit
//
// Created by Jarrod Parkes on 1/31/17.
// Copyright © 2017 Jarrod Parkes. All rights reserved.
//
// MARK: - DominoSet
/// A collection of dominoes that are only accessible one-at-a-time.
public class DominoSet {
// MARK: Properties
/// The collection of dominoes belonging to this set.
fileprivate var dominoes: [Domino]
/// The highest suit of all the dominoes in the set at the time of creation.
public let highestSuit: Suit
// MARK: Computed Properties
/// The number of dominoes in the collection.
public var count: Int {
return dominoes.count
}
// MARK: Initializers
/**
Initializes a set of dominoes from a specified collection.
- Parameter dominoes: A collection of dominoes
- Returns: A set of dominoes containing all the dominoes from the
specified collection.
*/
init(_ dominoes: [Domino]) {
self.dominoes = dominoes
var highestSuitDetected = Suit.zero
for domino in dominoes {
if domino.suitOne.rawValue > highestSuitDetected.rawValue {
highestSuitDetected = domino.suitOne
}
if domino.suitTwo.rawValue > highestSuitDetected.rawValue {
highestSuitDetected = domino.suitTwo
}
}
highestSuit = highestSuitDetected
}
/**
Creates a standard set of dominoes.
- Parameter highestSuit: The highest/largest suit represented in a
standard set
- Returns: A standard set of dominoes where the ends of the largest
ranking double are equal to the specified suit.
*/
public static func standardSet(_ highestSuit: Suit) -> DominoSet {
var dominoes: [Domino] = []
for suitValueOne in 0...highestSuit.rawValue {
for suitValueTwo in suitValueOne...highestSuit.rawValue {
dominoes.append(Domino(suitOne: Suit(rawValue: suitValueOne)!,
suitTwo: Suit(rawValue: suitValueTwo)!))
}
}
return DominoSet(dominoes)
}
// MARK: Dealing
/// Randomly shuffles all dominoes in the set.
public func shuffle() {
dominoes.shuffle()
}
/**
Deals a domino from the set, if one exists.
- Returns: A domino from the set, if one exists.
*/
public func deal() -> Domino? {
guard !dominoes.isEmpty else { return nil }
return dominoes.removeLast()
}
}
// MARK: - DominoSet: Equatable
extension DominoSet: Equatable {}
/**
Determines if two domino sets are equal, i.e. contain all the same dominoes.
- Parameters:
lhs: The first domino set
rhs: The second domino set
- Returns: A Boolean value indicating if the first and second domino sets
are equal.
*/
public func ==(lhs: DominoSet, rhs: DominoSet) -> Bool {
return lhs.dominoes == rhs.dominoes
}
| 0a002fcf7c888d2008097a813771a2e5 | 26.435185 | 80 | 0.624367 | false | false | false | false |
jingkecn/WatchWorker | refs/heads/master | src/ios/JSCore/Events/EventListenerOptions.swift | mit | 1 | //
// EventListenerOptions.swift
// WTVJavaScriptCore
//
// Created by Jing KE on 27/06/16.
// Copyright © 2016 WizTiVi. All rights reserved.
//
import Foundation
import JavaScriptCore
class EventListenerOptions: NSObject {
let capture: Bool
init(capture: Bool? = nil) {
self.capture = capture ?? false
}
convenience init?(options: JSValue?) {
guard let options = options where !options.isUndefined && !options.isNull else { return nil }
if options.isBoolean {
self.init(capture: options.toBool())
return
}
let captureValue = options.objectForKeyedSubscript("capture")
let capture: Bool? = captureValue.isBoolean ? captureValue.toBool() : nil
self.init(capture: capture)
}
}
class AddEventListenerOptions: EventListenerOptions {
let passive: Bool
let once: Bool
init(capture: Bool? = nil, passive: Bool? = nil, once: Bool? = nil) {
self.passive = passive ?? false
self.once = once ?? false
super.init(capture: capture)
}
convenience init?(options: JSValue?) {
guard let options = options where !options.isUndefined && !options.isNull else { return nil }
if options.isBoolean {
self.init(capture: options.toBool())
return
}
let captureValue = options.objectForKeyedSubscript("capture")
let capture: Bool? = captureValue.isBoolean ? captureValue.toBool() : nil
let passiveValue = options.objectForKeyedSubscript("passive")
let passive: Bool? = passiveValue.isBoolean ? passiveValue.toBool() : nil
let onceValue = options.objectForKeyedSubscript("once")
let once: Bool? = onceValue.isBoolean ? onceValue.toBool() : nil
self.init(capture: capture, passive: passive, once: once)
}
} | a6aaf3d21f2db9984c7437e2b56401c8 | 30.830508 | 101 | 0.635056 | false | false | false | false |
zadr/conservatory | refs/heads/main | Code/Internal/Random/Seeding.swift | bsd-2-clause | 1 | #if os(iOS) || os(OSX)
import Darwin
#else
import Glibc
#endif
internal struct Seed {
#if os(iOS) || os(OSX)
fileprivate static var bootTime: UInt {
var bootTime = timeval()
var mib = [ CTL_KERN, KERN_BOOTTIME ]
var size = MemoryLayout<timeval>.stride
sysctl(&mib, u_int(mib.count), &bootTime, &size, nil, 0)
return UInt(bootTime.tv_sec) + UInt(bootTime.tv_usec)
}
fileprivate static var CPUTime: UInt {
return 0
}
internal static func generate() -> [UInt] {
// todo: add in thread time, cpu time, cpu load, processor load, memory usage
return [
UInt(mach_absolute_time()),
bootTime,
// threadTime,
// CPUTime,
UInt(getpid()),
UInt(time(nil)),
UInt(pthread_mach_thread_np(pthread_self()))
]
}
#elseif os(Linux)
internal static func generate() -> [UInt] {
let seeds = [
UInt(getpid()),
UInt(time(nil)),
UInt(pthread_mach_thread_np(pthread_self()))
]
// todo: add in processor load, memory usage
let ids = [ CLOCK_MONOTONIC_RAW, CLOCK_BOOTTIME,
CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID ]
return ids.map { return clock($0) } + seeds
}
private static func clock(id: clockid_t) -> UInt {
var ts: timespec = timespec()
return withUnsafeMutablePointer(&ts) { (time) -> UInt in
clock_gettime(id, time)
return UInt(time.memory.tv_sec) + UInt(time.memory.tv_nsec)
}
}
#endif
}
| 8ec07b4e132e2a784b1a9e98a9a2cf69 | 22.603448 | 79 | 0.658875 | false | false | false | false |
WangCrystal/actor-platform | refs/heads/master | actor-apps/app-ios/ActorApp/Controllers/Group/InviteLinkViewController.swift | mit | 7 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class InviteLinkViewController: AATableViewController {
let gid: Int
var tableData: UAGrouppedTableData!
var currentUrl: String?
var urlCell: UACommonCellRegion!
init(gid: Int) {
self.gid = gid
super.init(style: UITableViewStyle.Grouped)
title = NSLocalizedString("GroupInviteLinkPageTitle", comment: "Invite Link Title")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.backgroundColor = MainAppTheme.list.backyardColor
tableView.hidden = true
tableData = UAGrouppedTableData(tableView: tableView)
urlCell = tableData.addSection()
.setHeaderText(NSLocalizedString("GroupInviteLinkTitle", comment: "Link title"))
.setFooterText(NSLocalizedString("GroupInviteLinkHint", comment: "Link hint"))
.addCommonCell()
.setStyle(.Normal)
let section = tableData.addSection()
section.addActionCell("ActionCopyLink", actionClosure: { () -> () in
UIPasteboard.generalPasteboard().string = self.currentUrl
self.alertUser("AlertLinkCopied")
})
.showBottomSeparator(15)
.showTopSeparator(0)
section.addActionCell("ActionShareLink", actionClosure: { () -> () in
UIApplication.sharedApplication().openURL(NSURL(string: self.currentUrl!)!)
})
.hideTopSeparator()
.showBottomSeparator(0)
tableData.addSection()
.addActionCell("ActionRevokeLink", actionClosure: { () -> () in
self.confirmAlertUser("GroupInviteLinkRevokeMessage", action: "GroupInviteLinkRevokeAction", tapYes: { () -> () in
self.reloadLink()
})
})
.setStyle(.Destructive)
execute(Actor.requestInviteLinkCommandWithGid(jint(gid)), successBlock: { (val) -> Void in
self.currentUrl = val as? String
self.urlCell.setContent(self.currentUrl!)
self.tableView.hidden = false
self.tableView.reloadData()
}) { (val) -> Void in
// TODO: Implement
}
}
func reloadLink() {
execute(Actor.requestRevokeLinkCommandWithGid(jint(gid)), successBlock: { (val) -> Void in
self.currentUrl = val as? String
self.urlCell.setContent(self.currentUrl!)
self.tableView.hidden = false
self.tableView.reloadData()
}) { (val) -> Void in
// TODO: Implement
}
}
} | 00f334c61c9049e83e285a1f65ecf902 | 34.590361 | 130 | 0.583813 | false | false | false | false |
shirokova/CustomAlert | refs/heads/master | CustomAlert/Classes/CustomAlertConfig.swift | mit | 1 | //
// CustomAlertConfig.swift
// CustomAlert
//
// Created by Anna Shirokova on 18/12/2018.
//
import CoreGraphics
public enum VerticalPosition {
case top(offset: CGFloat)
case center(topOffset: CGFloat?, centerOffset: CGFloat)
case bottom(offset: CGFloat)
case fill
}
public struct CustomAlertConfig {
let horizontalOffset: CGFloat
let cornerRadius: CGFloat
let verticalPosition: VerticalPosition
public init(
horizontalOffset: CGFloat = 25,
cornerRadius: CGFloat = 16,
verticalPosition: VerticalPosition = .center(topOffset: nil, centerOffset: 0)) {
self.horizontalOffset = horizontalOffset
self.cornerRadius = cornerRadius
self.verticalPosition = verticalPosition
}
public static var `default`: CustomAlertConfig {
return CustomAlertConfig()
}
}
| fc81dc4eb44d3f4477fbde1fc07161b3 | 24.205882 | 88 | 0.697783 | false | true | false | false |
team-supercharge/boa | refs/heads/master | lib/boa/module/templates/swift/ModuleInterface.swift | mit | 1 | //
// <%= @prefixed_module %>ModuleInterface.swift
// <%= @project %>
//
// Created by <%= @author %> on <%= @date %>.
//
//
import Foundation
protocol <%= @prefixed_module %>ModuleInterface: class
{
}
protocol <%= @prefixed_module %>ModuleDelegate: class
{
}
| 8d67a9a57b39f4c1d70a81229ee5abcb | 13.105263 | 54 | 0.600746 | false | false | false | false |
dannofx/AudioPal | refs/heads/master | AudioPal/AudioPal/PalsTableViewController.swift | mit | 1 | //
// PalsTableViewController.swift
// AudioPal
//
// Created by Danno on 5/18/17.
// Copyright © 2017 Daniel Heredia. All rights reserved.
//
import UIKit
class PalsTableViewController: UITableViewController, PalConnectionDelegate {
var callManager: CallManager
var connectedPals: [NearbyPal]
private lazy var userName: String? = {
return UserDefaults.standard.value(forKey: StoredValues.username) as? String
}()
fileprivate var dataController: DataController
override init(style: UITableViewStyle) {
callManager = CallManager()
connectedPals = []
dataController = DataController()
super.init(style: style)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
callManager = CallManager()
connectedPals = []
dataController = DataController()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
callManager = CallManager()
connectedPals = []
dataController = DataController()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
if let navigationBar = navigationController?.navigationBar {
let statusBarHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
let totalHeight = navigationBar.frame.size.height + statusBarHeight
let shadowHeight: CGFloat = 27.0
let mainHeight = totalHeight - shadowHeight
var colorBars = [(color: UIColor, height: CGFloat)]()
colorBars.append((UIColor.untBlueGreen, mainHeight))
colorBars.append((UIColor.untMustardYellow, shadowHeight))
let backgroundImage = UIImage.imageWithColorBars(colorBars, totalHeight: totalHeight)
navigationBar.setBackgroundImage(backgroundImage, for: .default)
}
dataController.delegate = self
registerForNotifications()
checkForNoPalsView()
}
override func viewDidAppear(_ animated: Bool) {
if (userName == nil) {
self.parent!.performSegue(withIdentifier: StoryboardSegues.setName, sender: self)
} else {
ADProcessor.askForMicrophoneAccess()
startCallManager()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startCallManager() {
callManager.palDelegate = self
callManager.start()
}
func restartCallManager() {
if callManager.isStarted {
callManager.stop()
}
startCallManager()
}
func checkForNoPalsView() {
if connectedPals.count == 0 {
let emptyView = Bundle.main.loadNibNamed("EmptyTable", owner: self, options: nil)!.first as! UIView
tableView.tableHeaderView = emptyView
tableView.separatorColor = UIColor.clear
} else {
tableView.tableHeaderView = nil
tableView.separatorColor = UIColor.untLightYellow
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == StoryboardSegues.showCall {
let callViewController = segue.destination as! CallViewController
callViewController.callManager = callManager
}else if segue.identifier == StoryboardSegues.settings {
let settingsViewController = segue.destination as! SettingsTableViewController
settingsViewController.dataController = dataController
}
}
// MARK: - Notifications
func registerForNotifications() {
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: NotificationNames.userReady),
object: nil,
queue: nil) { (notification) in
self.userName = (notification.userInfo![StoredValues.username] as! String)
self.restartCallManager()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: NotificationNames.micAccessRequired),
object: nil, queue: nil) { (notification) in
let missedCall = (notification.userInfo![DictionaryKeys.missedCall] as! Bool)
self.showPermissionsAlert(missedCall: missedCall)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - Alerts
extension PalsTableViewController {
func showPermissionsAlert(missedCall: Bool) {
let title: String!
let message: String!
if missedCall {
title = NSLocalizedString("Rejected call", comment: "")
message = NSLocalizedString("call.rejected.no.mic.access", comment: "")
} else {
title = NSLocalizedString("Microphone access denied!", comment: "")
message = NSLocalizedString("mic.access.denied", comment: "")
}
let alert = UIAlertController(title: title,
message: message,
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func showCannotCallAlert(blockedPal: NearbyPal) {
let title = NSLocalizedString("Blocked user", comment: "")
let message = String(format: NSLocalizedString("unblock %@ to call", comment: ""), blockedPal.username!)
let alert = UIAlertController(title: title,
message: message,
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
// MARK: - Table view data source
extension PalsTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return connectedPals.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifiers.pal, for: indexPath) as! PalTableViewCell
let pal = connectedPals[indexPath.row]
cell.configure(withPal: pal)
return cell
}
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
}
}
}
// MARK: - Table view delegate
extension PalsTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let pal = connectedPals[indexPath.row]
if !pal.isBlocked {
_ = callManager.startCall(toPal: pal)
} else {
showCannotCallAlert(blockedPal: pal)
}
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let pal = connectedPals[indexPath.row]
let title: String!
let color: UIColor!
if pal.isBlocked {
title = NSLocalizedString("Unblock", comment: "")
color = UIColor.untGreen
} else {
title = NSLocalizedString("Block", comment: "")
color = UIColor.untReddish
}
let blockAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: title){ (_, _) in
pal.isBlocked = !pal.isBlocked
self.tableView.beginUpdates()
tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
self.tableView.endUpdates()
self.dataController.updateBlockStatus(pal: pal)
}
blockAction.backgroundColor = color
return [blockAction]
}
}
// MARK: - PalConnectionDelegate
extension PalsTableViewController {
func callManager(_ callManager: CallManager, didDetectNearbyPal pal: NearbyPal) {
print("Inserting pal in main list")
tableView.beginUpdates()
let index = connectedPals.sortedInsert(item: pal, isAscendant: NearbyPal.isAscendant)
let indexPath = IndexPath.init(row: index, section: 0)
checkForNoPalsView()
tableView.insertRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
tableView.endUpdates()
dataController.checkIfBlocked(pal: pal) { (pal, blocked) in
if pal.isBlocked != blocked {
pal.isBlocked = blocked
self.updateCell(forPal: pal)
}
}
}
func callManager(_ callManager: CallManager, didDetectDisconnection pal: NearbyPal) {
guard let index = connectedPals.index(of: pal) else {
return
}
print("Deleting pal in main list")
tableView.beginUpdates()
let indexPath = IndexPath.init(row: index, section: 0)
connectedPals.remove(at: index)
checkForNoPalsView()
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
tableView.endUpdates()
}
func callManager(_ callManager: CallManager, didDetectCallError error:Error, withPal pal: NearbyPal) {
}
func callManager(_ callManager: CallManager, didPal pal: NearbyPal, changeStatus status: PalStatus) {
updateCell(forPal: pal)
}
func callManager(_ callManager: CallManager, didPal pal: NearbyPal, changeUsername username: String) {
updateCell(forPal: pal)
}
func callManager(_ callManager: CallManager, didStartCallWithPal pal: NearbyPal) {
performSegue(withIdentifier: StoryboardSegues.showCall, sender: self)
}
func updateCell(forPal pal: NearbyPal) {
guard connectedPals.index(of: pal) != nil else {
return
}
print("Updating pal in main list")
guard let tuple = connectedPals.sortedUpdate(item: pal, isAscendant: NearbyPal.isAscendant) else {
return
}
tableView.beginUpdates()
let oldIndexPath = IndexPath.init(row: tuple.old, section: 0)
let newIndexPath = IndexPath.init(row: tuple.new, section: 0)
tableView.moveRow(at: oldIndexPath, to: newIndexPath)
tableView.endUpdates()
tableView.beginUpdates()
tableView.reloadRows(at: [newIndexPath], with: UITableViewRowAnimation.automatic)
tableView.endUpdates()
}
}
// MARK: - Data Controller Delegate
extension PalsTableViewController: DataControllerDelegate {
func dataController(_ dataController: DataController, didUnblockUserWithId uuid: UUID) {
if let unblockedPal = ( connectedPals.filter{ $0.uuid == uuid }.first ) {
unblockedPal.isBlocked = false
updateCell(forPal: unblockedPal)
}
}
}
| 16051c83fd6689b09d13908839f95580 | 37.475884 | 136 | 0.627444 | false | false | false | false |
Jnosh/swift | refs/heads/master | benchmark/single-source/SetTests.swift | apache-2.0 | 11 | //===--- SetTests.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 TestsUtils
@inline(never)
public func run_SetIsSubsetOf(_ N: Int) {
let size = 200
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var isSubset = false
for _ in 0 ..< N * 5000 {
isSubset = set.isSubset(of: otherSet)
if isSubset {
break
}
}
CheckResults(!isSubset)
}
@inline(never)
func sink(_ s: inout Set<Int>) {
}
@inline(never)
public func run_SetExclusiveOr(_ N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var xor = Set<Int>()
for _ in 0 ..< N * 100 {
xor = set.symmetricDifference(otherSet)
}
sink(&xor)
}
@inline(never)
public func run_SetUnion(_ N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var or = Set<Int>()
for _ in 0 ..< N * 100 {
or = set.union(otherSet)
}
sink(&or)
}
@inline(never)
public func run_SetIntersect(_ N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var and = Set<Int>()
for _ in 0 ..< N * 100 {
and = set.intersection(otherSet)
}
sink(&and)
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue: Int {
return value.hashValue
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_SetIsSubsetOf_OfObjects(_ N: Int) {
let size = 200
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var isSubset = false
for _ in 0 ..< N * 5000 {
isSubset = set.isSubset(of: otherSet)
if isSubset {
break
}
}
CheckResults(!isSubset)
}
@inline(never)
func sink(_ s: inout Set<Box<Int>>) {
}
@inline(never)
public func run_SetExclusiveOr_OfObjects(_ N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var xor = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
xor = set.symmetricDifference(otherSet)
}
sink(&xor)
}
@inline(never)
public func run_SetUnion_OfObjects(_ N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var or = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
or = set.union(otherSet)
}
sink(&or)
}
@inline(never)
public func run_SetIntersect_OfObjects(_ N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var and = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
and = set.intersection(otherSet)
}
sink(&and)
}
| 8b3ae82e4c9a55f6fa6f4f0e3dc78e94 | 20.164319 | 80 | 0.6189 | false | false | false | false |
FuckBoilerplate/RxCache | refs/heads/master | Carthage/Checkouts/RxSwift/RxSwift/Disposables/RefCountDisposable.swift | mit | 12 | //
// RefCountDisposable.swift
// Rx
//
// Created by Junior B. on 10/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
public final class RefCountDisposable : DisposeBase, Cancelable {
private var _lock = SpinLock()
private var _disposable = nil as Disposable?
private var _primaryDisposed = false
private var _count = 0
/**
- returns: Was resource disposed.
*/
public var isDisposed: Bool {
_lock.lock(); defer { _lock.unlock() }
return _disposable == nil
}
/**
Initializes a new instance of the `RefCountDisposable`.
*/
public init(disposable: Disposable) {
_disposable = disposable
super.init()
}
/**
Holds a dependent disposable that when disposed decreases the refcount on the underlying disposable.
When getter is called, a dependent disposable contributing to the reference count that manages the underlying disposable's lifetime is returned.
*/
public func retain() -> Disposable {
return _lock.calculateLocked {
if let _ = _disposable {
do {
let _ = try incrementChecked(&_count)
} catch (_) {
rxFatalError("RefCountDisposable increment failed")
}
return RefCountInnerDisposable(self)
} else {
return Disposables.create()
}
}
}
/**
Disposes the underlying disposable only when all dependent disposables have been disposed.
*/
public func dispose() {
let oldDisposable: Disposable? = _lock.calculateLocked {
if let oldDisposable = _disposable, !_primaryDisposed
{
_primaryDisposed = true
if (_count == 0)
{
_disposable = nil
return oldDisposable
}
}
return nil
}
if let disposable = oldDisposable {
disposable.dispose()
}
}
fileprivate func release() {
let oldDisposable: Disposable? = _lock.calculateLocked {
if let oldDisposable = _disposable {
do {
let _ = try decrementChecked(&_count)
} catch (_) {
rxFatalError("RefCountDisposable decrement on release failed")
}
guard _count >= 0 else {
rxFatalError("RefCountDisposable counter is lower than 0")
}
if _primaryDisposed && _count == 0 {
_disposable = nil
return oldDisposable
}
}
return nil
}
if let disposable = oldDisposable {
disposable.dispose()
}
}
}
internal final class RefCountInnerDisposable: DisposeBase, Disposable
{
private let _parent: RefCountDisposable
private var _isDisposed: AtomicInt = 0
init(_ parent: RefCountDisposable)
{
_parent = parent
super.init()
}
internal func dispose()
{
if AtomicCompareAndSwap(0, 1, &_isDisposed) {
_parent.release()
}
}
}
| bc36102e04f35075b808892b5f3edd1e | 26.070866 | 149 | 0.550902 | false | false | false | false |
serp1412/LazyTransitions | refs/heads/master | LazyTransitionsTests/TransitionCombinatorTests.swift | bsd-2-clause | 1 | //
// TransitionCombinatorTests.swift
// LazyTransitions
//
// Created by Serghei Catraniuc on 12/12/16.
// Copyright © 2016 BeardWare. All rights reserved.
//
import XCTest
@testable import LazyTransitions
class MockTransitioner: TransitionerType {
weak var delegate: TransitionerDelegate?
var animator: TransitionAnimatorType = MockTransitionAnimator(orientation: .unknown)
var interactor: TransitionInteractor?
}
class TransitionCombinatorTests: XCTestCase {
var mockDelegate: MockTransitionerDelegate!
var transitionCombinator: TransitionCombinator!
var mockFirstTransitioner: MockTransitioner!
var mockSecondTransitioner: MockTransitioner!
var mockDefaultAnimator: MockTransitionAnimator!
override func setUp() {
mockDelegate = MockTransitionerDelegate()
mockFirstTransitioner = MockTransitioner()
mockSecondTransitioner = MockTransitioner()
mockDefaultAnimator = MockTransitionAnimator(orientation: .unknown)
transitionCombinator = TransitionCombinator(defaultAnimator: mockDefaultAnimator, transitioners: mockFirstTransitioner, mockSecondTransitioner)
transitionCombinator.delegate = mockDelegate
}
func testInit() {
XCTAssert(mockFirstTransitioner.delegate === transitionCombinator)
XCTAssert(mockSecondTransitioner.delegate === transitionCombinator)
XCTAssert(transitionCombinator.animator === mockDefaultAnimator)
XCTAssert(transitionCombinator.interactor === nil)
}
func testBeginTransition_FirstTransitioner() {
transitionCombinator.beginTransition(with: mockFirstTransitioner)
XCTAssert(mockDelegate.beginCalled.transitioner === mockFirstTransitioner)
XCTAssert(transitionCombinator.animator === mockFirstTransitioner.animator)
XCTAssert(transitionCombinator.interactor === mockFirstTransitioner.interactor)
}
func testBeginTransition_SecondTransitioner() {
transitionCombinator.beginTransition(with: mockSecondTransitioner)
XCTAssert(mockDelegate.beginCalled.transitioner === mockSecondTransitioner)
XCTAssert(transitionCombinator.animator === mockSecondTransitioner.animator)
XCTAssert(transitionCombinator.interactor === mockSecondTransitioner.interactor)
}
func testFinishedTransition_Completed_True() {
transitionCombinator.finishedInteractiveTransition(true)
XCTAssert(mockDelegate.finishCalled.completed == true)
XCTAssert(transitionCombinator.animator === mockDefaultAnimator)
XCTAssert(transitionCombinator.interactor === nil)
}
func testFinishedTransition_Completed_False() {
transitionCombinator.finishedInteractiveTransition(false)
XCTAssert(mockDelegate.finishCalled.completed == false)
XCTAssert(transitionCombinator.animator === mockDefaultAnimator)
XCTAssert(transitionCombinator.interactor === nil)
}
func testAddTransitioner() {
let newTransitioner = MockTransitioner()
let count = transitionCombinator.transitioners.count
transitionCombinator.add(newTransitioner)
XCTAssert(newTransitioner.delegate === transitionCombinator)
XCTAssert(transitionCombinator.transitioners.count - count == 1)
}
func testRemoveTransitioner_DoesntExist() {
let newTransitioner = MockTransitioner()
let count = transitionCombinator.transitioners.count
transitionCombinator.remove(newTransitioner)
XCTAssert(count == transitionCombinator.transitioners.count)
}
func testRemoveTransitioner_DoesExist_NoNeedForDelay() {
let newTransitioner = MockTransitioner()
transitionCombinator.add(newTransitioner)
let count = transitionCombinator.transitioners.count
transitionCombinator.remove(newTransitioner)
XCTAssert(count - transitionCombinator.transitioners.count == 1)
XCTAssert(!transitionCombinator.transitioners.contains(where: { $0 === newTransitioner }))
}
func testRemoveTransitioner_DoesExist_NeedsDelay() {
let newTransitioner = MockTransitioner()
transitionCombinator.add(newTransitioner)
let count = transitionCombinator.transitioners.count
transitionCombinator.beginTransition(with: mockFirstTransitioner)
transitionCombinator.remove(newTransitioner)
XCTAssert(count == transitionCombinator.transitioners.count)
XCTAssert(transitionCombinator.transitioners.contains(where: { $0 === newTransitioner }))
transitionCombinator.finishedInteractiveTransition(true)
XCTAssert(count - transitionCombinator.transitioners.count == 1)
XCTAssert(!transitionCombinator.transitioners.contains(where: { $0 === newTransitioner }))
}
func testAllowedOrientations_ShouldNotApplyWhenNil() {
let initialOrientations: [TransitionOrientation] = [.leftToRight]
mockFirstTransitioner.animator.allowedOrientations = initialOrientations
transitionCombinator = TransitionCombinator(transitioners: mockFirstTransitioner)
XCTAssert(initialOrientations == mockFirstTransitioner.animator.allowedOrientations!)
let newTransitioner = MockTransitioner()
newTransitioner.animator.allowedOrientations = initialOrientations
transitionCombinator.add(newTransitioner)
XCTAssert(initialOrientations == newTransitioner.animator.allowedOrientations!)
}
func testAllowedOrientations_ShouldApply() {
let orientations: [TransitionOrientation] = [.leftToRight]
mockFirstTransitioner.animator.allowedOrientations = orientations
transitionCombinator = TransitionCombinator(transitioners: mockFirstTransitioner)
let allowedOrientations: [TransitionOrientation] = [.bottomToTop]
transitionCombinator.allowedOrientations = allowedOrientations
XCTAssert(allowedOrientations == mockFirstTransitioner.animator.allowedOrientations!)
let newTransitioner = MockTransitioner()
newTransitioner.animator.allowedOrientations = orientations
transitionCombinator.add(newTransitioner)
XCTAssert(allowedOrientations == newTransitioner.animator.allowedOrientations!)
}
}
| b870d70c0e84d77d9a3139648b5890cf | 40.522293 | 151 | 0.724958 | false | true | false | false |
pmtao/SwiftUtilityFramework | refs/heads/master | SwiftUtilityFramework/Foundation/Timer/FixedDurationTimer.swift | mit | 1 | //
// FixedDurationTimer.swift
// SwiftUtilityFramework
//
// Created by 阿涛 on 18-7-4.
// Copyright © 2019年 SinkingSoul. All rights reserved.
//
import Foundation
/// 固定总时长的计时器(包括暂停时间)
public class FixedDurationTimer {
// MARK: --公开属性-----------
public var timer: DispatchSourceTimer?
public var isValid: Bool {
return timer != nil
}
/// 计时器状态
public var state: Poppin.State = .suspended
// MARK: --私有属性-----------
/// 计时开始的时间间隔
private var startTime: Int = 0
private var duration: Int = 0
private var endTime: Int = 0
private var repeating: Int = 0
private var observingPoints: [Int] = []
private var observingSlices: [(Int, Int)] = []
/// 计时精度
private var accuracy: Poppin.Accuracy = .microseconds
/// 后台处理的队列
private var backgroundHandleQueue: DispatchQueue?
/// UI 处理闭包
private var uiHandler: ((_ remainingTime: Int) -> Void)? = nil
/// 后台处理闭包
private var backgroundHandler: ((_ remainingTime: Int) -> Void)? = nil
/// 开始时间戳(纳秒)
private var startTimestamp: Int = 0
/// 最后一次启动时间戳(纳秒)
private var latestStartTimestamp: Int = 0
/// 最后一次暂停时间戳(纳秒)
private var latestSuspendTimestamp: Int = 0
/// 总运行时间(纳秒)
private var totalRunningTime: Int = 0
/// 总暂停时间(纳秒)
private var totalSuspendedTime: Int = 0
// MARK: --公开方法-----------
/// 启动新的计时器,指定开始时间和总时长(包括暂停时间),按照固定的时间间隔循环执行事件,从开始时间立即执行。
///
/// - Parameters:
/// - startTime: 几秒后开始
/// - duration: 总时长
/// - repeating: 时间间隔秒数
/// - accuracy: 时间精度
/// - backgroundQueue: 用于后台处理的队列
/// - uiHandler: UI 相关的事件处理闭包
/// - backgroundHandler: 后台相关的事件处理闭包
/// - remainingTime: 剩余时间
public func startFixedDurationTimer(
from startTime: Int = 0,
duration: Int,
repeating: Int,
accuracy: Poppin.Accuracy = .microseconds,
backgroundQueue: DispatchQueue? = nil,
uiHandler: ((_ remainingTime: Int) -> Void)? = nil,
backgroundHandler: ((_ remainingTime: Int) -> Void)? = nil)
{
// 重置内部属性
resetProperties()
// 创建新计时器
let timer = createFixedDurationTimer(
from: startTime,
duration: duration,
repeating: repeating,
accuracy: accuracy,
backgroundQueue: backgroundQueue,
uiHandler: uiHandler,
backgroundHandler: backgroundHandler)
// 取消现有计时器
if self.isValid {
switch state {
case .running:
cancel()
case .suspended:
resume()
cancel()
default:
break
}
}
self.timer = timer
resume()
}
/// 激活计时器
public func resume() {
// if state == .canceled {
// return
// }
// 在 canceled / suspended 状态下都可以启动
if state == .running {
return
} else {
let currentTimeStamp = Date.getTimeStamp(.nanoseconds)
if latestSuspendTimestamp > 0 {
// 记录暂停时间
totalSuspendedTime += currentTimeStamp - latestSuspendTimestamp
// 在暂停之后又重新恢复前,需要重新创建计时器,以解决暂停时积压的时间信号。
// 如果继续使用原有计时器,在恢复计时后,前两次发出的时间信号将不准确(短于间隔时间)。
let remainingTime = startTimestamp + duration.getNanoseconds(accuracy) - currentTimeStamp
print("已计时: \(totalRunningTime.toTimeStamp(.milliseconds)) 毫秒")
print("已暂停: \(totalSuspendedTime.toTimeStamp(.milliseconds)) 毫秒")
print("剩余: \(remainingTime.toTimeStamp(.milliseconds)) 毫秒")
if remainingTime <= 0 {
// 此时已超过原定的持续时间,计时器应取消。
self.timer?.resume()
self.timer?.cancel()
self.timer = nil
self.state = .canceled
print("计时器已超时取消 at \(currentTimeStamp.toTimeStamp(.milliseconds)) 毫秒")
return
} else {
// 创建新的计时器,并替换现有的计时器,保持原有持续时间不变。
let newTimer = createFixedDurationTimer(
from: 0,
duration: duration,
repeating: repeating,
accuracy: accuracy,
backgroundQueue: backgroundHandleQueue,
uiHandler: uiHandler,
backgroundHandler: backgroundHandler)
self.timer?.resume()
self.timer?.cancel()
self.timer = nil
print("原计时器已取消,已替换为新的计时器。")
self.timer = newTimer
}
}
timer?.resume()
state = .running
latestStartTimestamp = currentTimeStamp
print("计时器启动了:\(currentTimeStamp.toTimeStamp(.milliseconds)) 毫秒")
}
}
/// 暂停计时器
public func suspend() {
if state == .canceled {
return
}
if state == .suspended {
return
} else {
let currentTimeStamp = Date.getTimeStamp(.nanoseconds)
// 记录运行时间
totalRunningTime += currentTimeStamp - latestStartTimestamp
timer?.suspend()
state = .suspended
latestSuspendTimestamp = currentTimeStamp
print("计时器暂停了:\(currentTimeStamp.toTimeStamp(.milliseconds)) 毫秒")
}
}
/// 取消计时器
public func cancel(_ message: String = "") {
if state == .canceled {
return
} else {
if state != .running {
resume()
}
timer?.setEventHandler{}
timer?.cancel()
timer = nil
state = .canceled
print("计时器取消了:\(Date.getTimeStamp(.milliseconds)) 毫秒 from \(message)")
}
}
// MARK: --私有方法-----------
/// 创建计时器,指定开始时间和总时长(包括暂停时间),按照固定的时间间隔循环执行事件,从开始时间立即执行。
///
/// - Parameters:
/// - startTime: 几秒后开始
/// - duration: 总时长
/// - repeating: 时间间隔秒数
/// - accuracy: 时间精度
/// - backgroundQueue: 用于后台处理的队列
/// - uiHandler: UI 相关的事件处理闭包
/// - backgroundHandler: 后台相关的事件处理闭包
/// - remainingTime: 剩余时间
private func createFixedDurationTimer(
from startTime: Int = 0,
duration: Int,
repeating: Int,
accuracy: Poppin.Accuracy = .microseconds,
backgroundQueue: DispatchQueue? = nil,
uiHandler: ((_ remainingTime: Int) -> Void)? = nil,
backgroundHandler: ((_ remainingTime: Int) -> Void)? = nil)
-> DispatchSourceTimer?
{
self.startTime = startTime
self.duration = duration
self.repeating = repeating
self.accuracy = accuracy
self.backgroundHandleQueue = backgroundQueue
self.uiHandler = uiHandler
self.backgroundHandler = backgroundHandler
// 数据有效性校验
if startTime < 0 {
return nil
}
if duration <= 0 {
return nil
}
if repeating <= 0 {
return nil
}
if repeating > duration {
return nil
}
let timer = DispatchSource.makeTimerSource()
print("核心计时器已创建:\(timer) at \(Date.getTimeStamp(.nanoseconds)) 纳秒")
timer.schedule(deadline: .now() + .nanoseconds(startTime.getNanoseconds(accuracy)),
repeating: .nanoseconds(repeating.getNanoseconds(accuracy)),
leeway: .nanoseconds(1.getNanoseconds(accuracy)))
timer.setEventHandler {
let currentTimeStamp = Date.getTimeStamp(.nanoseconds)
print("currentTimeStamp: \(currentTimeStamp) 纳秒")
// 记录第一次启动时间
if self.startTimestamp == 0 {
self.startTimestamp = currentTimeStamp
self.latestStartTimestamp = currentTimeStamp
print("startTimestamp: \(self.startTimestamp) 纳秒")
}
let remainingTime = (self.startTimestamp + self.duration.getNanoseconds(accuracy)) - currentTimeStamp
print("剩余时间:\(remainingTime) 纳秒")
let uiHandler = self.prepareEventHandler(queue: DispatchQueue.main, handler: uiHandler)
let backgroundHandler = self.prepareEventHandler(queue: backgroundQueue, handler: backgroundHandler)
if self.state == .running {
// 计时器未结束时,继续执行。
if remainingTime > 0 {
print("\n开始执行计时器事件:\(Date.getTimeStamp(.microseconds)) 微秒====>")
uiHandler(remainingTime)
backgroundHandler(remainingTime)
print("结束计时器事件:\(Date.getTimeStamp(.microseconds)) 微秒 <====\n")
}
// 还有不足间隔时间的剩余时间,延迟到结束时再执行一次。
if remainingTime <= repeating.getNanoseconds(accuracy)
&& remainingTime > 0 {
self.cancel("还有不足间隔时间的剩余时间 \(remainingTime) 纳秒") // 先取消计时器
DispatchQueue.global().asyncAfter(
deadline: .now() + .nanoseconds(remainingTime)) {
uiHandler(0)
backgroundHandler(0)
}
}
// 计时器刚结束,继续执行。
if remainingTime == 0 {
self.cancel("计时器刚结束") // 取消计时器
uiHandler(remainingTime)
backgroundHandler(remainingTime)
}
// 已过时效,取消计时器。
if remainingTime < 0 {
self.cancel("已过时效,取消计时器")
}
} else if self.state == .suspended {
// 当前如果是暂停状态,事件无需执行。
print("计时器已取消了:\(Date.getTimeStamp(.microseconds)) 毫秒")
}
}
return timer
}
// MARK: --辅助方法-----------
/// 准备事件处理闭包
func prepareEventHandler(queue: DispatchQueue? = nil,
handler: ((_ remainingTime: Int) -> Void)? = nil)
-> ((Int) -> Void)
{
let packedHandler = { (_ remainingTime: Int) in
if queue == nil {
if handler != nil {
handler!(remainingTime)
}
} else {
if handler != nil {
queue!.async {
handler!(remainingTime)
}
}
}
}
return packedHandler
}
/// 重置内部属性,在启动新计时器第一步时使用。
private func resetProperties() {
state = .suspended
startTime = 0
startTimestamp = 0
duration = 0
endTime = 0
repeating = 0
observingPoints = []
observingSlices = []
backgroundHandleQueue = nil
uiHandler = nil
backgroundHandler = nil
accuracy = .microseconds
latestStartTimestamp = 0
latestSuspendTimestamp = 0
totalRunningTime = 0
totalSuspendedTime = 0
}
}
| 390d052b65aae42e38730d4819a4749c | 31.997093 | 113 | 0.507885 | false | false | false | false |
OSzhou/MyTestDemo | refs/heads/master | PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-HTTPServer.git--6671958091389663080/Sources/PerfectHTTPServer/HTTP2/HTTP2Frame.swift | apache-2.0 | 2 | //
// HTTP2Frame.swift
// PerfectHTTPServer
//
// Created by Kyle Jessup on 2017-06-20.
enum HTTP2FrameType: UInt8 {
case data = 0x0
case headers = 0x1
case priority = 0x2
case cancelStream = 0x3
case settings = 0x4
case pushPromise = 0x5
case ping = 0x6
case goAway = 0x7
case windowUpdate = 0x8
case continuation = 0x9
var description: String {
switch self {
case .data: return "HTTP2_DATA"
case .headers: return "HTTP2_HEADERS"
case .priority: return "HTTP2_PRIORITY"
case .cancelStream: return "HTTP2_RST_STREAM"
case .settings: return "HTTP2_SETTINGS"
case .pushPromise: return "HTTP2_PUSH_PROMISE"
case .ping: return "HTTP2_PING"
case .goAway: return "HTTP2_GOAWAY"
case .windowUpdate: return "HTTP2_WINDOW_UPDATE"
case .continuation: return "HTTP2_CONTINUATION"
}
}
}
typealias HTTP2FrameFlag = UInt8
let flagEndStream: HTTP2FrameFlag = 0x1
let flagEndHeaders: HTTP2FrameFlag = 0x4
let flagPadded: HTTP2FrameFlag = 0x8
let flagPriority: HTTP2FrameFlag = 0x20
let flagSettingsAck: HTTP2FrameFlag = 0x1
let flagPingAck: HTTP2FrameFlag = 0x1
struct HTTP2Frame {
let length: UInt32 // 24-bit
let type: HTTP2FrameType
let flags: UInt8
let streamId: UInt32 // 31-bit
var payload: [UInt8]?
var sentCallback: ((Bool) -> ())? = nil
var willSendCallback: (() -> ())? = nil
// Deprecate this
init(length: UInt32,
type: UInt8,
flags: UInt8 = 0,
streamId: UInt32 = 0,
payload: [UInt8]? = nil) {
self.length = length
self.type = HTTP2FrameType(rawValue: type)!
self.flags = flags
self.streamId = streamId
self.payload = payload
}
init(type: HTTP2FrameType,
flags: UInt8 = 0,
streamId: UInt32 = 0,
payload: [UInt8]? = nil) {
self.length = UInt32(payload?.count ?? 0)
self.type = type
self.flags = flags
self.streamId = streamId
self.payload = payload
}
var typeStr: String {
return type.description
}
var flagsStr: String {
var s = ""
if flags == 0 {
s.append("NO FLAGS")
}
if (flags & flagEndStream) != 0 {
s.append(" +HTTP2_END_STREAM")
}
if (flags & flagEndHeaders) != 0 {
s.append(" +HTTP2_END_HEADERS")
}
return s
}
func headerBytes() -> [UInt8] {
var data = [UInt8]()
let l = length.hostToNet >> 8
data.append(UInt8(l & 0xFF))
data.append(UInt8((l >> 8) & 0xFF))
data.append(UInt8((l >> 16) & 0xFF))
data.append(type.rawValue)
data.append(flags)
let s = streamId.hostToNet
data.append(UInt8(s & 0xFF))
data.append(UInt8((s >> 8) & 0xFF))
data.append(UInt8((s >> 16) & 0xFF))
data.append(UInt8((s >> 24) & 0xFF))
return data
}
}
| d8d8cd28af1f8d96e602bc39bca4da80 | 22.026549 | 50 | 0.667179 | false | false | false | false |
OSzhou/MyTestDemo | refs/heads/master | 17_SwiftTestCode/TestCode/CustomAlbum/Source/Data/HEPickerOptions.swift | apache-2.0 | 1 | //
// HEPickerOptions.swift
// HEPhotoPicker
//
// Created by apple on 2018/11/20.
// Copyright (c) 2018 heyode <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public enum HEMediaType : Int {
/// 只显示图片
case image
/// 只显示视频
case video
/// 所有类型都显示,并且都可以选择
case imageAndVideo
/// 所有类型都显示,但只能选一类
case imageOrVideo
}
open class HEPickerOptions: NSObject {
/// 要挑选的数据类型
public var mediaType : HEMediaType = .imageAndVideo
/// 列表是否按创建时间升序排列
public var ascendingOfCreationDateSort : Bool = false
/// 挑选图片的最大个数
public var maxCountOfImage = 9
/// 挑选视频的最大个数
public var maxCountOfVideo = 2
/// 是否支持图片单选,默认是false,如果是ture只允许选择一张图片(如果 mediaType = imageAndVideo 或者 imageOrVideo 此属性无效)
public var singlePicture = false
/// 是否支持视频单选 默认是false,如果是ture只允许选择一个视频(如果 mediaType = imageAndVideo 此属性无效)
public var singleVideo = false
/// 实现多次累加选择时,需要传入的选中的模型。为空时表示不需要多次累加
public var defaultSelections : [HEPhotoAsset]?
/// 选中样式图片
public var selectedImage = UIImage.heinit(name: "btn-check-selected")
/// 未选中样式图片
public var unselectedImage = UIImage.heinit(name: "btn-check-normal")
/// 自定义字符串
public var cancelButtonTitle = "取消"
public var selectDoneButtonTitle = "选择"
public var maxPhotoWaringTips = "最多只能选择%d个照片"
public var maxVideoWaringTips = "最多只能选择%d个视频"
}
| a60ed1d9220ed99c401762f3b325db43 | 36.8 | 94 | 0.719984 | false | false | false | false |
briceZhao/ZXRefresh | refs/heads/master | ZXRefreshExample/ZXRefreshExample/Default/DefaultCollectionViewController.swift | mit | 1 | //
// DefaultCollectionViewController.swift
// ZXRefreshExample
//
// Created by briceZhao on 2017/8/22.
// Copyright © 2017年 chengyue. All rights reserved.
//
import UIKit
private let reuseIdentifier = "DefaultCollectionViewCellId"
class DefaultCollectionViewController: UIViewController, UICollectionViewDataSource{
var collectionView: UICollectionView?
override func viewDidLoad() {
self.view.backgroundColor = UIColor.white
self.setUpCollectionView()
self.collectionView?.addRefreshHeaderView {
[unowned self] in
self.refresh()
}
self.collectionView?.addLoadMoreFooterView {
[unowned self] in
self.loadMore()
}
}
func refresh() {
perform(#selector(endRefresing), with: nil, afterDelay: 3)
}
func endRefresing() {
self.collectionView?.endRefreshing(isSuccess: true)
}
func loadMore() {
perform(#selector(endLoadMore), with: nil, afterDelay: 3)
}
func endLoadMore() {
self.collectionView?.endLoadMore(isNoMoreData: true)
}
func setUpCollectionView() {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = UICollectionViewScrollDirection.vertical
flowLayout.itemSize = CGSize(width: 100, height: 100)
self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
self.collectionView?.backgroundColor = UIColor.white
self.collectionView?.dataSource = self
self.view.addSubview(self.collectionView!)
self.collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 21
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.backgroundColor = UIColor.lightGray
return cell
}
deinit{
print("Deinit of DefaultCollectionViewController")
}
}
| abfefafe4406e1ce3a1b7571f4c95dd3 | 29.102564 | 121 | 0.662692 | false | false | false | false |
gminky019/Content-Media-App | refs/heads/master | Content Media App/Content Media App/learnViewController.swift | apache-2.0 | 1 | //
// learnViewController.swift
//
//
// Created by Jordan Harris on 4/28/16.
//
//
/*
This is the controller for the learn content view page.
*/
import Foundation
class learnViewController: UIViewController{
@IBOutlet weak var navButton: UIBarButtonItem!
@IBOutlet weak var heroOneView: UIImageView!
@IBOutlet weak var heroOneIcon: UIImageView!
@IBOutlet weak var heroOneType: UITextView!
@IBOutlet weak var heroOneTitle: UITextView!
@IBOutlet weak var heroTwoView: UIImageView!
@IBOutlet weak var heroTwoIcon: UIImageView!
@IBOutlet weak var heroTwoType: UITextView!
@IBOutlet weak var heroTwoTitle: UITextView!
@IBOutlet weak var originalOne: UIImageView!
@IBOutlet weak var originalOneIcon: UIImageView!
@IBOutlet weak var originalTwo: UIImageView!
@IBOutlet weak var originalTwoIcon: UIImageView!
@IBOutlet weak var originalThree: UIImageView!
@IBOutlet weak var originalThreeIcon: UIImageView!
@IBOutlet weak var originalFour: UIImageView!
@IBOutlet weak var originalFourIcon: UIImageView!
@IBOutlet weak var originalFive: UIImageView!
@IBOutlet weak var originalFiveIcon: UIImageView!
@IBOutlet weak var originalSix: UIImageView!
@IBOutlet weak var originalSixIcon: UIImageView!
@IBOutlet weak var recentOne: UIImageView!
@IBOutlet weak var recentOneIcon: UIImageView!
@IBOutlet weak var recentOneType: UITextView!
@IBOutlet weak var recentOneTitle: UITextView!
@IBOutlet weak var recentTwo: UIImageView!
@IBOutlet weak var recentTwoIcon: UIImageView!
@IBOutlet weak var recentTwoType: UITextView!
@IBOutlet weak var recentTwoTitle: UITextView!
@IBOutlet weak var recentThree: UIImageView!
@IBOutlet weak var recentThreeIcon: UIImageView!
@IBOutlet weak var recentThreeType: UITextView!
@IBOutlet weak var recentThreeTitle: UITextView!
@IBOutlet weak var recentFour: UIImageView!
@IBOutlet weak var recentFourIcon: UIImageView!
@IBOutlet weak var recentFourType: UITextView!
@IBOutlet weak var recentFourTitle: UITextView!
@IBOutlet weak var recentFive: UIImageView!
@IBOutlet weak var recentFiveIcon: UIImageView!
@IBOutlet weak var recentFiveType: UITextView!
@IBOutlet weak var recentFiveTitle: UITextView!
@IBOutlet weak var recentSix: UIImageView!
@IBOutlet weak var recentSixIcon: UIImageView!
@IBOutlet weak var recentSixType: UITextView!
@IBOutlet weak var recentSixTitle: UITextView!
@IBOutlet weak var footerBackground: UIImageView!
@IBOutlet weak var footerImageOne: UIImageView!
@IBOutlet weak var footerImageTwo: UIImageView!
@IBOutlet weak var footerImageThree: UIImageView!
@IBOutlet weak var footerImageFour: UIImageView!
var articleClicked = "null"
var contDict: [String: ThumbNail] = [String: ThumbNail]()
var passedThumbnail: ThumbNail!
override func viewDidLoad(){
// Declarations
let imageView = UIImageView(frame: CGRect(x:0, y:0, width: 86, height: 44))
let image = UIImage(named: "Logo.png")
imageView.contentMode = .ScaleAspectFit
imageView.image = image
navigationItem.titleView = imageView
var overlay : UIView
overlay = UIView(frame: view.frame)
let backgroundOverlay = UIImage(named: "BackgroundImageLoading2.png")
let backgroundView = UIImageView(image: backgroundOverlay)
var activityIndicator = UIActivityIndicatorView()
// Create Loading Screen
activityIndicator.frame = CGRectMake(0, 0, 40, 40)
activityIndicator.activityIndicatorViewStyle = .WhiteLarge
activityIndicator.center = CGPointMake(overlay.bounds.width / 2, (overlay.bounds.height / 3)*2)
backgroundView.addSubview(activityIndicator)
view.addSubview(backgroundView)
activityIndicator.startAnimating()
var integrate: MiddleIntegration = MiddleIntegration()
var content: ContentPage?
let typeColor = UIColor.init(red: 221/255, green: 180/255, blue: 0/255, alpha: 1)
// Load content from backend
integrate.getLearnPage(){ (returned: ContentPage) in
content = returned
var her1: ThumbNail = returned._heroes[0]
var her2: ThumbNail = returned._heroes[1]
var org1: ThumbNail = returned._others[0]
var org2: ThumbNail = returned._others[1]
var org3: ThumbNail = returned._others[2]
var org4: ThumbNail = returned._others[3]
var org5: ThumbNail = returned._others[4]
var org6: ThumbNail = returned._others[5]
var rec1: ThumbNail = returned._others[6]
var rec2: ThumbNail = returned._others[7]
var rec3: ThumbNail = returned._others[8]
var rec4: ThumbNail = returned._others[9]
var rec5: ThumbNail = returned._others[10]
var rec6: ThumbNail = returned._others[11]
self.contDict["HeroOne"] = her1
self.contDict["HeroTwo"] = her2
self.contDict["OriginalOne"] = org1
self.contDict["OriginalTwo"] = org2
self.contDict["OriginalThree"] = org3
self.contDict["OriginalFour"] = org4
self.contDict["OriginalFive"] = org5
self.contDict["OriginalSix"] = org6
self.contDict["RecentOne"] = rec1
self.contDict["RecentTwo"] = rec2
self.contDict["RecentThree"] = rec3
self.contDict["RecentFour"] = rec4
self.contDict["RecentFive"] = rec5
self.contDict["RecentSix"] = rec6
self.heroOneView.image = her1.pic
self.heroOneTitle.text = her1.title
self.heroOneType.text = "READ"
self.heroOneIcon.image = UIImage (named: "readicon.png")
self.heroTwoView.image = her2.pic
self.heroTwoTitle.text = her2.title
self.heroTwoType.text = "READ"
self.heroTwoIcon.image = UIImage (named: "readicon.png")
self.originalOne.image = org1.pic
self.originalOneIcon.image = UIImage (named: "readiconsmall.png")
self.originalTwo.image = org2.pic
self.originalTwoIcon.image = UIImage (named: "readiconsmall.png")
self.originalThree.image = org3.pic
self.originalThreeIcon.image = UIImage (named: "readiconsmall.png")
self.originalFour.image = org4.pic
self.originalFourIcon.image = UIImage (named: "readiconsmall.png")
self.originalFive.image = org5.pic
self.originalFiveIcon.image = UIImage (named: "readiconsmall.png")
self.originalSix.image = org6.pic
self.originalSixIcon.image = UIImage (named: "readiconsmall.png")
self.recentOne.image = rec1.pic
self.recentOneIcon.image = UIImage (named: "readiconsmall.png")
self.recentOneTitle.text = rec1.title
self.recentOneType.text = "READ"
self.recentTwo.image = rec2.pic
self.recentTwoIcon.image = UIImage (named: "readiconsmall.png")
self.recentTwoTitle.text = rec2.title
self.recentTwoType.text = "READ"
self.recentThree.image = rec3.pic
self.recentThreeIcon.image = UIImage (named: "readiconsmall.png")
self.recentThreeTitle.text = rec3.title
self.recentThreeType.text = "READ"
self.recentFour.image = rec4.pic
self.recentFourIcon.image = UIImage (named: "readiconsmall.png")
self.recentFourTitle.text = rec4.title
self.recentFourType.text = "READ"
self.recentFive.image = rec5.pic
self.recentFiveIcon.image = UIImage (named: "readiconsmall.png")
self.recentFiveTitle.text = rec5.title
self.recentFiveType.text = "READ"
self.recentSix.image = rec6.pic
self.recentSixIcon.image = UIImage (named: "readiconsmall.png")
self.recentSixTitle.text = rec6.title
self.recentSixType.text = "READ"
self.heroOneTitle.font = UIFont(name: "Roboto-Bold", size: 18)
self.heroOneTitle.textColor = UIColor.whiteColor()
self.heroOneType.font = UIFont(name: "Roboto-Medium", size: 12)
self.heroOneType.textColor = typeColor
self.heroTwoTitle.font = UIFont(name: "Roboto-Bold", size: 18)
self.heroTwoTitle.textColor = UIColor.whiteColor()
self.heroTwoType.font = UIFont(name: "Roboto-Medium", size: 12)
self.heroTwoType.textColor = typeColor
self.recentOneType.font = UIFont(name: "Roboto-Medium", size: 12)
self.recentOneType.textColor = typeColor
self.recentOneType.textAlignment = .Center
self.recentOneTitle.font = UIFont(name: "Roboto-Bold", size: 14)
self.recentOneTitle.textColor = UIColor.blackColor()
self.recentOneTitle.textAlignment = .Center
self.recentTwoType.font = UIFont(name: "Roboto-Medium", size: 12)
self.recentTwoType.textColor = typeColor
self.recentTwoType.textAlignment = .Center
self.recentTwoTitle.font = UIFont(name: "Roboto-Bold", size: 14)
self.recentTwoTitle.textColor = UIColor.blackColor()
self.recentTwoTitle.textAlignment = .Center
self.recentThreeType.font = UIFont(name: "Roboto-Medium", size: 12)
self.recentThreeType.textColor = typeColor
self.recentThreeType.textAlignment = .Center
self.recentThreeTitle.font = UIFont(name: "Roboto-Bold", size: 14)
self.recentThreeTitle.textColor = UIColor.blackColor()
self.recentThreeTitle.textAlignment = .Center
self.recentFourType.font = UIFont(name: "Roboto-Medium", size: 12)
self.recentFourType.textColor = typeColor
self.recentFourType.textAlignment = .Center
self.recentFourTitle.font = UIFont(name: "Roboto-Bold", size: 14)
self.recentFourTitle.textColor = UIColor.blackColor()
self.recentFourTitle.textAlignment = .Center
self.recentFiveType.font = UIFont(name: "Roboto-Medium", size: 12)
self.recentFiveType.textColor = typeColor
self.recentFiveType.textAlignment = .Center
self.recentFiveTitle.font = UIFont(name: "Roboto-Bold", size: 14)
self.recentFiveTitle.textColor = UIColor.blackColor()
self.recentFiveTitle.textAlignment = .Center
self.recentSixType.font = UIFont(name: "Roboto-Medium", size: 12)
self.recentSixType.textColor = typeColor
self.recentSixType.textAlignment = .Center
self.recentSixTitle.font = UIFont(name: "Roboto-Bold", size: 14)
self.recentSixTitle.textColor = UIColor.blackColor()
self.recentSixTitle.textAlignment = .Center
backgroundView.removeFromSuperview()
}
// Setup Footer
footerBackground.image = UIImage(named: "black.png")
footerImageOne.image = UIImage(named: "twitter2.png")
footerImageTwo.image = UIImage(named: "facebook2.png")
footerImageThree.image = UIImage(named: "youtube2.png")
footerImageFour.image = UIImage(named: "instagram2.png")
// Setup correct tags for all articles
heroOneView.tag = 1
heroOneView.userInteractionEnabled = true
let tapRecognizerHeroOne = UITapGestureRecognizer(target: self, action: "imageTapped:")
heroOneView.addGestureRecognizer(tapRecognizerHeroOne)
heroTwoView.tag = 2
heroTwoView.userInteractionEnabled = true
let tapRecognizerHeroTwo = UITapGestureRecognizer(target: self, action: "imageTapped:")
heroTwoView.addGestureRecognizer(tapRecognizerHeroTwo)
originalOne.tag = 3
originalOne.userInteractionEnabled = true
let tapRecognizerOrgOne = UITapGestureRecognizer(target: self, action: "imageTapped:")
originalOne.addGestureRecognizer(tapRecognizerOrgOne)
originalTwo.tag = 4
originalTwo.userInteractionEnabled = true
let tapRecognizerOrgTwo = UITapGestureRecognizer(target: self, action: "imageTapped:")
originalTwo.addGestureRecognizer(tapRecognizerOrgTwo)
originalThree.tag = 5
originalThree.userInteractionEnabled = true
let tapRecognizerOrgThree = UITapGestureRecognizer(target: self, action: "imageTapped:")
originalThree.addGestureRecognizer(tapRecognizerOrgThree)
originalFour.tag = 6
originalFour.userInteractionEnabled = true
let tapRecognizerOrgFour = UITapGestureRecognizer(target: self, action: "imageTapped:")
originalFour.addGestureRecognizer(tapRecognizerOrgFour)
originalFive.tag = 7
originalFive.userInteractionEnabled = true
let tapRecognizerOrgFive = UITapGestureRecognizer(target: self, action: "imageTapped:")
originalFive.addGestureRecognizer(tapRecognizerOrgFive)
originalSix.tag = 8
originalSix.userInteractionEnabled = true
let tapRecognizerOrgSix = UITapGestureRecognizer(target: self, action: "imageTapped:")
originalSix.addGestureRecognizer(tapRecognizerOrgSix)
recentOne.tag = 9
recentOne.userInteractionEnabled = true
let tapRecognizerRecOne = UITapGestureRecognizer(target: self, action: "imageTapped:")
recentOne.addGestureRecognizer(tapRecognizerRecOne)
recentTwo.tag = 10
recentTwo.userInteractionEnabled = true
let tapRecognizerRecTwo = UITapGestureRecognizer(target: self, action: "imageTapped:")
recentTwo.addGestureRecognizer(tapRecognizerRecTwo)
recentThree.tag = 11
recentThree.userInteractionEnabled = true
let tapRecognizerRecThree = UITapGestureRecognizer(target: self, action: "imageTapped:")
recentThree.addGestureRecognizer(tapRecognizerRecThree)
recentFour.tag = 12
recentFour.userInteractionEnabled = true
let tapRecognizerRecFour = UITapGestureRecognizer(target: self, action: "imageTapped:")
recentFour.addGestureRecognizer(tapRecognizerRecFour)
recentFive.tag = 13
recentFive.userInteractionEnabled = true
let tapRecognizerRecFive = UITapGestureRecognizer(target: self, action: "imageTapped:")
recentFive.addGestureRecognizer(tapRecognizerRecFive)
recentSix.tag = 14
recentSix.userInteractionEnabled = true
let tapRecognizerRecSix = UITapGestureRecognizer(target: self, action: "imageTapped:")
recentSix.addGestureRecognizer(tapRecognizerRecSix)
if self.revealViewController() != nil {
navButton.target = self.revealViewController()
navButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
// This function makes sure the correct article is sent to the article view when an image is tapped
func imageTapped(gestureRecognizer: UITapGestureRecognizer) {
switch gestureRecognizer.view!.tag {
case 1:
articleClicked = "Hero One"
passedThumbnail = self.contDict["HeroOne"]!
case 2:
articleClicked = "Hero Two"
passedThumbnail = self.contDict["HeroTwo"]
case 3:
articleClicked = "Original One"
passedThumbnail = self.contDict["OriginalOne"]
case 4:
articleClicked = "Original Two"
passedThumbnail = self.contDict["OriginalTwo"]
case 5:
articleClicked = "Original Three"
passedThumbnail = self.contDict["OriginalThree"]
case 6:
articleClicked = "Original Four"
passedThumbnail = self.contDict["OriginalFour"]
case 7:
articleClicked = "Original Five"
passedThumbnail = self.contDict["OriginalFive"]
case 8:
articleClicked = "Original Six"
passedThumbnail = self.contDict["OriginalSix"]
case 9:
articleClicked = "Recent One"
passedThumbnail = self.contDict["RecentOne"]
case 10:
articleClicked = "Recent Two"
passedThumbnail = self.contDict["RecentTwo"]
case 11:
articleClicked = "Recent Three"
passedThumbnail = self.contDict["RecentThree"]
case 12:
articleClicked = "Recent Four"
passedThumbnail = self.contDict["RecentFour"]
case 13:
articleClicked = "Recent Five"
passedThumbnail = self.contDict["RecentFive"]
case 14:
articleClicked = "Recent Six"
passedThumbnail = self.contDict["RecentSix"]
default:
articleClicked = "null"
}
self.performSegueWithIdentifier("goToArticle", sender: self)
}
// This function overrides the prepareForSegue to allow passing of objects.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let DestViewController : articleViewController = segue.destinationViewController as! articleViewController
DestViewController.article = articleClicked
DestViewController.articleThumbnail = passedThumbnail
}
}
| 58d84b678b1e46ddda5795561b029c20 | 40.935632 | 114 | 0.636717 | false | false | false | false |
L-Zephyr/Drafter | refs/heads/master | Sources/Drafter/Utils/Path+Extension.swift | mit | 1 | //
// Path+Extension.swift
// DrafterTests
//
// Created by LZephyr on 2018/5/16.
//
import Foundation
import PathKit
/// 文件类型
enum FileType: Int, AutoCodable {
case h // 头文件
case m // 实现文件,包括.m和.mm
case swift // swift文件
case unknown
}
extension Path {
/// 获取该源码文件对应的缓存位置
func cachePath() -> Path {
let cacheDir = Path(NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]) + "Drafter"
if !cacheDir.exists {
try? FileManager.default.createDirectory(at: cacheDir.url, withIntermediateDirectories: true, attributes: nil)
}
let hash = self.absolute().string.hashValue
return cacheDir + "\(hash)"
}
/// 获取文件夹下的所有文件
///
/// - Returns: 返回所有文件的集合,如果本身是一个文件则仅返回自身
var files: [Path] {
if self.isFile {
return [self]
} else {
return Array(self)
}
}
/// 获取绝对路径的散列值
var pathHash: String {
return self.absolute().string.md5
}
/// 文件类型
var fileType: FileType {
switch self.extension {
case "h":
return .h
case "m": fallthrough
case "mm":
return .m
case "swift":
return .swift
default:
return .unknown
}
}
/// 该文件是否为swift文件
var isSwift: Bool {
return self.fileType == .swift
}
/// 该文件是否为oc文件,.h或.m
var isObjc: Bool {
return self.fileType == .m || self.fileType == .h
}
}
| 95ddcb9d848408444df39d9c3de90620 | 20.929577 | 122 | 0.539499 | false | false | false | false |
ndagrawal/TwitterRedux | refs/heads/master | TwitterRedux/TwitterClient.swift | mit | 1 | //
// TwitterClient.swift
// TwitterOAuthDemo
//
// Created by Nilesh on 10/10/15.
// Copyright © 2015 CA. All rights reserved.
//
import UIKit
let twitterConsumerKey = "RttV1EgioEIE49s2y5EhUfjHw"
let twitterConsumerSecret = "n1aKkRq9so4o9sUUyGejsEtyoApF0l5kmUGbauzDnlwLdQFNw1"
let twitterBaseURL = NSURL(string: "https://api.twitter.com")
class TwitterClient: BDBOAuth1RequestOperationManager {
var loginCompletion:((user:User?,error:NSError?)->())?
class var sharedInstance : TwitterClient {
struct Static {
static let instance = TwitterClient(baseURL:twitterBaseURL,consumerKey: twitterConsumerKey ,consumerSecret: twitterConsumerSecret)
}
return Static.instance
}
func homeTimelineWithParams(params:NSDictionary?,completion:(tweets:[Tweet]?,error:NSError?)->()){
GET("1.1/statuses/home_timeline.json", parameters: params, success: { (operation:AFHTTPRequestOperation!, response:AnyObject!) -> Void in
// print("home_timeline \(response)")
let tweets = Tweet.tweetsWithArray(response as! [NSDictionary])
print("Count of Tweets \(tweets.count)")
completion(tweets: tweets, error: nil)
}, failure: { (operation:AFHTTPRequestOperation!, error:NSError!) -> Void in
print("Failure to get timeline")
completion(tweets: nil, error: error)
})
}
func loginWithCompletion(completion:(user:User?,error:NSError?)->()){
loginCompletion = completion
//Fetch Request Token ?& Redirect to authorization page.
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
TwitterClient.sharedInstance.fetchRequestTokenWithPath("oauth/request_token", method: "GET", callbackURL: NSURL(string: "cptwitterdemo://oauth"), scope: nil, success: { (requestToken:BDBOAuth1Credential!) -> Void in
print("Got the Request Token")
let authURL = NSURL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token)")
UIApplication.sharedApplication().openURL(authURL!)
}, failure: { (error : NSError!) -> Void in
print("Error Occured")
self.loginCompletion? (user:nil,error:error)
})
}
func openURL(url:NSURL){
TwitterClient.sharedInstance.fetchAccessTokenWithPath("oauth/access_token", method: "POST", requestToken: BDBOAuth1Credential(queryString: url.query)!, success: { (accessToken:BDBOAuth1Credential!) -> Void in
print("Receied Access Token ")
TwitterClient.sharedInstance.requestSerializer.saveAccessToken(accessToken)
TwitterClient.sharedInstance.GET("1.1/account/verify_credentials.json", parameters: nil, success: { (operation:AFHTTPRequestOperation!, response:AnyObject!) -> Void in
let user = User(dictionary: response as! NSDictionary)
User.currentUser = user
print("user \(user.name!)")
self.loginCompletion?(user: user, error: nil)
}, failure: { (operation:AFHTTPRequestOperation!, error:NSError!) -> Void in
print("Failure to verify credentials")
})
}
) { (error:NSError!) -> Void in
print(" Failed to receive access token")
}
}
}
| 908e7201559cc3c3d6e2f0870f49faa4 | 38.103448 | 223 | 0.64903 | false | false | false | false |
Subsets and Splits