repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Drakken-Engine/GameEngine | DrakkenEngine_Editor/GameView.swift | 1 | 990 | //
// GameView.swift
// DrakkenEngine
//
// Created by Allison Lindner on 21/10/16.
// Copyright © 2016 Drakken Studio. All rights reserved.
//
import Cocoa
class GameView: dGameView {
let appDelegate = NSApplication.shared().delegate as! AppDelegate
override func Init() {
self.scene.load(data: appDelegate.editorViewController!.editorView.scene.toData()!)
// self.scene = appDelegate.editorViewController!.editorView.scene
self.scene.DEBUG_MODE = true
self.state = .STOP
super.Init()
}
override func internalUpdate() {
if appDelegate.editorViewController?.lastLogCount != dCore.instance.allDebugLogs.count {
appDelegate.editorViewController?.consoleView.reloadData()
appDelegate.editorViewController?.consoleView.scrollRowToVisible(dCore.instance.allDebugLogs.count - 1)
appDelegate.editorViewController?.lastLogCount = dCore.instance.allDebugLogs.count
}
}
}
| gpl-3.0 | cf5e1c9aedc6669537bfa7f8263e16fb | 33.103448 | 115 | 0.695652 | 4.356828 | false | false | false | false |
ahoppen/swift | test/Generics/sr14510.swift | 2 | 1501 | // RUN: %target-typecheck-verify-swift -warn-redundant-requirements
// RUN: %target-swift-frontend -debug-generic-signatures -typecheck %s 2>&1 | %FileCheck %s
// CHECK-LABEL: Requirement signature: <Self where Self == Self.[Adjoint]Dual.[Adjoint]Dual, Self.[Adjoint]Dual : Adjoint>
public protocol Adjoint {
associatedtype Dual: Adjoint where Self.Dual.Dual == Self
}
// CHECK-LABEL: Requirement signature: <Self>
public protocol Diffable {
associatedtype Patch
}
// CHECK-LABEL: Requirement signature: <Self where Self : Adjoint, Self : Diffable, Self.[Adjoint]Dual : AdjointDiffable, Self.[Diffable]Patch : Adjoint, Self.[Adjoint]Dual.[Diffable]Patch == Self.[Diffable]Patch.[Adjoint]Dual>
public protocol AdjointDiffable: Adjoint & Diffable
where Self.Patch: Adjoint, Self.Dual: AdjointDiffable,
Self.Patch.Dual == Self.Dual.Patch {
}
// This is another example used to hit the same problem. Any one of the three
// conformance requirements 'A : P', 'B : P' or 'C : P' can be dropped and
// proven from the other two, but dropping two or more conformance requirements
// leaves us with an invalid signature.
// CHECK-LABEL: Requirement signature: <Self where Self.[P]A : P, Self.[P]A == Self.[P]B.[P]C, Self.[P]B : P, Self.[P]B == Self.[P]A.[P]C, Self.[P]C == Self.[P]A.[P]B>
protocol P {
associatedtype A : P where A == B.C
associatedtype B : P where B == A.C
associatedtype C : P where C == A.B
// expected-warning@-1 {{redundant conformance constraint 'Self.C' : 'P'}}
}
| apache-2.0 | bbd6a2621b92fc2753f32d5a8b93dde4 | 47.419355 | 227 | 0.710193 | 3.395928 | false | false | false | false |
Mars182838/WJCycleScrollView | WJCycleScrollView/Extentions/BlockButton.swift | 2 | 3436 | //
// BlockButton.swift
//
//
// Created by Cem Olcay on 12/08/15.
//
//
import UIKit
public typealias BlockButtonAction = (sender: BlockButton) -> Void
///Make sure you use "[weak self] (sender) in" if you are using the keyword self inside the closure or there might be a memory leak
public class BlockButton: UIButton {
// MARK: Propeties
public var highlightLayer: CALayer?
public var action: BlockButtonAction?
// MARK: Init
public init() {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
defaultInit()
}
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
super.init(frame: CGRect(x: x, y: y, width: w, height: h))
defaultInit()
}
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, action: BlockButtonAction?) {
super.init (frame: CGRect(x: x, y: y, width: w, height: h))
self.action = action
defaultInit()
}
public init(action: BlockButtonAction) {
super.init(frame: CGRectZero)
self.action = action
defaultInit()
}
public override init(frame: CGRect) {
super.init(frame: frame)
defaultInit()
}
public init(frame: CGRect, action: BlockButtonAction) {
super.init(frame: frame)
self.action = action
defaultInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func defaultInit() {
addTarget(self, action: #selector(BlockButton.didPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
addTarget(self, action: #selector(BlockButton.highlight), forControlEvents: [UIControlEvents.TouchDown, UIControlEvents.TouchDragEnter])
addTarget(self, action: #selector(BlockButton.unhighlight), forControlEvents: [
UIControlEvents.TouchUpInside,
UIControlEvents.TouchUpOutside,
UIControlEvents.TouchCancel,
UIControlEvents.TouchDragExit
])
setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
setTitleColor(UIColor.blueColor(), forState: UIControlState.Selected)
}
public func addAction(action: BlockButtonAction) {
self.action = action
}
// MARK: Action
public func didPressed(sender: BlockButton) {
action?(sender: sender)
}
// MARK: Highlight
public func highlight() {
if action == nil {
return
}
let highlightLayer = CALayer()
highlightLayer.frame = layer.bounds
highlightLayer.backgroundColor = UIColor.blackColor().CGColor
highlightLayer.opacity = 0.5
var maskImage: UIImage? = nil
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, 0)
if let context = UIGraphicsGetCurrentContext() {
layer.renderInContext(context)
maskImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
let maskLayer = CALayer()
maskLayer.contents = maskImage?.CGImage
maskLayer.frame = highlightLayer.frame
highlightLayer.mask = maskLayer
layer.addSublayer(highlightLayer)
self.highlightLayer = highlightLayer
}
public func unhighlight() {
if action == nil {
return
}
highlightLayer?.removeFromSuperlayer()
highlightLayer = nil
}
}
| mit | 584c84d53135b06bcd06d457aadccaf7 | 29.40708 | 144 | 0.639115 | 4.745856 | false | false | false | false |
GalinaCode/Nutriction-Cal | NutritionCal/Nutrition Cal/FullItemDetailsViewController.swift | 1 | 7767 | //
// FullItemDetailsViewController.swift
// Nutrition Cal
//
// Created by Galina Petrova on 03/25/16.
// Copyright © 2015 Galina Petrova. All rights reserved.
//
import UIKit
import CoreData
import HealthKit
import MaterialDesignColor
import RKDropdownAlert
class FullItemDetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating {
var ndbItem: NDBItem!
let healthStore = HealthStore.sharedInstance()
var nutritionsArray: [NDBNutrient] = []
var filtredNutritionsArray: [NDBNutrient] = []
@IBOutlet weak var tableView: UITableView!
var searchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
nutritionsArray = ndbItem.nutrients!
tableView.delegate = self
tableView.dataSource = self
// UI customizations
tabBarController?.tabBar.tintColor = MaterialDesignColor.green500
navigationController?.navigationBar.tintColor = MaterialDesignColor.green500
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: MaterialDesignColor.green500]
// set the search controller
searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.sizeToFit()
// UI customizations
searchController.searchBar.tintColor = MaterialDesignColor.green500
let textFieldInsideSearchBar = searchController.searchBar.valueForKey("searchField") as? UITextField
textFieldInsideSearchBar?.textColor = MaterialDesignColor.green500
searchController.searchBar.barTintColor = MaterialDesignColor.grey200
tableView.tableHeaderView = self.searchController.searchBar
self.definesPresentationContext = true
}
// MARK: - Core Data Convenience
// Shared Context from CoreDataStackManager
var sharedContext: NSManagedObjectContext {
return CoreDataStackManager.sharedInstance().managedObjectContext
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchString = self.searchController.searchBar.text
if searchString?.characters.count > 0 {
filterContentForSearch(searchString!)
} else {
filtredNutritionsArray = nutritionsArray
}
tableView.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FullItemDetailsViewControllerTableViewCell")!
if searchController.active {
cell.textLabel?.text = filtredNutritionsArray[indexPath.row].name
let value = filtredNutritionsArray[indexPath.row].value! as Double
let roundedValue = Double(round(1000*value)/1000)
let valueText = "\(roundedValue) " + filtredNutritionsArray[indexPath.row].unit!
cell.detailTextLabel?.text = valueText
} else {
cell.textLabel?.text = nutritionsArray[indexPath.row].name
let value = nutritionsArray[indexPath.row].value! as Double
let roundedValue = Double(round(1000*value)/1000)
let valueText = "\(roundedValue) " + nutritionsArray[indexPath.row].unit!
cell.detailTextLabel?.text = valueText
}
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active {
return filtredNutritionsArray.count
} else {
return nutritionsArray.count
}
}
@IBAction func eatItBarButtonItemTapped(sender: UIBarButtonItem) {
let alert = UIAlertController(title: "Select Size:", message: "\(ndbItem.name) has many sizes, Please choose one to eat/drink:", preferredStyle: .ActionSheet)
let nutrients = ndbItem.nutrients
for nutrient in nutrients! {
if nutrient.id == 208 {
for measure in nutrient.measures! {
let action = UIAlertAction(title: measure.label!, style: .Default, handler: { (action) -> Void in
let qtyAlert = UIAlertController(title: "Enter Quanitity", message: "How many \(measure.label!) did you eat/drink ?", preferredStyle:
UIAlertControllerStyle.Alert)
qtyAlert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
textField.placeholder = "Enter quanitity"
textField.keyboardType = UIKeyboardType.NumberPad
textField.addTarget(self, action: "qtyTextChanged:", forControlEvents: .EditingChanged)
})
qtyAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
let eatAction = UIAlertAction(title: "Eat!", style: .Default, handler: { (action) -> Void in
let textField = qtyAlert.textFields?.first!
if textField != nil {
if let qty = Int(textField!.text!) {
// create a DayEntry for the item eated
dispatch_async(dispatch_get_main_queue()) {
_ = DayEntry(item: self.ndbItem!, measure: measure, qty: qty, context: self.sharedContext)
self.saveContext()
// show eated dropdown alert
dispatch_async(dispatch_get_main_queue()) {
_ = RKDropdownAlert.title("Added", message: "", backgroundColor: MaterialDesignColor.green500, textColor: UIColor.whiteColor(), time: 2)
}
}
if let healthStoreSync = NSUserDefaults.standardUserDefaults().valueForKey("healthStoreSync") as? Bool {
if healthStoreSync {
self.healthStore.addNDBItemToHealthStore(self.ndbItem, selectedMeasure: measure, qty: qty, completionHandler: { (success, errorString) -> Void in
if success {
dispatch_async(dispatch_get_main_queue()) {
print("\(self.ndbItem.name) added to helth app")
}
} else {
print(errorString!)
self.presentMessage("Oops!", message: errorString!, action: "OK")
}
})
}
}
}
}
})
eatAction.enabled = false
qtyAlert.addAction(eatAction)
qtyAlert.view.tintColor = MaterialDesignColor.green500
dispatch_async(dispatch_get_main_queue()) {
self.presentViewController(qtyAlert, animated: true, completion: nil)
qtyAlert.view.tintColor = MaterialDesignColor.green500
}
})
alert.addAction(action)
}
}
}
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) -> Void in
}))
alert.view.tintColor = MaterialDesignColor.green500
presentViewController(alert, animated: true, completion: nil)
alert.view.tintColor = MaterialDesignColor.green500
}
//MARK: - Helpers
func filterContentForSearch (searchString: String) {
filtredNutritionsArray = nutritionsArray.filter({ (nutrient) -> Bool in
let nutrientMatch = nutrient.name!.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)
return nutrientMatch != nil ? true : false
})
}
func qtyTextChanged(sender:AnyObject) {
let tf = sender as! UITextField
var resp : UIResponder = tf
while !(resp is UIAlertController) { resp = resp.nextResponder()! }
let alert = resp as! UIAlertController
(alert.actions[1] as UIAlertAction).enabled = (tf.text != "")
}
func saveContext() {
dispatch_async(dispatch_get_main_queue()) {
CoreDataStackManager.sharedInstance().saveContext()
}
}
}
| apache-2.0 | 7e73a461d3469b527e14444d19a7faae | 30.441296 | 173 | 0.694952 | 4.432648 | false | false | false | false |
e78l/swift-corelibs-foundation | Foundation/MeasurementFormatter.swift | 1 | 3545 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@available(*, unavailable, message: "Not supported in swift-corelibs-foundation")
open class MeasurementFormatter : Formatter, NSSecureCoding {
public struct UnitOptions : OptionSet {
public private(set) var rawValue: UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let providedUnit = UnitOptions(rawValue: 1 << 0)
public static let naturalScale = UnitOptions(rawValue: 1 << 1)
public static let temperatureWithoutUnit = UnitOptions(rawValue: 1 << 2)
}
/*
This property can be set to ensure that the formatter behaves in a way the developer expects, even if it is not standard according to the preferences of the user's locale. If not specified, unitOptions defaults to localizing according to the preferences of the locale.
Ex:
By default, if unitOptions is set to the empty set, the formatter will do the following:
- kilocalories may be formatted as "C" instead of "kcal" depending on the locale.
- kilometersPerHour may be formatted as "miles per hour" for US and UK locales but "kilometers per hour" for other locales.
However, if MeasurementFormatter.UnitOptions.providedUnit is set, the formatter will do the following:
- kilocalories would be formatted as "kcal" in the language of the locale, even if the locale prefers "C".
- kilometersPerHour would be formatted as "kilometers per hour" for US and UK locales even though the preference is for "miles per hour."
Note that MeasurementFormatter will handle converting measurement objects to the preferred units in a particular locale. For instance, if provided a measurement object in kilometers and the set locale is en_US, the formatter will implicitly convert the measurement object to miles and return the formatted string as the equivalent measurement in miles.
*/
open var unitOptions: UnitOptions = []
/*
If not specified, unitStyle is set to NSFormattingUnitStyleMedium.
*/
open var unitStyle: Formatter.UnitStyle
/*
If not specified, locale is set to the user's current locale.
*/
/*@NSCopying*/ open var locale: Locale!
/*
If not specified, the number formatter is set up with NumberFormatter.Decimal.style.
*/
open var numberFormatter: NumberFormatter!
open func string(from measurement: Measurement<Unit>) -> String { NSUnsupported() }
/*
@param An NSUnit
@return A formatted string representing the localized form of the unit without a value attached to it. This method will return [unit symbol] if the provided unit cannot be localized.
*/
open func string(from unit: Unit) -> String { NSUnsupported() }
public override init() { NSUnimplemented() }
public required init?(coder aDecoder: NSCoder) { NSUnsupported() }
open override func encode(with aCoder: NSCoder) { NSUnsupported() }
public static var supportsSecureCoding: Bool { return true }
public func string<UnitType>(from measurement: Measurement<UnitType>) -> String { NSUnsupported() }
}
| apache-2.0 | 3789a3d58d0418af8ddc9f8030c00f65 | 45.038961 | 358 | 0.70409 | 4.958042 | false | false | false | false |
hammond756/Shifty | Shifty/Shifty/ActionSheet.swift | 1 | 16391 | //
// ActionSheet.swift
// Shifty
//
// Created by Aron Hammond on 17/06/15.
// Copyright (c) 2015 Aron Hammond. All rights reserved.
//
// Creates a UIAlertController whose actions can easily be set
import Foundation
import UIKit
import Parse
// definiton of protocol that all viewcontrollers incorporating an actionsheet or alertview conform to
@objc protocol ActionSheetDelegate
{
func getData()
func setActivityViewActive(on: Bool)
optional func popViewController()
optional func showAlert(alertView: UIAlertController)
optional func showAlertMessage(message: String)
}
// handles the creation of UIAlertControllers throughout the application
class ActionSheet
{
// information to know what to manipulate
var selectedShift: Shift
var associatedRequest: String?
var actionList = [UIAlertAction]()
var delegate: ActionSheetDelegate
let helper = Helper()
init(shift: Shift, delegate: ActionSheetDelegate, request: String?)
{
self.selectedShift = shift
self.delegate = delegate
self.associatedRequest = request
}
// add a action the the action sheet that supplies a shift to the marketplace and save the changes in the database
func createSupplyAction()
{
let supplyAction = UIAlertAction(title: Label.supply, style: .Default) { action -> Void in
self.selectedShift.status = Status.supplied
// ask for parse object with the objectID of the selectedShift
let query = PFQuery(className: ParseClass.shifts)
query.getObjectInBackgroundWithId(self.selectedShift.objectID) { (shift: PFObject?, error: NSError?) -> Void in
if let shift = self.helper.returnObjectAfterErrorCheck(shift, error: error) as? PFObject
{
shift[ParseKey.status] = Status.supplied
shift.saveInBackgroundWithBlock() { (succes: Bool, error: NSError?) -> Void in
if succes
{
self.delegate.getData()
}
}
}
}
}
actionList.append(supplyAction)
}
// add a action the the action sheet that approves a deal and save changes in the database
func createApproveAction()
{
let approveAction = UIAlertAction(title: "Goedkeuren", style: .Default) { action -> Void in
self.approveShiftChange()
}
actionList.append(approveAction)
}
// appriving a suggestion needs extra behaviour on top of approveShiftChange, namely removing the request
func createApproveSuggestionAction()
{
let approveSuggestionAction = UIAlertAction(title: Label.approve, style: .Default) { action -> Void in
self.approveShiftChange()
self.deleteAssociatedRequest()
// find all shifts that were suggested to the resolved request
let query = PFQuery(className: ParseClass.shifts)
query.whereKey(ParseKey.suggestedTo, equalTo: self.selectedShift.suggestedTo!)
query.findObjectsInBackgroundWithBlock() { (objects: [AnyObject]?, error: NSError?) -> Void in
if let associatedShifts = self.helper.returnObjectAfterErrorCheck(objects, error: error) as? [PFObject]
{
for (i,shift) in associatedShifts.enumerate()
{
shift.removeObjectForKey(ParseKey.suggestedTo)
shift[ParseKey.status] = Status.idle
shift.saveInBackgroundWithBlock() { (succes: Bool, error: NSError?) -> Void in
// start reloading data at last item
if succes && i == associatedShifts.count - 1
{
self.delegate.getData()
self.delegate.popViewController!()
}
}
}
}
}
}
actionList.append(approveSuggestionAction)
}
func deleteAssociatedRequest()
{
self.selectedShift.suggestedTo!.fetchIfNeededInBackgroundWithBlock() { (object: PFObject?, error: NSError?) -> Void in
if let request = self.helper.returnObjectAfterErrorCheck(object, error: error) as? PFObject
{
request.deleteInBackground()
}
}
}
func createDisapproveAction()
{
let disapproveAction = UIAlertAction(title: Label.disapprove, style: .Default) { action -> Void in
// set status back to Status.idle and remove acceptedBy
self.helper.updateShiftStatuses([self.selectedShift.objectID], newStatus: Status.supplied, suggestedTo: nil) { () -> Void in
self.delegate.getData()
}
}
actionList.append(disapproveAction)
}
func createDisapproveSuggestionAction()
{
let disapproveSuggestionAction = UIAlertAction(title: Label.disapprove, style: .Default) { action -> Void in
// ask for shift object with specific ID
let query = PFQuery(className: ParseClass.shifts)
query.getObjectInBackgroundWithId(self.selectedShift.objectID) { (shift: PFObject?, error: NSError?) -> Void in
if let shift = self.helper.returnObjectAfterErrorCheck(shift, error: error) as? PFObject
{
shift.removeObjectForKey(ParseKey.suggestedTo)
shift.removeObjectForKey(ParseKey.acceptedBy)
shift[ParseKey.status] = Status.idle
shift.saveInBackgroundWithBlock() { (succes: Bool, error: NSError?) -> Void in
if succes
{
self.delegate.getData()
}
}
}
}
}
actionList.append(disapproveSuggestionAction)
}
// accept a shift suggested to the user's request
func createAcceptSuggestionAction()
{
let acceptSuggestionAction = UIAlertAction(title: Label.accept, style: .Default) { action -> Void in
// ask for shift object with specific ID
let query = PFQuery(className: ParseClass.shifts)
query.getObjectInBackgroundWithId(self.selectedShift.objectID) { (shift: PFObject?, error: NSError? ) -> Void in
if let shift = self.helper.returnObjectAfterErrorCheck(shift, error: error) as? PFObject
{
// check whether the shift is already accepted by another user
if shift[ParseKey.acceptedBy] == nil
{
shift[ParseKey.acceptedBy] = PFUser.currentUser()
shift[ParseKey.status] = Status.awaittingFromSug
shift.saveInBackgroundWithBlock() { (succes, error) -> Void in
if succes
{
self.delegate.getData()
}
}
}
}
}
}
actionList.append(acceptSuggestionAction)
}
// update properties in application and in the database
func approveShiftChange()
{
// ask for shift with specific objectID
let query = PFQuery(className: ParseClass.shifts)
query.getObjectInBackgroundWithId(self.selectedShift.objectID) { (shift: PFObject?, error: NSError?) -> Void in
if let shift = self.helper.returnObjectAfterErrorCheck(shift, error: error) as? PFObject
{
// set properties
shift[ParseKey.status] = Status.idle
shift[ParseKey.owner] = shift[ParseKey.acceptedBy]
shift.removeObjectForKey(ParseKey.acceptedBy)
shift.removeObjectForKey(ParseKey.suggestedTo)
shift.saveInBackgroundWithBlock() { (succes: Bool, error: NSError?) -> Void in
if succes
{
self.delegate.getData()
}
}
}
}
}
// add a action the the action sheet that revokes a shift from the marketplace and save change in the database
func createRevokeAction()
{
let revokeAction = UIAlertAction(title: Label.revoke, style: .Default) { action -> Void in
// ask for shift met specific ID
let query = PFQuery(className: ParseClass.shifts)
query.getObjectInBackgroundWithId(self.selectedShift.objectID) { (shift: PFObject?, error: NSError?) -> Void in
if let shift = self.helper.returnObjectAfterErrorCheck(shift, error: error) as? PFObject
{
// set back to "idle"
shift[ParseKey.status] = Status.idle
shift.saveInBackgroundWithBlock() { (succes: Bool, error: NSError?) -> Void in
if succes
{
self.delegate.getData()
}
}
}
}
}
actionList.append(revokeAction)
}
// add a action the the action sheet that accepts a supplied shift and save change in the database
func createAcceptAction()
{
let acceptAction = UIAlertAction(title: Label.accept, style: .Default) { action -> Void in
//
let query = PFQuery(className: ParseClass.shifts)
query.getObjectInBackgroundWithId(self.selectedShift.objectID) { (shift: PFObject?, error: NSError? ) -> Void in
if let shift = self.helper.returnObjectAfterErrorCheck(shift, error: error) as? PFObject
{
// check whether the shift conflicts with an owned one
self.helper.checkIfDateIsTaken(self.selectedShift.date) { taken -> Void in
if taken
{
self.delegate.showAlertMessage?("Je werkt al op deze dag")
return
}
else if (shift[ParseKey.acceptedBy] == nil) && (shift[ParseKey.owner] as? PFUser != PFUser.currentUser())
{
shift[ParseKey.acceptedBy] = PFUser.currentUser()
shift[ParseKey.status] = Status.awaiting
shift.saveInBackgroundWithBlock() { (succes, error) -> Void in
if succes
{
self.delegate.getData()
}
}
}
// shift was already accepted, but data wasn't updated yet
else if shift[ParseKey.acceptedBy] != nil
{
self.delegate.showAlert?(self.getAlertViewForMissedOppurtunity())
}
}
}
}
}
actionList.append(acceptAction)
}
// destructive button on the actionsheet
func createDeleteAction()
{
let deleteAction = UIAlertAction(title: Label.delete, style: .Destructive) { action -> Void in
self.delegate.showAlert?(self.getConfirmationAlertView())
}
actionList.append(deleteAction)
}
// create ActionSheet that holds all possible actions for a selected cell
func getAlertController() -> UIAlertController
{
let actionSheetController = UIAlertController()
for action in actionList
{
actionSheetController.addAction(action)
}
let cancelAction = UIAlertAction(title: Label.cancel, style: .Cancel) { action -> Void in
actionSheetController.dismissViewControllerAnimated(true, completion: nil)
}
actionSheetController.addAction(cancelAction)
return actionSheetController
}
// create an AlertView that shows in the special case that a displayed shift is already accepted by another user
func getAlertViewForMissedOppurtunity() -> UIAlertController
{
let alertView = UIAlertController(title: nil, message: "Helaas, deze dienst is net voor je weggekaapt.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: Label.cancel, style: .Cancel) { action -> Void in
alertView.dismissViewControllerAnimated(true, completion: nil)
self.delegate.getData()
}
alertView.addAction(cancelAction)
return alertView
}
// shows UIAlertView warning user that he/she is about to delete something
func getConfirmationAlertView() -> UIAlertController
{
let alertView = UIAlertController(title: nil, message: "Je staat op het punt je diensten te verwijderen.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: Label.cancel, style: .Cancel) { action -> Void in
alertView.dismissViewControllerAnimated(true, completion: nil)
}
// prefroms the actual deletion.
let confirmAction = UIAlertAction(title: Label.delete, style: .Destructive) { action -> Void in
self.delegate.setActivityViewActive(true)
// ask for shifts that are created from the same fixed shift, owned by the user and not pending
let shiftQuery = PFQuery(className: ParseClass.shifts)
.whereKey(ParseKey.createdFrom, equalTo: self.selectedShift.createdFrom)
.whereKey(ParseKey.owner, equalTo: PFUser.currentUser()!)
shiftQuery.findObjectsInBackgroundWithBlock() { (objects: [AnyObject]?, error: NSError?) -> Void in
if let objects = self.helper.returnObjectAfterErrorCheck(objects, error: error) as? [PFObject]
{
for (i,object) in objects.enumerate()
{
// refresh after deleting the last object
if i == objects.count - 1
{
object.deleteInBackgroundWithBlock() { (succes: Bool, error: NSError?) -> Void in
if succes
{
self.delegate.getData()
}
}
return
}
object.deleteInBackground()
}
}
}
// delete entry in FixedShifts
PFQuery(className: ParseClass.fixed).getObjectInBackgroundWithId(self.selectedShift.createdFrom.objectId!) { (fixedShift: PFObject?, error: NSError?) -> Void in
fixedShift?.deleteInBackground()
}
}
alertView.addAction(confirmAction)
alertView.addAction(cancelAction)
return alertView
}
// function to easily include one or more actions in the actionsheet
func includeActions(actions: [String])
{
for action in actions
{
switch action
{
case Action.supply: createSupplyAction()
case Action.revoke: createRevokeAction()
case Action.approve: createApproveAction()
case Action.accept: createAcceptAction()
case Action.delete: createDeleteAction()
case Action.approveSug: createApproveSuggestionAction()
case Action.acceptSug: createAcceptSuggestionAction()
case Action.disapprove: createDisapproveAction()
case Action.disapproveSug: createDisapproveSuggestionAction()
default: break
}
}
}
} | mit | 1e490acdaf50a14afe01a7d5c5487ffe | 41.466321 | 172 | 0.555854 | 5.552507 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01300-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 1 | 708 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
let c = a
func e() {
}
func f<T>() -> T -> T {
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
}
class a<f : b, g : b where f.d == g> {
}
protocol b {
}
struct c<h : b> : b {
}
struct c<d : Sequence> {
}
func a<d>() -> [c<d>] {
| apache-2.0 | 85b4ef24cd1c0bcc974e9b3bc2c469c0 | 21.83871 | 79 | 0.621469 | 2.765625 | false | false | false | false |
abellono/IssueReporter | IssueReporter/Core/Image.swift | 1 | 1160 | //
// Image.swift
// IssueReporter
//
// Created by Hakon Hanesand on 10/6/16.
// Copyright © 2017 abello. All rights reserved.
//
//
import Foundation
internal class Image {
let image: UIImage
let identifier: String = UUID().uuidString
let compressionRatio: Double = 0.5
var localImageURL: URL? = nil
var cloudImageURL: URL? = nil
var state: State = .initial
var compressionCompletionBlock: (Image) -> () = { _ in }
init(image: UIImage) {
self.image = image.applyRotationToImageData()
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
guard let strongSelf = self else { return }
strongSelf.imageData = strongSelf.image.jpegData(compressionQuality: CGFloat(strongSelf.compressionRatio))
}
}
var imageData: Data? {
didSet {
DispatchQueue.main.async {
self.compressionCompletionBlock(self)
}
}
}
}
extension Image: Equatable {
public static func ==(lhs: Image, rhs: Image) -> Bool {
return lhs.identifier == rhs.identifier
}
}
| mit | 4cddae13dea3413000838425b1430ac7 | 23.145833 | 118 | 0.599655 | 4.457692 | false | false | false | false |
google/JacquardSDKiOS | Example/JacquardSDK/ScanningView/ScanningViewController.swift | 1 | 14524 | // Copyright 2021 Google LLC
//
// 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 Combine
import CoreBluetooth
import JacquardSDK
import MaterialComponents
import UIKit
struct AdvertisingTagCellModel: Hashable {
let tag: ConnectableTag
static func == (lhs: AdvertisingTagCellModel, rhs: AdvertisingTagCellModel) -> Bool {
return lhs.tag.identifier == rhs.tag.identifier
}
func hash(into hasher: inout Hasher) {
tag.identifier.hash(into: &hasher)
}
}
private enum TagSection: Int {
case advertisingTags = 0
case connectedTags
var title: String {
switch self {
case .connectedTags: return "PREVIOUSLY CONNECTED TAGS"
case .advertisingTags: return "NEARBY TAGS"
}
}
}
/// This viewcontroller showcases the usage of the Tag scanning api.
class ScanningViewController: UIViewController {
private enum Constants {
static let matchSerialNumberDescription =
"Match the last 4 digits with the serial number on the back of your Tag."
static let chargeTagDescription =
"""
Charge your Tag until the LED is pulsing white. Then, press and hold the power button on
your Tag for 3 seconds to pair.
"""
static let noTagsFound = "No tags found"
static let stopScanHeight: CGFloat = 50.0
static let pairingTimeInterval: TimeInterval = 30.0
static let pairingTimeOutMessage = "Tag pairing timed out."
}
private enum ButtonState: String {
case scan = "Scan"
case scanning = "Scanning..."
case pair = "Pair"
case pairing = "Pairing..."
case paired = "Paired"
case tryAgain = "Try Again"
}
@IBOutlet private weak var tagsTableView: UITableView!
@IBOutlet private weak var scanButton: GreyRoundCornerButton!
@IBOutlet private weak var searchingLabel: UILabel!
@IBOutlet private weak var scanDescriptionLabel: UILabel!
@IBOutlet private weak var downArrowStackView: UIStackView!
@IBOutlet private weak var stopScanButtonHeight: NSLayoutConstraint!
// To trigger failure if device pairing does not succeed in 60 seconds.
private var pairingTimer: Timer?
private var pairingDuration = 60.0
var shouldShowCloseButton = false
private var buttonState = ButtonState.scan {
didSet {
self.scanButton.setTitle(buttonState.rawValue, for: .normal)
}
}
private let loadingView = LoadingViewController.instance
/// Array will hold tags which are already paired and available in iOS Bluetooth settings screen.
private var preConnectedTags = [PreConnectedTag]()
/// Array will hold the new advertsing tags.
private var advertisedTags = [AdvertisedTag]()
private var cancellables = [Cancellable]()
private var scanDiffableDataSource:
UITableViewDiffableDataSource<TagSection, AdvertisingTagCellModel>?
private var selectedIndexPath: IndexPath?
override func viewDidLoad() {
super.viewDidLoad()
if shouldShowCloseButton {
navigationItem.leftBarButtonItem = UIBarButtonItem(
image: UIImage(named: "close"),
style: .done,
target: self,
action: #selector(closeButtonTapped))
}
title = "Scan and Pair Tag"
scanButton.setTitleFont(UIFont.system20Normal, for: .normal)
scanDescriptionLabel.text = Constants.chargeTagDescription
// Sets up the Tableview before we start receving advertising tags from the publisher.
configureTagsTableView()
// Subscribe to the advertisingTags publisher.
// A tag will be published evertyime an advertising Jacquard Tag is found.
sharedJacquardManager.advertisingTags
.throttleAdvertisedTags()
.sink { [weak self] tag in
print("found tag: \(tag.pairingSerialNumber) && \(tag.rssi)\n")
guard let self = self else { return }
self.updateScanViewUI()
if let index = self.advertisedTags.firstIndex(where: { $0.identifier == tag.identifier }) {
self.advertisedTags[index] = tag
} else {
self.advertisedTags.append(tag)
}
self.updateDataSource()
self.tagsTableView.reloadData()
}.addTo(&cancellables)
}
@objc private func closeButtonTapped() {
dismiss(animated: true, completion: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Stop scanning when not required.
stopScanning()
}
@IBAction func stopScanButtonTapped(_ sender: UIButton) {
stopScanning()
buttonState = .scan
stopScanButtonHeight.constant = 0
if selectedIndexPath != nil {
selectedIndexPath = nil
tagsTableView.reloadData()
}
}
@IBAction func scanButtonTapped(_ sender: UIButton) {
if buttonState == ButtonState.pair {
startPairing()
return
}
// Remove all existing tags in list before scanning.
resetTagsList()
// After initiating scan, the advertisingTags subscription is called everytime a tag is found.
// `startScanning()` only scans for advertising tags, it does not return Tags already connected.
// see also `preConnectedTags()`
do {
let options: [String: Any] = [CBCentralManagerScanOptionAllowDuplicatesKey: true]
try sharedJacquardManager.startScanning(options: options)
scanDescriptionLabel.text = Constants.chargeTagDescription
buttonState = .scanning
searchingLabel.text = ButtonState.scanning.rawValue
searchingLabel.isHidden = false
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(30)) {
if self.advertisedTags.isEmpty {
self.buttonState = .tryAgain
self.stopScanButtonHeight.constant = Constants.stopScanHeight
}
self.searchingLabel.text = Constants.noTagsFound
}
} catch {
// startScanning will throw an error, if Bluetooth is unavailable.
buttonState = .scan
searchingLabel.isHidden = true
let message = MDCSnackbarMessage()
message.text = "Error when scanning for tags, check if bluetooth is available"
let action = MDCSnackbarMessageAction()
let actionHandler = { () in
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
action.handler = actionHandler
action.title = "ACTION"
message.action = action
MDCSnackbarManager.default.show(message)
print(error)
}
// Returns an array of `PreConnectedTag` objects.
// Call `JacquardManager.preConnectedTags()` to retrive Tags already connected to the phone.
preConnectedTags = sharedJacquardManager.preConnectedTags().sorted(
by: { $0.displayName > $1.displayName })
if !preConnectedTags.isEmpty {
buttonState = .scanning
updateScanViewUI()
self.updateDataSource()
}
}
func resetTagsList() {
// Remove all existing tags in list before scanning.
advertisedTags.removeAll()
preConnectedTags.removeAll()
updateDataSource()
}
private func updateScanViewUI() {
scanDescriptionLabel.text = Constants.matchSerialNumberDescription
downArrowStackView.isHidden = true
stopScanButtonHeight.constant = Constants.stopScanHeight
}
private func startPairing() {
guard let selectedIndexPath = selectedIndexPath else {
return
}
buttonState = .pairing
loadingView.modalPresentationStyle = .overCurrentContext
present(loadingView, animated: true) {
self.loadingView.startLoading(withMessage: "Pairing")
}
stopScanning()
invalidatePairingTimer()
guard let cellModel = scanDiffableDataSource?.itemIdentifier(for: selectedIndexPath) else {
return
}
let connectionStream = sharedJacquardManager.connect(cellModel.tag)
handleConnectStateChanges(connectionStream)
pairingTimer = Timer.scheduledTimer(
withTimeInterval: pairingDuration,
repeats: false
) { [weak self] _ in
guard let self = self else { return }
self.invalidatePairingTimer()
self.loadingView.stopLoading()
MDCSnackbarManager.default.show(
MDCSnackbarMessage(text: "Getting issue to tag pairing, Please retry.")
)
}
}
func stopScanning() {
sharedJacquardManager.stopScanning()
}
private func invalidatePairingTimer() {
pairingTimer?.invalidate()
pairingTimer = nil
}
func handleConnectStateChanges(_ connectionStream: AnyPublisher<TagConnectionState, Error>) {
connectionStream
.sink { [weak self] error in
// Connection attempts never time out,
// so an error will be received only when the connection cannot be recovered or retried.
self?.loadingView.stopLoading(message: "Connection Error")
self?.invalidatePairingTimer()
MDCSnackbarManager.default.show(MDCSnackbarMessage(text: "\(error)"))
} receiveValue: { [weak self] connectionState in
switch connectionState {
case .preparingToConnect:
self?.loadingView.indicatorProgress(0.0)
case .connecting(let current, let total),
.initializing(let current, let total),
.configuring(let current, let total):
self?.loadingView.indicatorProgress(Float(current / total))
case .connected(let connectedTag):
// Tag is successfully paired, you can now subscribe and retrieve the tag stream.
print("connected to tag: \(connectedTag)")
self?.invalidatePairingTimer()
self?.buttonState = .paired
self?.loadingView.stopLoading(withMessage: "Paired") {
self?.connectionSuccessful(for: connectedTag)
}
case .disconnected(let error):
print("Disconnected with error: \(String(describing: error))")
self?.buttonState = .pair
self?.loadingView.stopLoading()
self?.invalidatePairingTimer()
MDCSnackbarManager.default.show(MDCSnackbarMessage(text: "Disconnected"))
@unknown default:
fatalError("Unknown connection state.")
}
}
.addTo(&cancellables)
}
func connectionSuccessful(for tag: ConnectedTag) {
Preferences.addKnownTag(
KnownTag(identifier: tag.identifier, name: tag.name)
)
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let navigationController = UINavigationController(rootViewController: DashboardViewController())
appDelegate?.window?.rootViewController = navigationController
}
}
// Extension contains only UI Logic not related to Jacquard SDK API's
extension ScanningViewController {
var sortedAdvertisedTags: [AdvertisedTag] {
return
advertisedTags
.sorted(by: { $0.displayName < $1.displayName })
}
func updateDataSource() {
tagsTableView.isHidden = advertisedTags.isEmpty && preConnectedTags.isEmpty
let advertisedModels =
sortedAdvertisedTags
.map { AdvertisingTagCellModel(tag: $0) }
let preConnectedModels =
preConnectedTags
.map { AdvertisingTagCellModel(tag: $0) }
var snapshot = NSDiffableDataSourceSnapshot<TagSection, AdvertisingTagCellModel>()
snapshot.appendSections([.advertisingTags])
snapshot.appendItems(advertisedModels, toSection: .advertisingTags)
snapshot.appendSections([.connectedTags])
snapshot.appendItems(preConnectedModels, toSection: .connectedTags)
self.scanDiffableDataSource?.apply(snapshot)
}
func configureTagsTableView() {
let nib = UINib(nibName: "ScanningTableViewCell", bundle: nil)
tagsTableView.register(nib, forCellReuseIdentifier: ScanningTableViewCell.reuseIdentifier)
tagsTableView.dataSource = scanDiffableDataSource
tagsTableView.delegate = self
scanDiffableDataSource = UITableViewDiffableDataSource<TagSection, AdvertisingTagCellModel>(
tableView: tagsTableView,
cellProvider: { (tagsTableView, indexPath, advTagCellModel) -> UITableViewCell? in
guard
let cell = tagsTableView.dequeueReusableCell(
withIdentifier: ScanningTableViewCell.reuseIdentifier,
for: indexPath
) as? ScanningTableViewCell
else {
assertionFailure("TagCell could not be created")
return nil
}
cell.configure(with: advTagCellModel, isSelected: self.selectedIndexPath == indexPath)
return cell
})
}
}
/// Handle Tableview delegate methods
extension ScanningViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45.0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(
frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 40))
let label = UILabel(frame: headerView.bounds)
label.text = TagSection(rawValue: section)?.title
label.font = UIFont.system12Medium
label.textColor = UIColor(red: 0.392, green: 0.392, blue: 0.392, alpha: 1)
headerView.addSubview(label)
return headerView
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
selectedIndexPath = indexPath
tableView.reloadData()
buttonState = .pair
scanButton.isHidden = false
}
}
extension AnyPublisher where Output == AdvertisedTag {
func throttleAdvertisedTags() -> AnyPublisher<AdvertisedTag, Failure> {
var deliveryInterval = -1
let publishers = filter { _ in
// Reset interval count.
if deliveryInterval >= Int.max || deliveryInterval < 0 {
deliveryInterval = -1
}
deliveryInterval += 1
// If CBCentralManagerScanOptionAllowDuplicatesKey is true, in this case peripheral
// advertising interval is very fast ~100ms to show on UI. Since there is no api with
// central manager which control advertising interval, we need to filter out results to show
// in table properly.
return deliveryInterval % 60 == 0
}
return publishers.eraseToAnyPublisher()
}
}
| apache-2.0 | 37ddb536a6a12f5e7bf565a043cb0d86 | 33.498812 | 100 | 0.704489 | 4.880376 | false | false | false | false |
romaonthego/TableViewDataManager | Source/Classes/Components/DateTime/TableViewDatePickerCell.swift | 1 | 2952 | //
// TableViewDatePickerCell.swift
// TableViewDataManager
//
// Copyright (c) 2016 Roman Efimov (https://github.com/romaonthego)
//
// 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 class TableViewDatePickerCell: TableViewFormCell {
// MARK: Public variables
//
public override var item: TableViewItem! { get { return datePickerItem } set { datePickerItem = newValue as! TableViewDatePickerItem } }
// MARK: Private variables
//
private var datePickerItem: TableViewDatePickerItem!
// MARK: Interface builder outlets
//
@IBOutlet public private(set) var datePicker: UIDatePicker!
// MARK: View Lifecycle
//
public override func cellWillAppear() {
super.cellWillAppear()
guard let dateTimeItem = self.datePickerItem.dateTimeItem, let value = dateTimeItem.value else {
return
}
self.datePicker.date = value
self.datePicker.datePickerMode = dateTimeItem.datePickerMode
self.datePicker.locale = dateTimeItem.locale
self.datePicker.calendar = dateTimeItem.calendar
self.datePicker.timeZone = dateTimeItem.timeZone
self.datePicker.minimumDate = dateTimeItem.minimumDate
self.datePicker.maximumDate = dateTimeItem.maximumDate
self.datePicker.minuteInterval = dateTimeItem.minuteInterval
}
// MARK: Actions
@IBAction func datePickerValueChanged(sender: UIDatePicker!) {
if let dateTimeItem = self.datePickerItem.dateTimeItem {
dateTimeItem.value = sender.date
}
guard let changeHandler = self.datePickerItem.changeHandler, let tableView = self.tableViewDataManager.tableView, let indexPath = self.indexPath else {
return
}
changeHandler(section: self.section, item: self.datePickerItem, tableView: tableView, indexPath: indexPath)
}
}
| mit | 1320f15ec3c2e21e7f4e46913e329797 | 40 | 159 | 0.716463 | 4.92 | false | false | false | false |
gresrun/Darts301 | App/Darts301/Darts301/VictoryViewController.swift | 1 | 4047 | //
// VictoryViewController.swift
// Darts301
//
// Created by Greg Haines on 3/3/17.
// Copyright © 2017 Aly & Friends. All rights reserved.
//
import GoogleMobileAds
import Firebase
import UIImage_animatedGif
import UIKit
class VictoryViewController : UIViewController, GADInterstitialDelegate {
@IBOutlet weak var celebrateImageView: UIImageView!
@IBOutlet weak var victoryMessageLabel: UILabel!
@IBOutlet weak var playAgainButton: UIButton!
var winner: Player!
var pointSpread: Int!
private var interstitial: GADInterstitial?
override func viewDidLoad() {
super.viewDidLoad()
let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("Images.bundle")
let contents = try! fileManager.contentsOfDirectory(at: assetURL, includingPropertiesForKeys: [
URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles)
let randomIndex = Int(arc4random_uniform(UInt32(contents.count)))
let imageUrl = contents[randomIndex]
if let gif = UIImage.animatedImage(withAnimatedGIFURL: imageUrl) {
self.celebrateImageView.image = gif
NSLayoutConstraint(item: self.celebrateImageView!,
attribute: .width,
relatedBy: .equal,
toItem: self.celebrateImageView,
attribute: .height,
multiplier: gif.size.width / gif.size.height,
constant: 0.0).isActive = true
}
if !IAPProducts.store.isProductPurchased(IAPProducts.noAds) {
// Pre-load the post-victory interstitial ad.
interstitial = GADInterstitial(adUnitID: Ads.postVictoryAdUnitId)
interstitial!.delegate = self
let adRequest = GADRequest()
adRequest.testDevices = [kGADSimulatorID]
interstitial!.load(adRequest)
}
// Log that a game was finished.
Analytics.logEvent(AnalyticsEventPostScore, parameters: [
AnalyticsParameterLevel: "1" as NSObject,
AnalyticsParameterCharacter: "\(winner.playerNum)" as NSObject,
AnalyticsParameterScore: "\(pointSpread ?? 0)" as NSObject
])
// Finish setting up the UI.
Utils.addShadow(to: celebrateImageView)
playAgainButton.layer.cornerRadius = 8.0
Utils.addShadow(to: playAgainButton)
view.backgroundColor = (winner.playerNum == 1) ? Colors.player1Color : Colors.player2Color
if pointSpread < 10 {
victoryMessageLabel.text = String(format: NSLocalizedString("VICTORY_CLOSE", value: "That was a close one!\nBut %@ wins. Nice work!", comment: "Label indicating which player won and that the margin of victory was small."), winner.name)
} else if pointSpread < 75 {
victoryMessageLabel.text = String(format: NSLocalizedString("VICTORY_STANDARD", value: "Good game,\n%@ wins!", comment: "Label indicating which player won and that the margin of victory was nominal."), winner.name)
} else {
victoryMessageLabel.text = String(format: NSLocalizedString("VICTORY_HUGE", value: "%@ crushed it!\nGood win.", comment: "Label indicating which player won and that the margin of victory was large."), winner.name)
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBAction func playAgainPressed() {
if let interstitial = interstitial, interstitial.isReady {
interstitial.present(fromRootViewController: self)
} else {
returnToWelcomeVC()
}
}
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
returnToWelcomeVC()
}
private func returnToWelcomeVC() {
// Perform segue to welcome VC.
self.performSegue(withIdentifier: Segues.playAgain, sender: self)
}
}
| apache-2.0 | 00fae40a0373d17cac9309728a2ce200 | 42.978261 | 247 | 0.654226 | 4.934146 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | Foundation/NSHTTPCookie.swift | 1 | 23490 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
public struct HTTPCookiePropertyKey : RawRepresentable, Equatable, Hashable, Comparable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue.hashValue
}
public static func ==(_ lhs: HTTPCookiePropertyKey, _ rhs: HTTPCookiePropertyKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func <(_ lhs: HTTPCookiePropertyKey, _ rhs: HTTPCookiePropertyKey) -> Bool {
return rhs.rawValue == rhs.rawValue
}
}
extension HTTPCookiePropertyKey {
/// Key for cookie name
public static let name = HTTPCookiePropertyKey(rawValue: "Name")
/// Key for cookie value
public static let value = HTTPCookiePropertyKey(rawValue: "Value")
/// Key for cookie origin URL
public static let originURL = HTTPCookiePropertyKey(rawValue: "OriginURL")
/// Key for cookie version
public static let version = HTTPCookiePropertyKey(rawValue: "Version")
/// Key for cookie domain
public static let domain = HTTPCookiePropertyKey(rawValue: "Domain")
/// Key for cookie path
public static let path = HTTPCookiePropertyKey(rawValue: "Path")
/// Key for cookie secure flag
public static let secure = HTTPCookiePropertyKey(rawValue: "Secure")
/// Key for cookie expiration date
public static let expires = HTTPCookiePropertyKey(rawValue: "Expires")
/// Key for cookie comment text
public static let comment = HTTPCookiePropertyKey(rawValue: "Comment")
/// Key for cookie comment URL
public static let commentURL = HTTPCookiePropertyKey(rawValue: "CommentURL")
/// Key for cookie discard (session-only) flag
public static let discard = HTTPCookiePropertyKey(rawValue: "Discard")
/// Key for cookie maximum age (an alternate way of specifying the expiration)
public static let maximumAge = HTTPCookiePropertyKey(rawValue: "Max-Age")
/// Key for cookie ports
public static let port = HTTPCookiePropertyKey(rawValue: "Port")
// For Cocoa compatibility
internal static let created = HTTPCookiePropertyKey(rawValue: "Created")
}
/// `NSHTTPCookie` represents an http cookie.
///
/// An `NSHTTPCookie` instance represents a single http cookie. It is
/// an immutable object initialized from a dictionary that contains
/// the various cookie attributes. It has accessors to get the various
/// attributes of a cookie.
open class HTTPCookie : NSObject {
let _comment: String?
let _commentURL: URL?
let _domain: String
let _expiresDate: Date?
let _HTTPOnly: Bool
let _secure: Bool
let _sessionOnly: Bool
let _name: String
let _path: String
let _portList: [NSNumber]?
let _value: String
let _version: Int
var _properties: [HTTPCookiePropertyKey : Any]
static let _attributes: [HTTPCookiePropertyKey]
= [.name, .value, .originURL, .version, .domain,
.path, .secure, .expires, .comment, .commentURL,
.discard, .maximumAge, .port]
/// Initialize a NSHTTPCookie object with a dictionary of parameters
///
/// - Parameter properties: The dictionary of properties to be used to
/// initialize this cookie.
///
/// Supported dictionary keys and value types for the
/// given dictionary are as follows.
///
/// All properties can handle an NSString value, but some can also
/// handle other types.
///
/// <table border=1 cellspacing=2 cellpadding=4>
/// <tr>
/// <th>Property key constant</th>
/// <th>Type of value</th>
/// <th>Required</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.comment</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>Comment for the cookie. Only valid for version 1 cookies and
/// later. Default is nil.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.commentURL</td>
/// <td>NSURL or NSString</td>
/// <td>NO</td>
/// <td>Comment URL for the cookie. Only valid for version 1 cookies
/// and later. Default is nil.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.domain</td>
/// <td>NSString</td>
/// <td>Special, a value for either .originURL or
/// HTTPCookiePropertyKey.domain must be specified.</td>
/// <td>Domain for the cookie. Inferred from the value for
/// HTTPCookiePropertyKey.originURL if not provided.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.discard</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>A string stating whether the cookie should be discarded at
/// the end of the session. String value must be either "TRUE" or
/// "FALSE". Default is "FALSE", unless this is cookie is version
/// 1 or greater and a value for HTTPCookiePropertyKey.maximumAge is not
/// specified, in which case it is assumed "TRUE".</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.expires</td>
/// <td>NSDate or NSString</td>
/// <td>NO</td>
/// <td>Expiration date for the cookie. Used only for version 0
/// cookies. Ignored for version 1 or greater.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.maximumAge</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>A string containing an integer value stating how long in
/// seconds the cookie should be kept, at most. Only valid for
/// version 1 cookies and later. Default is "0".</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.name</td>
/// <td>NSString</td>
/// <td>YES</td>
/// <td>Name of the cookie</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.originURL</td>
/// <td>NSURL or NSString</td>
/// <td>Special, a value for either HTTPCookiePropertyKey.originURL or
/// HTTPCookiePropertyKey.domain must be specified.</td>
/// <td>URL that set this cookie. Used as default for other fields
/// as noted.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.path</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>Path for the cookie. Inferred from the value for
/// HTTPCookiePropertyKey.originURL if not provided. Default is "/".
/// </td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.port</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>comma-separated integer values specifying the ports for the
/// cookie. Only valid for version 1 cookies and later. Default is
/// empty string ("").</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.secure</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>A string stating whether the cookie should be transmitted
/// only over secure channels. String value must be either "TRUE"
/// or "FALSE". Default is "FALSE".</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.value</td>
/// <td>NSString</td>
/// <td>YES</td>
/// <td>Value of the cookie</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.version</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>Specifies the version of the cookie. Must be either "0" or
/// "1". Default is "0".</td>
/// </tr>
/// </table>
///
/// All other keys are ignored.
///
/// - Returns: An initialized `NSHTTPCookie`, or nil if the set of
/// dictionary keys is invalid, for example because a required key is
/// missing, or a recognized key maps to an illegal value.
///
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
public init?(properties: [HTTPCookiePropertyKey : Any]) {
guard
let path = properties[.path] as? String,
let name = properties[.name] as? String,
let value = properties[.value] as? String
else {
return nil
}
let canonicalDomain: String
if let domain = properties[.domain] as? String {
canonicalDomain = domain
} else if
let originURL = properties[.originURL] as? URL,
let host = originURL.host
{
canonicalDomain = host
} else {
return nil
}
_path = path
_name = name
_value = value
_domain = canonicalDomain
if let
secureString = properties[.secure] as? String, secureString.characters.count > 0
{
_secure = true
} else {
_secure = false
}
let version: Int
if let
versionString = properties[.version] as? String, versionString == "1"
{
version = 1
} else {
version = 0
}
_version = version
if let portString = properties[.port] as? String, _version == 1 {
_portList = portString.characters
.split(separator: ",")
.flatMap { Int(String($0)) }
.map { NSNumber(value: $0) }
} else {
_portList = nil
}
// TODO: factor into a utility function
if version == 0 {
let expiresProperty = properties[.expires]
if let date = expiresProperty as? Date {
_expiresDate = date
} else if let dateString = expiresProperty as? String {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss O" // per RFC 6265 '<rfc1123-date, defined in [RFC2616], Section 3.3.1>'
let timeZone = TimeZone(abbreviation: "GMT")
formatter.timeZone = timeZone
_expiresDate = formatter.date(from: dateString)
} else {
_expiresDate = nil
}
} else if
let maximumAge = properties[.maximumAge] as? String,
let secondsFromNow = Int(maximumAge), _version == 1 {
_expiresDate = Date(timeIntervalSinceNow: Double(secondsFromNow))
} else {
_expiresDate = nil
}
if let discardString = properties[.discard] as? String {
_sessionOnly = discardString == "TRUE"
} else {
_sessionOnly = properties[.maximumAge] == nil && version >= 1
}
if version == 0 {
_comment = nil
_commentURL = nil
} else {
_comment = properties[.comment] as? String
if let commentURL = properties[.commentURL] as? URL {
_commentURL = commentURL
} else if let commentURL = properties[.commentURL] as? String {
_commentURL = URL(string: commentURL)
} else {
_commentURL = nil
}
}
_HTTPOnly = false
_properties = [
.created : Date().timeIntervalSinceReferenceDate, // Cocoa Compatibility
.discard : _sessionOnly,
.domain : _domain,
.name : _name,
.path : _path,
.secure : _secure,
.value : _value,
.version : _version
]
if let comment = properties[.comment] {
_properties[.comment] = comment
}
if let commentURL = properties[.commentURL] {
_properties[.commentURL] = commentURL
}
if let expires = properties[.expires] {
_properties[.expires] = expires
}
if let maximumAge = properties[.maximumAge] {
_properties[.maximumAge] = maximumAge
}
if let originURL = properties[.originURL] {
_properties[.originURL] = originURL
}
if let _portList = _portList {
_properties[.port] = _portList
}
}
/// Return a dictionary of header fields that can be used to add the
/// specified cookies to the request.
///
/// - Parameter cookies: The cookies to turn into request headers.
/// - Returns: A dictionary where the keys are header field names, and the values
/// are the corresponding header field values.
open class func requestHeaderFields(with cookies: [HTTPCookie]) -> [String : String] {
var cookieString = cookies.reduce("") { (sum, next) -> String in
return sum + "\(next._name)=\(next._value); "
}
//Remove the final trailing semicolon and whitespace
if ( cookieString.length > 0 ) {
cookieString.characters.removeLast()
cookieString.characters.removeLast()
}
return ["Cookie": cookieString]
}
/// Return an array of cookies parsed from the specified response header fields and URL.
///
/// This method will ignore irrelevant header fields so
/// you can pass a dictionary containing data other than cookie data.
/// - Parameter headerFields: The response header fields to check for cookies.
/// - Parameter URL: The URL that the cookies came from - relevant to how the cookies are interpeted.
/// - Returns: An array of NSHTTPCookie objects
open class func cookies(withResponseHeaderFields headerFields: [String : String], forURL url: URL) -> [HTTPCookie] {
//HTTP Cookie parsing based on RFC 6265: https://tools.ietf.org/html/rfc6265
//Though RFC6265 suggests that multiple cookies cannot be folded into a single Set-Cookie field, this is
//pretty common. It also suggests that commas and semicolons among other characters, cannot be a part of
// names and values. This implementation takes care of multiple cookies in the same field, however it doesn't
//support commas and semicolons in names and values(except for dates)
guard let cookies: String = headerFields["Set-Cookie"] else { return [] }
let nameValuePairs = cookies.components(separatedBy: ";") //split the name/value and attribute/value pairs
.map({$0.trim()}) //trim whitespaces
.map({removeCommaFromDate($0)}) //get rid of commas in dates
.flatMap({$0.components(separatedBy: ",")}) //cookie boundaries are marked by commas
.map({$0.trim()}) //trim again
.filter({$0.caseInsensitiveCompare("HTTPOnly") != .orderedSame}) //we don't use HTTPOnly, do we?
.flatMap({createNameValuePair(pair: $0)}) //create Name and Value properties
//mark cookie boundaries in the name-value array
var cookieIndices = (0..<nameValuePairs.count).filter({nameValuePairs[$0].hasPrefix("Name")})
cookieIndices.append(nameValuePairs.count)
//bake the cookies
var httpCookies: [HTTPCookie] = []
for i in 0..<cookieIndices.count-1 {
if let aCookie = createHttpCookie(url: url, pairs: nameValuePairs[cookieIndices[i]..<cookieIndices[i+1]]) {
httpCookies.append(aCookie)
}
}
return httpCookies
}
//Bake a cookie
private class func createHttpCookie(url: URL, pairs: ArraySlice<String>) -> HTTPCookie? {
var properties: [HTTPCookiePropertyKey : Any] = [:]
for pair in pairs {
let name = pair.components(separatedBy: "=")[0]
var value = pair.components(separatedBy: "\(name)=")[1] //a value can have an "="
if canonicalize(name) == .expires {
value = value.insertComma(at: 3) //re-insert the comma
}
properties[canonicalize(name)] = value
}
//if domain wasn't provided use the URL
if properties[.domain] == nil {
properties[.domain] = url.absoluteString
}
//the default Path is "/"
if properties[.path] == nil {
properties[.path] = "/"
}
return HTTPCookie(properties: properties)
}
//we pass this to a map()
private class func removeCommaFromDate(_ value: String) -> String {
if value.hasPrefix("Expires") || value.hasPrefix("expires") {
return value.removeCommas()
}
return value
}
//These cookie attributes are defined in RFC 6265 and 2965(which is obsolete)
//HTTPCookie supports these
private class func isCookieAttribute(_ string: String) -> Bool {
return _attributes.first(where: {$0.rawValue.caseInsensitiveCompare(string) == .orderedSame}) != nil
}
//Cookie attribute names are case-insensitive as per RFC6265: https://tools.ietf.org/html/rfc6265
//but HTTPCookie needs only the first letter of each attribute in uppercase
private class func canonicalize(_ name: String) -> HTTPCookiePropertyKey {
let idx = _attributes.index(where: {$0.rawValue.caseInsensitiveCompare(name) == .orderedSame})!
return _attributes[idx]
}
//A name=value pair should be translated to two properties, Name=name and Value=value
private class func createNameValuePair(pair: String) -> [String] {
if pair.caseInsensitiveCompare(HTTPCookiePropertyKey.secure.rawValue) == .orderedSame {
return ["Secure=TRUE"]
}
let name = pair.components(separatedBy: "=")[0]
let value = pair.components(separatedBy: "\(name)=")[1]
if !isCookieAttribute(name) {
return ["Name=\(name)", "Value=\(value)"]
}
return [pair]
}
/// Returns a dictionary representation of the receiver.
///
/// This method returns a dictionary representation of the
/// `NSHTTPCookie` which can be saved and passed to
/// `init(properties:)` later to reconstitute an equivalent cookie.
///
/// See the `NSHTTPCookie` `init(properties:)` method for
/// more information on the constraints imposed on the dictionary, and
/// for descriptions of the supported keys and values.
///
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open var properties: [HTTPCookiePropertyKey : Any]? {
return _properties
}
/// The version of the receiver.
///
/// Version 0 maps to "old-style" Netscape cookies.
/// Version 1 maps to RFC2965 cookies. There may be future versions.
open var version: Int {
return _version
}
/// The name of the receiver.
open var name: String {
return _name
}
/// The value of the receiver.
open var value: String {
return _value
}
/// Returns The expires date of the receiver.
///
/// The expires date is the date when the cookie should be
/// deleted. The result will be nil if there is no specific expires
/// date. This will be the case only for *session-only* cookies.
/*@NSCopying*/ open var expiresDate: Date? {
return _expiresDate
}
/// Whether the receiver is session-only.
///
/// `true` if this receiver should be discarded at the end of the
/// session (regardless of expiration date), `false` if receiver need not
/// be discarded at the end of the session.
open var isSessionOnly: Bool {
return _sessionOnly
}
/// The domain of the receiver.
///
/// This value specifies URL domain to which the cookie
/// should be sent. A domain with a leading dot means the cookie
/// should be sent to subdomains as well, assuming certain other
/// restrictions are valid. See RFC 2965 for more detail.
open var domain: String {
return _domain
}
/// The path of the receiver.
///
/// This value specifies the URL path under the cookie's
/// domain for which this cookie should be sent. The cookie will also
/// be sent for children of that path, so `"/"` is the most general.
open var path: String {
return _path
}
/// Whether the receiver should be sent only over secure channels
///
/// Cookies may be marked secure by a server (or by a javascript).
/// Cookies marked as such must only be sent via an encrypted connection to
/// trusted servers (i.e. via SSL or TLS), and should not be delievered to any
/// javascript applications to prevent cross-site scripting vulnerabilities.
open var isSecure: Bool {
return _secure
}
/// Whether the receiver should only be sent to HTTP servers per RFC 2965
///
/// Cookies may be marked as HTTPOnly by a server (or by a javascript).
/// Cookies marked as such must only be sent via HTTP Headers in HTTP Requests
/// for URL's that match both the path and domain of the respective Cookies.
/// Specifically these cookies should not be delivered to any javascript
/// applications to prevent cross-site scripting vulnerabilities.
open var isHTTPOnly: Bool {
return _HTTPOnly
}
/// The comment of the receiver.
///
/// This value specifies a string which is suitable for
/// presentation to the user explaining the contents and purpose of this
/// cookie. It may be nil.
open var comment: String? {
return _comment
}
/// The comment URL of the receiver.
///
/// This value specifies a URL which is suitable for
/// presentation to the user as a link for further information about
/// this cookie. It may be nil.
/*@NSCopying*/ open var commentURL: URL? {
return _commentURL
}
/// The list ports to which the receiver should be sent.
///
/// This value specifies an NSArray of NSNumbers
/// (containing integers) which specify the only ports to which this
/// cookie should be sent.
///
/// The array may be nil, in which case this cookie can be sent to any
/// port.
open var portList: [NSNumber]? {
return _portList
}
}
//utils for cookie parsing
fileprivate extension String {
func trim() -> String {
return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
}
func removeCommas() -> String {
return self.replacingOccurrences(of: ",", with: "")
}
func insertComma(at index:Int) -> String {
return String(self.characters.prefix(index)) + "," + String(self.characters.suffix(self.characters.count-index))
}
}
| apache-2.0 | ad1bc5df7ead4e14ac9ae2c2eec81a78 | 37.382353 | 140 | 0.602214 | 4.617653 | false | false | false | false |
weijingyunIOS/JYAutoLayout | JYAutoLayout-Swift/WideHightAlignment.swift | 1 | 1965 | //
// WideHightAlignment.swift
// FFAutoLayout iOS Examples
//
// Created by wei_jingyun on 15/7/1.
// Copyright © 2015年 joyios. All rights reserved.
//
import UIKit
class WideHightAlignment: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
let centerBtn = UIButton(title: "与self中心对齐 ", bgColor: UIColor.red)
addSubview(centerBtn)
UIEdgeView(centerBtn).center(self).size(200, h: 200).end();
let leftTop = UIButton(title: "WH参考redView", bgColor: UIColor.blue)
addSubview(leftTop)
UIEdgeView(leftTop).alignTop(self,c:64).alignLeft(self).width(centerBtn, m: 0.5).height(centerBtn,m:0.5).end()
let rightTop = UIButton(title: "WH与左上等宽高", bgColor: UIColor.blue)
addSubview(rightTop)
UIEdgeView(rightTop).size(leftTop).alignTop(self,c: 64).alignRight(self).end()
let rightBottom = UIButton(title: "WH与左上等宽高", bgColor: UIColor.blue)
addSubview(rightBottom)
UIEdgeView(rightBottom).alignBottom(self).alignRight(self).size(leftTop).end()
let leftBottom = UIButton(title: "WH与左上等宽高", bgColor: UIColor.blue)
addSubview(leftBottom)
UIEdgeView(leftBottom).alignBottom(self).alignLeft(self).size(leftTop).end()
// 以下为对齐
let centerTop = UIButton(title: "centerTop", bgColor: UIColor.blue)
addSubview(centerTop)
UIEdgeView(centerTop).center(leftTop).size(50, h: 50).end()
let centerleft = UIButton(title: "centerleft", bgColor: UIColor.blue)
addSubview(centerleft)
UIEdgeView(centerleft).centerX(leftTop).centerY(centerBtn, c: 100).size(50, h: 50).end()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit{
print((#file as NSString).lastPathComponent, #function)
}
}
| apache-2.0 | 63952d5cfc809d8139417c12808a2624 | 34.886792 | 118 | 0.650894 | 3.77381 | false | false | false | false |
danielsaidi/Vandelay | VandelayDemo/Photos/UIImage+Resize.swift | 1 | 1297 | //
// UIImage_ResizeExtensions.swift
// VandelayDemo
//
// Created by Daniel Saidi on 2016-01-21.
// Copyright © 2016 Daniel Saidi. All rights reserved.
//
import UIKit
public extension UIImage {
// MARK: - Public functions
func resized(toHeight points: CGFloat) -> UIImage {
let height = points * scale
let ratio = height / size.height
let width = size.width * ratio
let newSize = CGSize(width: width, height: height)
return resized(toSize: newSize, withQuality: .high)
}
func resized(toWidth points: CGFloat) -> UIImage {
let width = points * scale
let ratio = width / size.width
let height = size.height * ratio
let newSize = CGSize(width: width, height: height)
return resized(toSize: newSize, withQuality: .high)
}
}
// MARK: - Private Functions
private extension UIImage {
private func resized(toSize newSize: CGSize, withQuality quality: CGInterpolationQuality) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, scale)
draw(in: CGRect(origin: CGPoint.zero, size: newSize))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result ?? UIImage()
}
}
| mit | 5ab9050352298eb76c8897293b81f791 | 27.8 | 106 | 0.652006 | 4.6121 | false | false | false | false |
neilpa/Erasure | Source/CollectionOf.swift | 1 | 2058 | //
// CollectionOf.swift
// Erasure
//
// Created by Neil Pankey on 5/20/15.
// Copyright (c) 2015 Neil Pankey. All rights reserved.
//
/// A type-erased collection.
public struct CollectionOf<T, Index: ForwardIndexType>: CollectionType {
private let _generate: () -> GeneratorOf<T>
private let _startIndex: () -> Index
private let _endIndex: () -> Index
private let _subscript: (Index) -> T
public init<C: CollectionType where C.Generator.Element == T, C.Index == Index>(_ base: C) {
_generate = { GeneratorOf(base.generate()) }
_startIndex = { base.startIndex }
_endIndex = { base.endIndex }
_subscript = { base[$0] }
}
public func generate() -> GeneratorOf<T> {
return _generate()
}
public var startIndex: Index {
return _startIndex()
}
public var endIndex: Index {
return _endIndex()
}
public subscript(index: Index) -> T {
return _subscript(index)
}
}
/// A type-erased mutable collection.
public struct MutableCollectionOf<T, Index: ForwardIndexType>: MutableCollectionType {
private let _generate: () -> GeneratorOf<T>
private let _startIndex: () -> Index
private let _endIndex: () -> Index
private let _subscript: (Index) -> T
private let _mutate: (Index, T) -> ()
public init<C: MutableCollectionType where C.Generator.Element == T, C.Index == Index>(var _ base: C) {
_generate = { GeneratorOf(base.generate()) }
_startIndex = { base.startIndex }
_endIndex = { base.endIndex }
_subscript = { base[$0] }
_mutate = { (index, value) in base[index] = value }
}
public func generate() -> GeneratorOf<T> {
return _generate()
}
public var startIndex: Index {
return _startIndex()
}
public var endIndex: Index {
return _endIndex()
}
public subscript(index: Index) -> T {
get {
return _subscript(index)
}
set {
_mutate(index, newValue)
}
}
}
| mit | 0684e9168349c742147c162ec897234c | 26.078947 | 107 | 0.586492 | 4.124248 | false | false | false | false |
simeonpp/home-hunt | ios-client/Pods/SwinjectStoryboard/Sources/SwinjectStoryboard.swift | 6 | 7628 | //
// SwinjectStoryboard.swift
// Swinject
//
// Created by Yoichi Tagaya on 7/31/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Swinject
#if os(iOS) || os(tvOS) || os(OSX)
/// The `SwinjectStoryboard` provides the features to inject dependencies of view/window controllers in a storyboard.
///
/// To specify a registration name of a view/window controller registered to the `Container` as a service type,
/// add a user defined runtime attribute with the following settings:
///
/// - Key Path: `swinjectRegistrationName`
/// - Type: String
/// - Value: Registration name to the `Container`
///
/// in User Defined Runtime Attributes section on Indentity Inspector pane.
/// If no name is supplied to the registration, no runtime attribute should be specified.
public class SwinjectStoryboard: _SwinjectStoryboardBase, SwinjectStoryboardProtocol {
/// A shared container used by SwinjectStoryboard instances that are instantiated without specific containers.
///
/// Typical usecases of this property are:
/// - Implicit instantiation of UIWindow and its root view controller from "Main" storyboard.
/// - Storyboard references to transit from a storyboard to another.
public static var defaultContainer = Container()
// Boxing to workaround a runtime error [Xcode 7.1.1 and Xcode 7.2 beta 4]
// If container property is Resolver type and a Resolver instance is assigned to the property,
// the program crashes by EXC_BAD_ACCESS, which looks a bug of Swift.
internal var container: Box<Resolver>!
/// Do NOT call this method explicitly. It is designed to be called by the runtime.
public override class func initialize() {
struct Static {
static var onceToken: () = {
(SwinjectStoryboard.self as SwinjectStoryboardProtocol.Type).setup?()
}()
}
let _ = Static.onceToken
}
private override init() {
super.init()
}
/// Creates the new instance of `SwinjectStoryboard`. This method is used instead of an initializer.
///
/// - Parameters:
/// - name: The name of the storyboard resource file without the filename extension.
/// - bundle: The bundle containing the storyboard file and its resources. Specify nil to use the main bundle.
/// - container: The container with registrations of the view/window controllers in the storyboard and their dependencies.
/// The shared singleton container `SwinjectStoryboard.defaultContainer` is used if no container is passed.
///
/// - Returns: The new instance of `SwinjectStoryboard`.
public class func create(
name: String,
bundle storyboardBundleOrNil: Bundle?,
container: Resolver = SwinjectStoryboard.defaultContainer) -> SwinjectStoryboard
{
// Use this factory method to create an instance because the initializer of UI/NSStoryboard is "not inherited".
let storyboard = SwinjectStoryboard._create(name, bundle: storyboardBundleOrNil)
storyboard.container = Box(container)
return storyboard
}
#if os(iOS) || os(tvOS)
/// Instantiates the view controller with the specified identifier.
/// The view controller and its child controllers have their dependencies injected
/// as specified in the `Container` passed to the initializer of the `SwinjectStoryboard`.
///
/// - Parameter identifier: The identifier set in the storyboard file.
///
/// - Returns: The instantiated view controller with its dependencies injected.
public override func instantiateViewController(withIdentifier identifier: String) -> UIViewController {
SwinjectStoryboard.pushInstantiatingStoryboard(self)
let viewController = super.instantiateViewController(withIdentifier: identifier)
SwinjectStoryboard.popInstantiatingStoryboard()
injectDependency(to: viewController)
return viewController
}
private func injectDependency(to viewController: UIViewController) {
guard !viewController.wasInjected else { return }
defer { viewController.wasInjected = true }
let registrationName = viewController.swinjectRegistrationName
// Xcode 7.1 workaround for Issue #10. This workaround is not necessary with Xcode 7.
// If a future update of Xcode fixes the problem, replace the resolution with the following code and fix storyboardInitCompleted too.
// https://github.com/Swinject/Swinject/issues/10
if let container = container.value as? _Resolver {
let option = SwinjectStoryboardOption(controllerType: type(of: viewController))
typealias FactoryType = (Resolver, Container.Controller) -> Container.Controller
let _ = container._resolve(name: registrationName, option: option) { (factory: FactoryType) in factory(self.container.value, viewController) }
} else {
fatalError("A type conforming Resolver protocol must conform _Resolver protocol too.")
}
for child in viewController.childViewControllers {
injectDependency(to: child)
}
}
#elseif os(OSX)
/// Instantiates the view/Window controller with the specified identifier.
/// The view/window controller and its child controllers have their dependencies injected
/// as specified in the `Container` passed to the initializer of the `SwinjectStoryboard`.
///
/// - Parameter identifier: The identifier set in the storyboard file.
///
/// - Returns: The instantiated view/window controller with its dependencies injected.
public override func instantiateController(withIdentifier identifier: String) -> Any {
SwinjectStoryboard.pushInstantiatingStoryboard(self)
let controller = super.instantiateController(withIdentifier: identifier)
SwinjectStoryboard.popInstantiatingStoryboard()
injectDependency(to: controller)
return controller
}
private func injectDependency(to controller: Container.Controller) {
if let controller = controller as? InjectionVerifiable {
guard !controller.wasInjected else { return }
defer { controller.wasInjected = true }
}
let registrationName = (controller as? RegistrationNameAssociatable)?.swinjectRegistrationName
// Xcode 7.1 workaround for Issue #10. This workaround is not necessary with Xcode 7.
// If a future update of Xcode fixes the problem, replace the resolution with the following code and fix storyboardInitCompleted too:
// https://github.com/Swinject/Swinject/issues/10
if let container = container.value as? _Resolver {
let option = SwinjectStoryboardOption(controllerType: type(of: controller))
typealias FactoryType = (Resolver, Container.Controller) -> Container.Controller
let _ = container._resolve(name: registrationName, option: option) { (factory: FactoryType) in factory(self.container.value, controller) }
} else {
fatalError("A type conforming Resolver protocol must conform _Resolver protocol too.")
}
if let windowController = controller as? NSWindowController, let viewController = windowController.contentViewController {
injectDependency(to: viewController)
}
if let viewController = controller as? NSViewController {
for child in viewController.childViewControllers {
injectDependency(to: child)
}
}
}
#endif
}
#endif
| mit | c648b444a01ff73c9b3a1a3738483806 | 46.66875 | 154 | 0.700144 | 5.27455 | false | false | false | false |
timd/ProiOSTableCollectionViews | Ch08/Chapter8/Chapter8/ViewController.swift | 1 | 4404 | //
// ViewController.swift
// Chapter8
//
// Created by Tim on 29/10/15.
// Copyright © 2015 Tim Duckett. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let OddRowHeight: CGFloat = 70.0
let EvenRowHeight: CGFloat = 100.0
let OddCellIdentifier = "OddCellIdentifier"
let EvenCellIdentifier = "EvenCellIdentifier"
var tableData: [String]!
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
configureTable()
configureData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func configureTable() {
tableView.registerNib(UINib(nibName: "OddCell", bundle: nil), forCellReuseIdentifier: OddCellIdentifier)
tableView.registerNib(UINib(nibName: "EvenCell", bundle: nil), forCellReuseIdentifier: EvenCellIdentifier)
}
func configureData() {
tableData = ["Lorem ipsum dolor sit amet",
"Consectetur adipiscing elit",
"Sed do eiusmod tempor incididunt",
"Labore et dolore magna aliqua",
"Ut enim ad minim veniam",
"Quis nostrud exercitation ullamco",
"Laboris nisi ut aliquip ex ea commodo",
"Duis aute irure dolor in reprehenderit",
"Voluptate velit esse cillum dolore",
"Fugiat nulla pariatur",
"Excepteur sint occaecat",
"Cupidatat non proident",
"Sunt in culpa qui officia",
"Deserunt mollit anim id est laborum",
"Nunc sit amet libero ligula",
"Etiam imperdiet rhoncus enim",
"In pharetra velit porttitor in",
"Aliquam non urna ac lectus mollis dignissim",
"Nunc semper nisi dolor",
"Non faucibus mauris commodo ac",
"Sed maximus nunc sem",
"Dapibus nibh interdum",
"Quisque ut orci rhoncus, suscipit nisi ut",
"Integer luctus consectetur aliquam",
"Nulla ornare lectus malesuada",
"Morbi dapibus, urna eu mollis pharetra",
"Lectus eros commodo libero",
"Et dictum lacus odio ac leo",
"Integer varius urna quis commodo cursus"
]
}
}
extension ViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count - 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let remainder = indexPath.row % 2
switch remainder {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier(EvenCellIdentifier, forIndexPath: indexPath) as! EvenCell
cell.iconView.image = UIImage(named: "cat")
cell.backgroundColor = UIColor(patternImage: UIImage(named: "evenBackground")!)
cell.cellTitle.text = "Cell \(indexPath.row)"
cell.cellMainContent.text = tableData[indexPath.row]
cell.cellOtherContent.text = tableData[indexPath.row + 1]
return cell
default:
let cell = tableView.dequeueReusableCellWithIdentifier(OddCellIdentifier, forIndexPath: indexPath) as! OddCell
cell.iconView.image = UIImage(named: "dog")
cell.backgroundColor = UIColor(patternImage: UIImage(named: "oddBackground")!)
cell.cellTitle.text = "Cell \(indexPath.row)"
cell.cellContent.text = tableData[indexPath.row]
return cell
}
}
}
extension ViewController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath.row % 2 == 0) {
return EvenRowHeight
}
return OddRowHeight
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.backgroundView?.backgroundColor = UIColor.redColor()
}
}
| mit | 1ab1e5b407eb9a1757f23b689b1df792 | 31.614815 | 124 | 0.625028 | 5.235434 | false | false | false | false |
Gajesh1722/FlappyBird | FlappyBird/GameViewController.swift | 1 | 2095 | //
// GameViewController.swift
// FlappyBird
//
// Created by Parth Kheni on 12/4/15.
// Copyright (c) 2015 TechMuzz. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : String) -> SKNode? {
let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks")
let sceneData: NSData?
do {
sceneData = try NSData(contentsOfFile: path!, options: .DataReadingMappedIfSafe)
} catch _ {
sceneData = nil
}
let archiver = NSKeyedUnarchiver(forReadingWithData: sceneData!)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return UIInterfaceOrientationMask.AllButUpsideDown
} else {
return UIInterfaceOrientationMask.All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| mit | 4c2447502a88681e8af09ac657d25621 | 28.928571 | 94 | 0.622912 | 5.6469 | false | false | false | false |
bibekdari/swiftCameraPhotoAndVideo | Camera/CameraViewController.swift | 1 | 11825 | //
// CameraViewController.swift
// Camera
//
// Created by DARI on 4/8/16.
// Copyright © 2016 DARI. All rights reserved.
//
import UIKit
import AVFoundation
class CameraViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var previewView: UIView!
@IBOutlet weak var buttonCapture: UIButton!
//manages the data flow between the inputs and the outputs and error handling
var session = AVCaptureSession()
var cameraPosition: AVCaptureDevicePosition = .Back
let videoOutput = AVCaptureVideoDataOutput()
let stillCameraOutput = AVCaptureStillImageOutput()
let sampleBufferQueue = dispatch_queue_create("sample buffer delegate", DISPATCH_QUEUE_SERIAL)
let sessionQueue = dispatch_queue_create("session queue for camera of com.qwerty1234567.example.capture", DISPATCH_QUEUE_SERIAL)
var cameraModeIsPhoto = true
var currentDevice: AVCaptureDevice!
override func viewDidLoad() {
super.viewDidLoad()
self.startSession()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func captureTouched(sender: UIButton) {
if previewView.hidden {
previewView.hidden = false
return
}
sender.setTitle("Capture", forState: .Normal)
if self.cameraModeIsPhoto {
self.captureStillImage(sessionQueue)
previewView.hidden = true
sender.setTitle("Capturing", forState: .Normal)
}
}
@IBAction func switchCamera(sender: UIButton) {
dispatch_async(sessionQueue) {
self.session.stopRunning()
}
//var newDevice: AVCaptureDevice?
switch self.cameraPosition {
case .Back:
//newDevice = self.getCameraDeviceOfSpecificPosition(AVMediaTypeVideo, position: .Front)
sender.setTitle("Front", forState: .Normal)
self.cameraPosition = .Front
default:
//newDevice = self.getCameraDeviceOfSpecificPosition(AVMediaTypeVideo, position: .Back)
sender.setTitle("Back", forState: .Normal)
self.cameraPosition = .Back
}
// if let newDevice = newDevice {
// self.session.removeInput(getCaptureDeviceInputForCaptureDevice(currentDevice))
// self.currentDevice = newDevice
// self.session.addInput(getCaptureDeviceInputForCaptureDevice(newDevice))
// }
self.session = AVCaptureSession()
self.startSession()
}
func startSession(){
self.session.beginConfiguration()
//if deviceAuthorizationCheck(AVMediaTypeVideo) || deviceAuthorizationCheck(AVMediaTypeAudio) {
if let camera = self.getCameraDeviceOfSpecificPosition(AVMediaTypeVideo, position: self.cameraPosition), let audio = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio) {
self.currentDevice = camera
addInputDeviceToSession(getCaptureDeviceInputForCaptureDevice(audio)!, session: self.session)
addCaptureOutputToSession(captureSession: self.session, captureOutput: self.stillCameraOutput)
if let input = self.getCaptureDeviceInputForCaptureDevice(camera) {
if self.addInputDeviceToSession(input, session: self.session) {
self.attachPreviewLayerToSession(self.session, viewToAddLayer: previewView)
self.addCaptureVideoOutputToSession(catpureSession: self.session, videoOutput: self.videoOutput, sampleBufferdelegateObject: self, queue: self.sampleBufferQueue)
self.addCaptureOutputToSession(captureSession: self.session, captureOutput: self.stillCameraOutput)
self.capturePresetForCaptureDevice(self.session, currentDevice: currentDevice, isOutputStillImage: self.cameraModeIsPhoto)
//since all actions and configs done on the session or the camera are blocking calls so its dispatched to background serial queue
dispatch_async(sessionQueue, {
self.session.startRunning()
})
}
}
}
self.session.commitConfiguration()
//}
}
private func captureStillImage(queue: dispatch_queue_t){
dispatch_async(queue) {
let connection = self.stillCameraOutput.connectionWithMediaType(AVMediaTypeVideo)
//update video orientation w.r.t. device
connection.videoOrientation = AVCaptureVideoOrientation(rawValue: UIDevice.currentDevice().orientation.rawValue) ?? AVCaptureVideoOrientation.Portrait
self.stillCameraOutput.captureStillImageAsynchronouslyFromConnection(connection, completionHandler: { (imageDataSampleBuffer, error) in
if error == nil {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
let _: NSDictionary? = CMCopyDictionaryOfAttachments(nil, imageDataSampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate))
if let image = UIImage(data: imageData) {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let filePath = documentsURL.URLByAppendingPathComponent("temp.jpg")
self.imageView.image = image
//self.buttonCapture.setImage(image, forState: .Normal)
if imageData.writeToURL(filePath, atomically: true) {
dispatch_async(dispatch_get_main_queue(), {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let filePath = documentsURL.URLByAppendingPathComponent("temp.jpg")
//self.imageView.image = UIImage(contentsOfFile: String(filePath))
self.buttonCapture.setTitle("Try Next", forState: .Normal)
})
}
}
}else{
print("Capturing still image error: \(error)")
}
})
}
}
//MARK:- Capture devices and capture input devices
/*
Gives a camera device with type and position of device (back or front)
*/
private func getCameraDeviceOfSpecificPosition(devicesWithMediaType: String, position: AVCaptureDevicePosition) -> AVCaptureDevice?{
if let availableCameraDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as? [AVCaptureDevice] {
let device = availableCameraDevices.filter({ (device) -> Bool in
return device.position == position
})
if device.count > 0 {
return device.first!
}else {
print("No device in given position")
}
}else {
print("No camera device")
}
return nil
}
/*
Gives capture device input for the given capture device
AVCaptureDeviceInput provides input data coming from the device
*/
private func getCaptureDeviceInputForCaptureDevice(captureDevice: AVCaptureDevice) -> AVCaptureDeviceInput? {
do {
return try AVCaptureDeviceInput(device: captureDevice)
} catch {
print("Cannot get input: \(error)")
}
return nil
}
/*
We must add input device to session for getting input from the device to that session
*/
private func addInputDeviceToSession(device: AVCaptureDeviceInput, session: AVCaptureSession) -> Bool {
if session.canAddInput(device) {
session.addInput(device)
return true
}
print("Cant add input to session")
return !true
}
/*
we must add video output for generating outputs
*/
private func addCaptureVideoOutputToSession<T:AVCaptureVideoDataOutputSampleBufferDelegate>(catpureSession session: AVCaptureSession, videoOutput: AVCaptureVideoDataOutput, sampleBufferdelegateObject: T, queue: dispatch_queue_t) -> Bool{
videoOutput.setSampleBufferDelegate(sampleBufferdelegateObject, queue: queue)
return addCaptureOutputToSession(captureSession: session, captureOutput: videoOutput)
}
/*
add output to session
*/
private func addCaptureOutputToSession(captureSession session: AVCaptureSession, captureOutput output: AVCaptureOutput) -> Bool{
if session.canAddOutput(output){
session.addOutput(output)
return true
}
return !true
}
//MARK:- input device permissions check
/*
check if it is authorized for accessing the device input or not
*/
private func deviceAuthorizationCheck(deviceMediaType: String) -> Bool{
switch AVCaptureDevice.authorizationStatusForMediaType(deviceMediaType) {
case .Authorized:
break
case .Restricted, .Denied:
print("user explicitly denied camera usage.")
case .NotDetermined:
//ask for permission
AVCaptureDevice.requestAccessForMediaType(deviceMediaType, completionHandler: { (permissionGrantStatus) in
return permissionGrantStatus
})
}
return !true
}
/*
Attach preview layer to session to display output from the camera or Video Capturing devices.
*/
private func attachPreviewLayerToSession(session: AVCaptureSession, viewToAddLayer view: UIView, frameForPreviewLayer frame: CGRect? = nil) {
let previewLayer = AVCaptureVideoPreviewLayer(session: session)
if let frame = frame {
previewLayer.frame = frame
}else {
previewLayer.frame = self.view.bounds
}
// if let layers = view.layer.sublayers {
// for layer in layers {
// layer.removeFromSuperlayer()
// }
// }
view.layer.addSublayer(previewLayer)
}
/*
set quality of image/video for session
*/
private func capturePresetForCaptureDevice(session: AVCaptureSession , currentDevice: AVCaptureDevice, isOutputStillImage: Bool ){
let capturePreset = self.getCaptureSessionPresetForOutputMode(isOutputStillImage)
if currentDevice.supportsAVCaptureSessionPreset(capturePreset) {
session.sessionPreset = capturePreset
} else {
session.sessionPreset = AVCaptureSessionPresetLow
}
}
/*
Determine which quality of audio or video is to be captured
*/
private func getCaptureSessionPresetForOutputMode(stillImage: Bool) -> String {
return (stillImage) ? AVCaptureSessionPresetPhoto : AVCaptureSessionPresetMedium
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension CameraViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
}
}
| mit | 2b821822fcda90effcc978d8a5ffee50 | 43.618868 | 241 | 0.652486 | 5.698313 | false | false | false | false |
andrebng/Food-Diary | Food Snap/View Controllers/New Meal View Controller/NewMealViewController.swift | 1 | 8503 | //MIT License
//
//Copyright (c) 2017 Andre Nguyen
//
//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.
// AddToDiaryViewController.swift
// Food Snap
//
// Created by Andre Nguyen on 7/30/17.
// Copyright © 2017 Andre Nguyen. All rights reserved.
//
import UIKit
import CoreML
import SwiftOverlays
// MARK: - New Meal Protocol
protocol NewMealDelegate {
func setMealData(viewModel: MealViewViewModel)
}
@available(iOS 11.0, *)
class NewMealViewController : UIViewController, UINavigationControllerDelegate {
static let segueIdentifier = "AddToDiarySegue"
// MARK: - Properties
@IBOutlet weak var topView: UIView!
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var nameOfDishLabel: UILabel!
@IBOutlet weak var nameOfDishTextField: UITextField!
@IBOutlet weak var nameOfDishTextView: UITextView!
@IBOutlet weak var caloriesLabel: UILabel!
@IBOutlet weak var caloriesTextField: UITextField!
@IBOutlet weak var fatLabel: UILabel!
@IBOutlet weak var fatTextField: UITextField!
@IBOutlet weak var ctaButton: UIButton!
// MARK: -
var viewModel: NewMealViewViewModel?
// MARK: -
var mealPredictions: [Meal]?
override func viewDidLoad() {
super.viewDidLoad()
// Setup UI
self.setupUI()
// Init View Model
viewModel = NewMealViewViewModel()
viewModel?.didUpdateName = { [unowned self] (name) in
self.nameOfDishTextView.text = self.viewModel?.name
}
viewModel?.didUpdateCaloriesString = { [unowned self] (calories) in
self.caloriesTextField.text = self.viewModel?.caloriesAsString
}
viewModel?.didUpdateFatString = { [unowned self] (fat) in
self.fatTextField.text = self.viewModel?.fatAsString
}
viewModel?.queryingDidChange = { [unowned self] (querying) in
if querying {
self.showWaitOverlayWithText("Analyzing Image...")
}
else {
self.removeAllOverlays()
}
}
viewModel?.didRecognizeImages = { [unowned self] (meals) in
self.mealPredictions = meals
self.performSegue(withIdentifier: MealPredictionsViewController.segueIdentifier, sender: self)
}
// Set Delegates & Tags
self.nameOfDishTextView.delegate = self
self.caloriesTextField.tag = 2
self.fatTextField.tag = 3
self.caloriesTextField.delegate = self
self.fatTextField.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == MealPredictionsViewController.segueIdentifier {
guard let vc = segue.destination as? MealPredictionsViewController else { return }
vc.mealPredictions = self.mealPredictions
vc.delegate = self
}
}
// Hide keyboard on touch
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.nameOfDishTextView.resignFirstResponder()
self.caloriesTextField.resignFirstResponder()
self.fatTextField.resignFirstResponder()
}
// MARK: - Helper Methods
private func setupUI() {
// Rounden corners on top
self.topView.setRoundedTopCorners()
// Top Gradient
self.topView.setGradientBackground(startColor: UIColor(red:0.06, green:0.52, blue:0.84, alpha:1.0), endColor: UIColor(red:0.35, green:0.60, blue:0.97, alpha:1.0))
// Bottom Gradient
self.bottomView.setGradientBackground(startColor: UIColor.white, endColor: UIColor(red:0.80, green:0.78, blue:0.78, alpha:1.0))
self.ctaButton.layer.cornerRadius = 5
self.ctaButton.clipsToBounds = true
}
// MARK: - Action Methods
@IBAction func clickedCamera(_ sender: Any) {
if !UIImagePickerController.isSourceTypeAvailable(.camera) {
return
}
let cameraPicker = UIImagePickerController()
cameraPicker.presentCamera(viewController: self)
}
@IBAction func clickedLibrary(_ sender: Any) {
let picker = UIImagePickerController()
picker.presentPhotoLibrary(viewController: self)
}
@IBAction func clickedCTA(_ sender: Any) {
if (viewModel?.state() == .isEmpty) {
self.dismiss(animated: true, completion: nil)
}
else if (viewModel?.state() == .isMissingValue) {
let alert = UIAlertController(title: "Error", message: "Please fill in all fields.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
else if (viewModel?.state() == .notEmpty) {
let mutableMeals = DiaryTableViewViewModel.sharedInstance.meals
guard let meal = viewModel?.toMeal() else { return }
mutableMeals.add(meal)
DiaryTableViewViewModel.sharedInstance.meals = mutableMeals
self.dismiss(animated: true, completion: nil)
}
}
}
// MARK: - New Meal Delegate
@available(iOS 11.0, *)
extension NewMealViewController : NewMealDelegate {
func setMealData(viewModel: MealViewViewModel) {
self.viewModel?.name = viewModel.name
self.viewModel?.calories = viewModel.calories
self.viewModel?.fat = viewModel.fat
}
}
// MARK: - UIImage Picker Controller Delegate
@available(iOS 11.0, *)
extension NewMealViewController : UIImagePickerControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true)
guard let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else {
return
}
viewModel?.image = image
}
}
// MARK: - Text Field Delegate
@available(iOS 11.0, *)
extension NewMealViewController : UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
guard let text = textField.text else { return }
if textField.tag == 2 {
viewModel?.calories = text.toFloat()
}
else if textField.tag == 3 {
viewModel?.fat = text.toFloat()
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
}
// MARK: - Text View Delegate
@available(iOS 11.0, *)
extension NewMealViewController: UITextViewDelegate {
func textViewDidEndEditing(_ textView: UITextView) {
viewModel?.name = textView.text
}
}
| mit | 461c7cd9bb19ef2d43e052c9a2fd942c | 32.341176 | 170 | 0.652317 | 4.903114 | false | false | false | false |
ethanneff/organize | Organize/TestViewController.swift | 1 | 4911 | //
// TestViewController.swift
// Organize
//
// Created by Ethan Neff on 6/29/16.
// Copyright © 2016 Ethan Neff. All rights reserved.
//
import UIKit
class TestViewController: UIViewController, PomodoroTimerDelegate {
let button1: UIButton = UIButton()
let button2: UIButton = UIButton()
let button3: UIButton = UIButton()
let button4: UIButton = UIButton()
let button5: UIButton = UIButton()
let label1: UILabel = UILabel()
let timer = PomodoroTimer()
enum Names: Int {
case One
case Two
case Three
case Four
case Five
var output: String {
switch self {
case .One: return "one"
case .Two: return "two"
case .Three: return "three"
case .Four: return "four"
case .Five: return "five"
}
}
}
init() {
super.init(nibName: nil, bundle: nil)
let buttons = [button1, button2, button3, button4, button5]
setupLabel(label: label1)
setupButtons(buttons: buttons)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
timer.delegate = self
timer.reload()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setupLabel(label label: UILabel) {
label1.text = "label"
view.addSubview(label1)
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .Center
label.textColor = Constant.Color.button
label.font = UIFont(name: "Menlo-Regular", size: UIFont.systemFontSize())
var constraints: [NSLayoutConstraint] = []
constraints.append(NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: Constant.Button.padding))
constraints.append(NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: Constant.Button.padding))
constraints.append(NSLayoutConstraint(item: label, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: -Constant.Button.padding))
constraints.append(NSLayoutConstraint(item: label, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: Constant.Button.height))
NSLayoutConstraint.activateConstraints(constraints)
}
func setupButtons(buttons buttons: [UIButton]) {
var constraints: [NSLayoutConstraint] = []
for i in 0..<buttons.count {
let button = buttons[i]
view.addSubview(button)
button.tag = i
button.setTitle(Names(rawValue: i)!.output, forState: .Normal)
button.layer.cornerRadius = 5
button.clipsToBounds = true
button.backgroundColor = Constant.Color.button
button.setTitleColor(Constant.Color.background, forState: .Normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(buttonPressed(_:)), forControlEvents: .TouchUpInside)
constraints.append(NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: i == 0 ? label1 : buttons[i-1], attribute: .Bottom, multiplier: 1, constant: Constant.Button.padding))
constraints.append(NSLayoutConstraint(item: button, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: Constant.Button.padding))
constraints.append(NSLayoutConstraint(item: button, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: -Constant.Button.padding))
constraints.append(NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: Constant.Button.height))
}
NSLayoutConstraint.activateConstraints(constraints)
}
func buttonPressed(button: UIButton) {
switch button.tag {
case 0: buttonOne()
case 1: buttonTwo()
case 2: buttonThree()
case 3: buttonFour()
case 4: buttonFive()
default: break
}
Util.animateButtonPress(button: button)
}
func buttonOne() {
timer.start()
}
func buttonTwo() {
timer.pause()
}
func buttonThree() {
timer.stop()
}
func buttonFour() {
}
func buttonFive() {
}
func pomodoroTimerUpdate(output output: String, isBreak: Bool, isPaused: Bool) {
label1.text = output
label1.textColor = isBreak || isPaused ? Constant.Color.border : Constant.Color.button
}
func pomodoroTimerBreak() {
Util.playSound(systemSound: .BeepBoBoopFailure)
Util.vibrate()
}
func pomodoroTimerWork() {
Util.playSound(systemSound: .BeepBoBoopSuccess)
Util.vibrate()
}
}
| mit | 37299c2f892eebf49239afa94c526dd5 | 32.175676 | 204 | 0.692668 | 4.251082 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAddressSearch/Sources/FeatureAddressSearchUI/View/AddressModificationView.swift | 1 | 8594 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import ComposableArchitecture
import Errors
import ErrorsUI
import FeatureAddressSearchDomain
import Localization
import SwiftUI
import ToolKit
import UIComponentsKit
struct AddressModificationView: View {
private typealias L10n = LocalizationConstants.AddressSearch
private let store: Store<
AddressModificationState,
AddressModificationAction
>
init(
store: Store<
AddressModificationState,
AddressModificationAction
>
) {
self.store = store
}
var body: some View {
WithViewStore(store) { viewStore in
if !viewStore.isPresentedFromSearchView {
PrimaryNavigationView {
content
}
footer
} else {
content
footer
}
}
}
private var content: some View {
WithViewStore(store) { viewStore in
ScrollView {
form
.padding(.vertical, Spacing.padding3)
.primaryNavigation(title: viewStore.screenTitle)
.trailingNavigationButton(.close, isVisible: !viewStore.isPresentedFromSearchView) {
viewStore.send(.cancelEdit)
}
.onAppear {
viewStore.send(.onAppear)
}
.alert(
store.scope(state: \.failureAlert),
dismiss: .dismissAlert
)
}
}
}
private var form: some View {
WithViewStore(store) { viewStore in
VStack(spacing: Spacing.padding3) {
subtitle
VStack(spacing: Spacing.padding1) {
Input(
text: viewStore.binding(\.$line1),
isFirstResponder: viewStore
.binding(\.$selectedInputField)
.equals(.line1),
label: L10n.Form.addressLine1,
placeholder: L10n.Form.Placeholder.line1,
state: viewStore.state.line1.isEmpty ? .error : .default,
configuration: {
$0.textContentType = .streetAddressLine1
},
onReturnTapped: {
viewStore.send(.binding(.set(\.$selectedInputField, .line2)))
}
)
Input(
text: viewStore.binding(\.$line2),
isFirstResponder: viewStore
.binding(\.$selectedInputField)
.equals(.line2),
label: L10n.Form.addressLine2,
placeholder: L10n.Form.Placeholder.line2,
configuration: {
$0.textContentType = .streetAddressLine2
},
onReturnTapped: {
viewStore.send(.binding(.set(\.$selectedInputField, .city)))
}
)
Input(
text: viewStore.binding(\.$city),
isFirstResponder: viewStore
.binding(\.$selectedInputField)
.equals(.city),
label: L10n.Form.city,
configuration: {
$0.textContentType = .addressCity
},
onReturnTapped: {
viewStore.send(.binding(.set(\.$selectedInputField, .state)))
}
)
HStack(spacing: Spacing.padding2) {
if viewStore.isStateFieldVisible {
Input(
text: viewStore.binding(\.$stateName),
isFirstResponder: viewStore
.binding(\.$selectedInputField)
.equals(.state),
label: L10n.Form.state,
configuration: {
$0.textContentType = .addressState
},
onReturnTapped: {
viewStore.send(.binding(.set(\.$selectedInputField, .zip)))
}
)
.disabled(true)
}
Input(
text: viewStore.binding(\.$postcode),
isFirstResponder: viewStore
.binding(\.$selectedInputField)
.equals(.zip),
label: L10n.Form.zip,
configuration: {
$0.textContentType = .postalCode
},
onReturnTapped: {
viewStore.send(.binding(.set(\.$selectedInputField, nil)))
}
)
}
Input(
text: .constant(countryName(viewStore.state.country)),
isFirstResponder: .constant(false),
label: L10n.Form.country
)
.disabled(true)
}
.padding(.horizontal, Spacing.padding3)
}
}
}
private var footer: some View {
WithViewStore(store) { viewStore in
PrimaryButton(
title: viewStore.saveButtonTitle ?? L10n.Buttons.save,
isLoading: viewStore.state.loading
) {
viewStore.send(.updateAddress)
}
.disabled(
viewStore.state.line1.isEmpty
|| viewStore.state.postcode.isEmpty
|| viewStore.state.city.isEmpty
|| viewStore.state.country.isEmpty
)
.frame(alignment: .bottom)
.padding([.horizontal, .bottom])
.background(
Rectangle()
.fill(.white)
.shadow(color: .white, radius: 3, x: 0, y: -15)
)
}
}
private var subtitle: some View {
WithViewStore(store) { viewStore in
if let subtitle = viewStore.screenSubtitle {
VStack(alignment: .leading, spacing: Spacing.padding1) {
Text(subtitle)
.typography(.paragraph1)
.foregroundColor(.WalletSemantic.body)
.multilineTextAlignment(.leading)
}
.padding(.horizontal, Spacing.padding2)
}
}
}
}
extension View {
fileprivate func trailingNavigationButton(
_ navigationButton: NavigationButton,
isVisible: Bool,
action: @escaping () -> Void
) -> some View {
guard isVisible else { return AnyView(self) }
return AnyView(navigationBarItems(
trailing: HStack {
navigationButton.button(action: action)
}
))
}
}
func countryName(_ code: String) -> String {
let locale = NSLocale.current as NSLocale
return locale.displayName(forKey: NSLocale.Key.countryCode, value: code) ?? ""
}
#if DEBUG
struct AddressModification_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
AddressModificationView(
store: Store(
initialState: .init(
addressDetailsId: MockServices.addressId,
isPresentedFromSearchView: false
),
reducer: addressModificationReducer,
environment: .init(
mainQueue: .main,
config: .init(title: "Title", subtitle: "Subtitle"),
addressService: MockServices(),
addressSearchService: MockServices(),
onComplete: { _ in }
)
)
)
}
}
}
#endif
| lgpl-3.0 | cabb07b69b45becc98df9702d0a2b99b | 35.105042 | 100 | 0.442686 | 6.213304 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Cocoa/Extensions/UINavigationBar+Extensions.swift | 1 | 797 | //
// Xcore
// Copyright © 2014 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
extension UINavigationBar {
private enum AssociatedKey {
static var isTransparent = "isTransparent"
}
open var isTransparent: Bool {
get { associatedObject(&AssociatedKey.isTransparent, default: false) }
set {
guard newValue != isTransparent else { return }
setAssociatedObject(&AssociatedKey.isTransparent, value: newValue)
guard newValue else {
setBackgroundImage(nil, for: .default)
return
}
setBackgroundImage(UIImage(), for: .default)
shadowImage = UIImage()
isTranslucent = true
backgroundColor = .clear
}
}
}
| mit | 32be339b54b4b75558067fcfd511843a | 24.677419 | 78 | 0.594221 | 5.527778 | false | false | false | false |
danoli3/ResearchKit | samples/ORKCatalog/ORKCatalog/Results/ResultTableViewProviders.swift | 2 | 39043 | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import ResearchKit
/**
Create a `protocol<UITableViewDataSource, UITableViewDelegate>` that knows
how to present the metadata for an `ORKResult` instance. Extra metadata is
displayed for specific `ORKResult` types. For example, a table view provider
for an `ORKFileResult` instance will display the `fileURL` in addition to the
standard `ORKResult` properties.
To learn about how to read metadata from the different kinds of `ORKResult`
instances, see the `ResultTableViewProvider` subclasses below. Specifically,
look at their `resultRowsForSection(_:)` implementations which are meant to
enhance the metadata that is displayed for the result table view provider.
Note: since these table view providers are meant to display data for developers
and are not user visible (see description in `ResultViewController`), none
of the properties / content are localized.
*/
func resultTableViewProviderForResult(result: ORKResult?) -> protocol<UITableViewDataSource, UITableViewDelegate> {
guard let result = result else {
/*
Use a table view provider that shows that there hasn't been a recently
provided result.
*/
return NoRecentResultTableViewProvider()
}
// The type that will be used to create an instance of a table view provider.
let providerType: ResultTableViewProvider.Type
/*
Map the type of the result to its associated `ResultTableViewProvider`.
To reduce the possible effects of someone modifying this code--i.e.
cases getting reordered and accidentally getting matches for subtypes
of the intended result type, we guard against any subtype matches
(e.g. the `ORKCollectionResult` guard against `result` being an
`ORKTaskResult` instance).
*/
switch result {
// Survey Questions
case is ORKBooleanQuestionResult:
providerType = BooleanQuestionResultTableViewProvider.self
case is ORKChoiceQuestionResult:
providerType = ChoiceQuestionResultTableViewProvider.self
case is ORKDateQuestionResult:
providerType = DateQuestionResultTableViewProvider.self
case is ORKNumericQuestionResult:
providerType = NumericQuestionResultTableViewProvider.self
case is ORKScaleQuestionResult:
providerType = ScaleQuestionResultTableViewProvider.self
case is ORKTextQuestionResult:
providerType = TextQuestionResultTableViewProvider.self
case is ORKTimeIntervalQuestionResult:
providerType = TimeIntervalQuestionResultTableViewProvider.self
case is ORKTimeOfDayQuestionResult:
providerType = TimeOfDayQuestionResultTableViewProvider.self
// Consent
case is ORKConsentSignatureResult:
providerType = ConsentSignatureResultTableViewProvider.self
// Active Tasks
case is ORKPasscodeResult:
providerType = PasscodeResultTableViewProvider.self
case is ORKFileResult:
providerType = FileResultTableViewProvider.self
case is ORKSpatialSpanMemoryResult:
providerType = SpatialSpanMemoryResultTableViewProvider.self
case is ORKTappingIntervalResult:
providerType = TappingIntervalResultTableViewProvider.self
case is ORKToneAudiometryResult:
providerType = ToneAudiometryResultTableViewProvider.self
case is ORKReactionTimeResult:
providerType = ReactionTimeViewProvider.self
case is ORKTowerOfHanoiResult:
providerType = TowerOfHanoiResultTableViewProvider.self
case is ORKPSATResult:
providerType = PSATResultTableViewProvider.self
case is ORKTimedWalkResult:
providerType = TimedWalkResultTableViewProvider.self
case is ORKHolePegTestResult:
providerType = HolePegTestResultTableViewProvider.self
// All
case is ORKTaskResult:
providerType = TaskResultTableViewProvider.self
/*
Refer to the comment near the switch statement for why the
additional guard is here.
*/
case is ORKCollectionResult where !(result is ORKTaskResult):
providerType = CollectionResultTableViewProvider.self
default:
fatalError("No ResultTableViewProvider defined for \(result.dynamicType).")
}
// Return a new instance of the specific `ResultTableViewProvider`.
return providerType.init(result: result)
}
/**
An enum representing the data that can be presented in a `UITableViewCell` by
a `ResultsTableViewProvider` type.
*/
enum ResultRow {
// MARK: Cases
case Text(String, detail: String, selectable: Bool)
case TextImage(String, image: UIImage?)
case Image(UIImage?)
// MARK: Types
/**
Possible `UITableViewCell` identifiers that have been defined in the main
storyboard.
*/
enum TableViewCellIdentifier: String {
case Default = "Default"
case NoResultSet = "NoResultSet"
case NoChildResults = "NoChildResults"
case TextImage = "TextImage"
case Image = "Image"
}
// MARK: Initialization
/// Helper initializer for `ResultRow.Text`.
init(text: String, detail: Any?, selectable: Bool = false) {
/*
Show the string value if `detail` is not `nil`, otherwise show that
it's "nil". Use Optional's map method to map the value to a string
if the detail is not `nil`.
*/
let detailText = detail.map { String($0) } ?? "nil"
self = .Text(text, detail: detailText, selectable: selectable)
}
}
/**
A special `protocol<UITableViewDataSource, UITableViewDelegate>` that displays
a row saying that there's no result.
*/
class NoRecentResultTableViewProvider: NSObject, UITableViewDataSource, UITableViewDelegate {
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier(ResultRow.TableViewCellIdentifier.NoResultSet.rawValue, forIndexPath: indexPath)
}
}
// MARK: ResultTableViewProvider and Subclasses
/**
Base class for displaying metadata for an `ORKResult` instance. The metadata
that's displayed are common properties for all `ORKResult` instances (e.g.
`startDate` and `endDate`).
*/
class ResultTableViewProvider: NSObject, UITableViewDataSource, UITableViewDelegate {
// MARK: Properties
let result: ORKResult
// MARK: Initializers
required init(result: ORKResult) {
self.result = result
}
// MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let resultRows = resultRowsForSection(section)
// Show an empty row if there isn't any metadata in the rows for this section.
if resultRows.isEmpty {
return 1
}
return resultRows.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let resultRows = resultRowsForSection(indexPath.section)
// Show an empty row if there isn't any metadata in the rows for this section.
if resultRows.isEmpty {
return tableView.dequeueReusableCellWithIdentifier(ResultRow.TableViewCellIdentifier.NoChildResults.rawValue, forIndexPath: indexPath)
}
// Fetch the `ResultRow` that corresponds to `indexPath`.
let resultRow = resultRows[indexPath.row]
switch resultRow {
case let .Text(text, detail: detailText, selectable):
let cell = tableView.dequeueReusableCellWithIdentifier(ResultRow.TableViewCellIdentifier.Default.rawValue, forIndexPath: indexPath)
cell.textLabel!.text = text
cell.detailTextLabel!.text = detailText
/*
In this sample, the accessory type should be a disclosure
indicator if the table view cell is selectable.
*/
cell.selectionStyle = selectable ? .Default : .None
cell.accessoryType = selectable ? .DisclosureIndicator : .None
return cell
case let .TextImage(text, image):
let cell = tableView.dequeueReusableCellWithIdentifier(ResultRow.TableViewCellIdentifier.TextImage.rawValue, forIndexPath: indexPath) as! TextImageTableViewCell
cell.leftTextLabel.text = text
cell.rightImageView.image = image
return cell
case let .Image(image):
let cell = tableView.dequeueReusableCellWithIdentifier(ResultRow.TableViewCellIdentifier.Image.rawValue, forIndexPath: indexPath) as! ImageTableViewCell
cell.fullImageView.image = image
return cell
}
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? "Result" : nil
}
// MARK: Overridable Methods
func resultRowsForSection(section: Int) -> [ResultRow] {
// Default to an empty array.
guard section == 0 else { return [] }
return [
// The class name of the result object.
ResultRow(text: "type", detail: result.dynamicType),
/*
The identifier of the result, which corresponds to the task,
step or item that generated it.
*/
ResultRow(text: "identifier", detail: result.identifier),
// The start date for the result.
ResultRow(text: "start", detail: result.startDate),
// The end date for the result.
ResultRow(text: "end", detail: result.endDate)
]
}
}
/// Table view provider specific to an `ORKBooleanQuestionResult` instance.
class BooleanQuestionResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let boolResult = result as! ORKBooleanQuestionResult
var boolResultDetailText: String?
if let booleanAnswer = boolResult.booleanAnswer {
boolResultDetailText = booleanAnswer.boolValue ? "true" : "false"
}
return super.resultRowsForSection(section) + [
ResultRow(text: "bool", detail: boolResultDetailText)
]
}
}
/// Table view provider specific to an `ORKChoiceQuestionResult` instance.
class ChoiceQuestionResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let choiceResult = result as! ORKChoiceQuestionResult
return super.resultRowsForSection(section) + [
ResultRow(text: "choices", detail: choiceResult.choiceAnswers)
]
}
}
/// Table view provider specific to an `ORKDateQuestionResult` instance.
class DateQuestionResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let questionResult = result as! ORKDateQuestionResult
return super.resultRowsForSection(section) + [
// The date the user entered.
ResultRow(text: "dateAnswer", detail: questionResult.dateAnswer),
// The calendar that was used when the date picker was presented.
ResultRow(text: "calendar", detail: questionResult.calendar),
// The timezone when the user answered.
ResultRow(text: "timeZone", detail: questionResult.timeZone)
]
}
}
/// Table view provider specific to an `ORKNumericQuestionResult` instance.
class NumericQuestionResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let questionResult = result as! ORKNumericQuestionResult
return super.resultRowsForSection(section) + [
// The numeric value the user entered.
ResultRow(text: "numericAnswer", detail: questionResult.numericAnswer),
// The unit string that was displayed with the numeric value.
ResultRow(text: "unit", detail: questionResult.unit)
]
}
}
/// Table view provider specific to an `ORKScaleQuestionResult` instance.
class ScaleQuestionResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let scaleQuestionResult = result as! ORKScaleQuestionResult
return super.resultRowsForSection(section) + [
// The numeric value returned from the discrete or continuous slider.
ResultRow(text: "scaleAnswer", detail: scaleQuestionResult.scaleAnswer)
]
}
}
/// Table view provider specific to an `ORKTextQuestionResult` instance.
class TextQuestionResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let questionResult = result as! ORKTextQuestionResult
return super.resultRowsForSection(section) + [
// The text the user typed into the text view.
ResultRow(text: "textAnswer", detail: questionResult.textAnswer)
]
}
}
/// Table view provider specific to an `ORKTimeIntervalQuestionResult` instance.
class TimeIntervalQuestionResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let questionResult = result as! ORKTimeIntervalQuestionResult
return super.resultRowsForSection(section) + [
// The time interval the user answered.
ResultRow(text: "intervalAnswer", detail: questionResult.intervalAnswer)
]
}
}
/// Table view provider specific to an `ORKTimeOfDayQuestionResult` instance.
class TimeOfDayQuestionResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let questionResult = result as! ORKTimeOfDayQuestionResult
// Format the date components received in the result.
let dateComponentsFormatter = NSDateComponentsFormatter()
let dateComponentsAnswerText = dateComponentsFormatter.stringFromDateComponents(questionResult.dateComponentsAnswer!)
return super.resultRowsForSection(section) + [
// String summarizing the date components the user entered.
ResultRow(text: "dateComponentsAnswer", detail: dateComponentsAnswerText)
]
}
}
/// Table view provider specific to an `ORKConsentSignatureResult` instance.
class ConsentSignatureResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let signatureResult = result as! ORKConsentSignatureResult
let signature = signatureResult.signature!
return super.resultRowsForSection(section) + [
/*
The identifier for the signature, identifying which one it is in
the document.
*/
ResultRow(text: "identifier", detail: signature.identifier),
/*
The title of the signatory, displayed under the line. For
example, "Participant".
*/
ResultRow(text: "title", detail: signature.title),
// The given name of the signatory.
ResultRow(text: "givenName", detail: signature.givenName),
// The family name of the signatory.
ResultRow(text: "familyName", detail: signature.familyName),
// The date the signature was obtained.
ResultRow(text: "date", detail: signature.signatureDate),
// The captured image.
.TextImage("signature", image: signature.signatureImage)
]
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let lastRow = self.tableView(tableView, numberOfRowsInSection: indexPath.section) - 1
if indexPath.row == lastRow {
return 200
}
return UITableViewAutomaticDimension
}
}
/// Table view provider specific to an `ORKPasscodeResult` instance.
class PasscodeResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let passcodeResult = result as! ORKPasscodeResult
var passcodeResultDetailText: String?
passcodeResultDetailText = passcodeResult.passcodeSaved.boolValue ? "true" : "false"
return super.resultRowsForSection(section) + [
ResultRow(text: "passcodeSaved", detail: passcodeResultDetailText)
]
}
}
/// Table view provider specific to an `ORKFileResult` instance.
class FileResultTableViewProvider: ResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let questionResult = result as! ORKFileResult
let rows = super.resultRowsForSection(section) + [
// The MIME content type for the file produced.
ResultRow(text: "contentType", detail: questionResult.contentType),
// The URL of the generated file on disk.
ResultRow(text: "fileURL", detail: questionResult.fileURL)
]
if let fileURL = questionResult.fileURL, let contentType = questionResult.contentType where contentType.hasPrefix("image/") {
if let data = NSData(contentsOfURL: fileURL), let image = UIImage(data: data) {
return rows + [
// The image of the generated file on disk.
.Image(image)
]
}
}
return rows
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let resultRows = resultRowsForSection(indexPath.section)
if !resultRows.isEmpty {
switch resultRows[indexPath.row] {
case .Image(.Some(let image)):
// Keep the aspect ratio the same.
let imageAspectRatio = image.size.width / image.size.height
return tableView.frame.size.width / imageAspectRatio
default:
break
}
}
return UITableViewAutomaticDimension
}
}
/// Table view provider specific to an `ORKSpatialSpanMemoryResult` instance.
class SpatialSpanMemoryResultTableViewProvider: ResultTableViewProvider {
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return super.tableView(tableView, titleForHeaderInSection: 0)
}
return "Game Records"
}
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let questionResult = result as! ORKSpatialSpanMemoryResult
let rows = super.resultRowsForSection(section)
if section == 0 {
return rows + [
// The score the user received for the game as a whole.
ResultRow(text: "score", detail: questionResult.score),
// The number of games played.
ResultRow(text: "numberOfGames", detail: questionResult.numberOfGames),
// The number of failures.
ResultRow(text: "numberOfFailures", detail: questionResult.numberOfFailures)
]
}
return rows + questionResult.gameRecords!.map { gameRecord in
// Note `gameRecord` is of type `ORKSpatialSpanMemoryGameRecord`.
return ResultRow(text: "game", detail: gameRecord.score)
}
}
}
/// Table view provider specific to an `ORKTappingIntervalResult` instance.
class TappingIntervalResultTableViewProvider: ResultTableViewProvider {
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return super.tableView(tableView, titleForHeaderInSection: 0)
}
return "Samples"
}
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let questionResult = result as! ORKTappingIntervalResult
let rows = super.resultRowsForSection(section)
if section == 0 {
return rows + [
// The size of the view where the two target buttons are displayed.
ResultRow(text: "stepViewSize", detail: questionResult.stepViewSize),
// The rect corresponding to the left button.
ResultRow(text: "buttonRect1", detail: questionResult.buttonRect1),
// The rect corresponding to the right button.
ResultRow(text: "buttonRect2", detail: questionResult.buttonRect2)
]
}
// Add a `ResultRow` for each sample.
return rows + questionResult.samples!.map { tappingSample in
// These tap locations are relative to the rectangle defined by `stepViewSize`.
let buttonText = tappingSample.buttonIdentifier == .None ? "None" : "button \(tappingSample.buttonIdentifier.rawValue)"
let text = String(format: "%.3f", tappingSample.timestamp)
let detail = "\(buttonText) \(tappingSample.location)"
return ResultRow(text: text, detail: detail)
}
}
}
/// Table view provider specific to an `ORKToneAudiometryResult` instance.
class ToneAudiometryResultTableViewProvider: ResultTableViewProvider {
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return super.tableView(tableView, titleForHeaderInSection: 0)
}
return "Samples"
}
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let toneAudiometryResult = result as! ORKToneAudiometryResult
let rows = super.resultRowsForSection(section)
if section == 0 {
return rows + [
// The size of the view where the two target buttons are displayed.
ResultRow(text: "outputVolume", detail: toneAudiometryResult.outputVolume),
]
}
// Add a `ResultRow` for each sample.
return rows + toneAudiometryResult.samples!.map { toneSample in
let text: String
let detail: String
let channelName = toneSample.channel == .Left ? "Left" : "Right"
text = "\(toneSample.frequency) \(channelName)"
detail = "\(toneSample.amplitude)"
return ResultRow(text: text, detail: detail)
}
}
}
/// Table view provider specific to an `ORKReactionTimeResult` instance.
class ReactionTimeViewProvider: ResultTableViewProvider {
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return super.tableView(tableView, titleForHeaderInSection: 0)
}
return "File Results"
}
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let reactionTimeResult = result as! ORKReactionTimeResult
let rows = super.resultRowsForSection(section)
if section == 0 {
return rows + [
ResultRow(text: "timestamp", detail: reactionTimeResult.timestamp)
]
}
let fileResultDetail = reactionTimeResult.fileResult.fileURL!.absoluteString
return rows + [
ResultRow(text: "File Result", detail: fileResultDetail)
]
}
}
/// Table view provider specific to an `ORKTowerOfHanoiResult` instance.
class TowerOfHanoiResultTableViewProvider: ResultTableViewProvider {
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let towerOfHanoiResult = result as! ORKTowerOfHanoiResult
return towerOfHanoiResult.moves != nil ? (towerOfHanoiResult.moves!.count + 1) : 1
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return super.tableView(tableView, titleForHeaderInSection: 0)
}
return "Move \(section )"
}
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let towerOfHanoiResult = result as! ORKTowerOfHanoiResult
let rows = super.resultRowsForSection(section)
if section == 0 {
return rows + [
ResultRow(text: "solved", detail: towerOfHanoiResult.puzzleWasSolved ? "true" : "false"),
ResultRow(text: "moves", detail: "\(towerOfHanoiResult.moves?.count ?? 0 )")]
}
// Add a `ResultRow` for each sample.
let move = towerOfHanoiResult.moves![section - 1] as! ORKTowerOfHanoiMove
return rows + [
ResultRow(text: "donor tower", detail: "\(move.donorTowerIndex)"),
ResultRow(text: "recipient tower", detail: "\(move.recipientTowerIndex)"),
ResultRow(text: "timestamp", detail: "\(move.timestamp)")]
}
}
/// Table view provider specific to an `ORKPSATResult` instance.
class PSATResultTableViewProvider: ResultTableViewProvider {
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return super.tableView(tableView, titleForHeaderInSection: 0)
}
return "Answers"
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let PSATResult = result as! ORKPSATResult
var rows = super.resultRowsForSection(section)
if section == 0 {
var presentation = ""
let presentationMode = PSATResult.presentationMode
if (presentationMode == .Auditory) {
presentation = "PASAT"
} else if (presentationMode == .Visual) {
presentation = "PVSAT"
} else if (presentationMode.contains(.Auditory) && presentationMode.contains(.Visual)) {
presentation = "PAVSAT"
} else {
presentation = "Unknown"
}
// The presentation mode (auditory and/or visual) of the PSAT.
rows.append(ResultRow(text: "presentation", detail: presentation))
// The time interval between two digits.
rows.append(ResultRow(text: "ISI", detail: PSATResult.interStimulusInterval))
// The time duration the digit is shown on screen.
rows.append(ResultRow(text: "stimulus", detail: PSATResult.stimulusDuration))
// The serie length of the PSAT.
rows.append(ResultRow(text: "length", detail: PSATResult.length))
// The number of correct answers.
rows.append(ResultRow(text: "total correct", detail: PSATResult.totalCorrect))
// The total number of consecutive correct answers.
rows.append(ResultRow(text: "total dyad", detail: PSATResult.totalDyad))
// The total time for the answers.
rows.append(ResultRow(text: "total time", detail: PSATResult.totalTime))
// The initial digit number.
rows.append(ResultRow(text: "initial digit", detail: PSATResult.initialDigit))
return rows
}
// Add a `ResultRow` for each sample.
return rows + PSATResult.samples!.map { sample in
let PSATSample = sample as! ORKPSATSample
let text = String(format: "%@", PSATSample.correct ? "correct" : "error")
let detail = "\(PSATSample.answer) (digit: \(PSATSample.digit), time: \(PSATSample.time))"
return ResultRow(text: text, detail: detail)
}
}
}
/// Table view provider specific to an `ORKTimedWalkResult` instance.
class TimedWalkResultTableViewProvider: ResultTableViewProvider {
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return super.tableView(tableView, titleForHeaderInSection: 0)
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let TimedWalkResult = result as! ORKTimedWalkResult
let rows = super.resultRowsForSection(section)
return rows + [
// The timed walk distance in meters.
ResultRow(text: "distance (m)", detail: TimedWalkResult.distanceInMeters),
// The time limit to complete the trials.
ResultRow(text: "time limit (s)", detail: TimedWalkResult.timeLimit),
// The duration for a Timed Walk.
ResultRow(text: "duration (s)", detail: TimedWalkResult.duration)
]
}
}
/// Table view provider specific to an `ORKHolePegTestResult` instance.
class HolePegTestResultTableViewProvider: ResultTableViewProvider {
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return super.tableView(tableView, titleForHeaderInSection: 0)
}
return "Moves"
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let holePegTestResult = result as! ORKHolePegTestResult
var rows = super.resultRowsForSection(section)
if section == 0 {
var side = ""
let movingDirection = holePegTestResult.movingDirection
if (movingDirection == .Left) {
side = "left > right"
} else if (movingDirection == .Right) {
side = "right > left"
}
// The hole peg test moving direction.
rows.append(ResultRow(text: "direction", detail: side))
// The step is for the dominant hand.
rows.append(ResultRow(text: "dominant hand", detail: holePegTestResult.dominantHandTested))
// The number of pegs to test.
rows.append(ResultRow(text: "number of pegs", detail: holePegTestResult.numberOfPegs))
// The detection area sensitivity.
rows.append(ResultRow(text: "threshold", detail: holePegTestResult.threshold))
// The hole peg test also assesses the rotation capabilities.
if result.identifier.rangeOfString("place") != nil {
rows.append(ResultRow(text: "rotated", detail: holePegTestResult.rotated))
}
// The number of succeeded moves (out of `numberOfPegs` possible).
rows.append(ResultRow(text: "total successes", detail: holePegTestResult.totalSuccesses))
// The number of failed moves.
rows.append(ResultRow(text: "total failures", detail: holePegTestResult.totalFailures))
// The total time needed to perform the test step (ie. the sum of all samples time).
rows.append(ResultRow(text: "total time", detail: holePegTestResult.totalTime))
// The total distance needed to perform the test step (ie. the sum of all samples distance).
rows.append(ResultRow(text: "total distance", detail: holePegTestResult.totalDistance))
return rows
}
// Add a `ResultRow` for each sample.
return rows + holePegTestResult.samples!.map { sample in
let holePegTestSample = sample as! ORKHolePegTestSample
let text = "time (s): \(holePegTestSample.time))"
let detail = "distance (pt): \(holePegTestSample.distance)"
return ResultRow(text: text, detail: detail)
}
}
}
/// Table view provider specific to an `ORKTaskResult` instance.
class TaskResultTableViewProvider: CollectionResultTableViewProvider {
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let taskResult = result as! ORKTaskResult
let rows = super.resultRowsForSection(section)
if section == 0 {
return rows + [
ResultRow(text: "taskRunUUID", detail: taskResult.taskRunUUID.UUIDString),
ResultRow(text: "outputDirectory", detail: taskResult.outputDirectory)
]
}
return rows
}
}
/// Table view provider specific to an `ORKCollectionResult` instance.
class CollectionResultTableViewProvider: ResultTableViewProvider {
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return super.tableView(tableView, titleForHeaderInSection: 0)
}
return "Child Results"
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return indexPath.section == 1
}
// MARK: ResultTableViewProvider
override func resultRowsForSection(section: Int) -> [ResultRow] {
let collectionResult = result as! ORKCollectionResult
let rows = super.resultRowsForSection(section)
// Show the child results in section 1.
if section == 1 {
return rows + collectionResult.results!.map { childResult in
let childResultClassName = "\(childResult.dynamicType)"
return ResultRow(text: childResultClassName, detail: childResult.identifier, selectable: true)
}
}
return rows
}
}
| bsd-3-clause | 14aaeca6dfd276c139457dba97ba2df4 | 37.12793 | 176 | 0.645903 | 5.633098 | false | false | false | false |
djschilling/SOPA-iOS | SOPA/view/LevelMode/LevelModeScoreScene.swift | 1 | 5409 | //
// LevelModeScoreScene.swift
// SOPA
//
// Created by Raphael Schilling on 17.05.18.
// Copyright © 2018 David Schilling. All rights reserved.
//
import Foundation
import SpriteKit
class LevelModeScoreScene: SKScene {
let BUTTON_DIMENTIONS = CGFloat(0.28)
let BUTTON_HEIGHT = CGFloat(0.05)
let STAR_HEIGHT_HEIGH = CGFloat(0.37)
let STAR_HEIGHT_LOW = CGFloat(0.33)
let TITLE_HEIGHT = CGFloat(0.95)
let levelResult: LevelResult
init(size: CGSize, levelResult: LevelResult) {
self.levelResult = levelResult
super.init(size: size)
addButtons()
addStaticObjects()
}
func addButtons() {
let restartButton = SpriteButton(imageNamed: "restart", onClick: restartLevel)
let levelChoiceButton = SpriteButton(imageNamed: "LevelChoice", onClick: levelChoiceMenu)
let nextLevelButton = SpriteButton(imageNamed: "NextLevel", onClick: startNextLevel)
let buttonSize = CGSize(width: size.width * BUTTON_DIMENTIONS, height: size.width * BUTTON_DIMENTIONS)
restartButton.size = buttonSize
levelChoiceButton.size = buttonSize
nextLevelButton.size = buttonSize
let buttonY = size.width * BUTTON_DIMENTIONS / 2 + size.height * BUTTON_HEIGHT
restartButton.position = CGPoint(x: size.width / 2, y: buttonY)
levelChoiceButton.position = CGPoint(x: size.width / 6, y: 100)
nextLevelButton.position = CGPoint(x: 5 * size.width / 6, y: 100)
addChild(restartButton)
addChild(levelChoiceButton)
addChild(nextLevelButton)
}
func addStaticObjects() {
let titleLableA = SKLabelNode(fontNamed: "Impact")
titleLableA.text = String(levelResult.levelId) + ". Level"
titleLableA.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center
titleLableA.verticalAlignmentMode = SKLabelVerticalAlignmentMode.top
titleLableA.position.y = size.height * TITLE_HEIGHT
titleLableA.position.x = size.width / 2
titleLableA.fontSize = size.height * 0.1
addChild(titleLableA)
let titleLableB = SKLabelNode(fontNamed: "Impact")
titleLableB.text = "complete"
titleLableB.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center
titleLableB.verticalAlignmentMode = SKLabelVerticalAlignmentMode.top
titleLableB.position.y = size.height * TITLE_HEIGHT - 0.1 * size.height
titleLableB.position.x = size.width / 2
titleLableB.fontSize = size.height * 0.1
addChild(titleLableB)
let yourMovesLable = SKLabelNode(fontNamed: "Impact")
yourMovesLable.text = "Your moves:\t\t\t\t" + String(levelResult.moveCount)
yourMovesLable.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center
yourMovesLable.verticalAlignmentMode = SKLabelVerticalAlignmentMode.bottom
yourMovesLable.position.y = size.height * (0.6)
yourMovesLable.position.x = size.width / 2
yourMovesLable.fontSize = size.height * 0.05
addChild(yourMovesLable)
let level = ResourcesManager.getInstance().levelService!.getLevelById(id: levelResult.levelId)!
let movesPossibleLable = SKLabelNode(fontNamed: "Impact")
movesPossibleLable.text = "Moves for 3 stars:\t" + String(level.minimumMovesToSolve!)
movesPossibleLable.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center
movesPossibleLable.verticalAlignmentMode = SKLabelVerticalAlignmentMode.bottom
movesPossibleLable.position.y = size.height * (0.52)
movesPossibleLable.position.x = size.width / 2
movesPossibleLable.fontSize = size.height * 0.05
addChild(movesPossibleLable)
addStars()
}
func addStars() {
let starSize = CGSize(width: size.width * 0.36, height: size.width * 0.36)
let star1 = SKSpriteNode(imageNamed: "star_score" )
star1.size = starSize
star1.position = CGPoint(x: starSize.width / 2, y: STAR_HEIGHT_HEIGH * size.height)
addChild(star1)
let star2 = SKSpriteNode(imageNamed: levelResult.stars >= 2 ? "star_score": "starSW_score")
star2.size = starSize
star2.position = CGPoint(x: size.width / 2, y: STAR_HEIGHT_LOW * size.height)
addChild(star2)
let star3 = SKSpriteNode(imageNamed: levelResult.stars == 3 ? "star_score": "starSW_score")
star3.size = starSize
star3.position = CGPoint(x: size.width - starSize.width / 2, y: STAR_HEIGHT_HEIGH * size.height)
addChild(star3)
}
func restartLevel() {
ResourcesManager.getInstance().storyService?.reloadLevelModeGameScene(levelId: levelResult.levelId)
}
func levelChoiceMenu() {
ResourcesManager.getInstance().storyService?.loadLevelCoiceScene()
}
func startNextLevel() {
if ResourcesManager.getInstance().levelService?.getLevelCount() == levelResult.levelId {
ResourcesManager.getInstance().storyService?.loadLevelCoiceScene()
} else {
ResourcesManager.getInstance().storyService?.loadNextLevelModeGameScene(levelId: levelResult.levelId + 1)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 5390f71a202d7edf6377b92fb62a435a | 41.25 | 117 | 0.673447 | 4.322942 | false | false | false | false |
onebytecode/krugozor-iOSVisitors | krugozor-visitorsApp/VisitorManager.swift | 1 | 4417 | //
// VisitorManager.swift
// krugozor-visitorsApp
//
// Created by Alexander Danilin on 21/10/2017.
// Copyright © 2017 oneByteCode. All rights reserved.
//
import Foundation
/// Version 0.1.0
// For Version 1.0.0
// TODO: Errors Suppot
// TODO: Logging
public enum VisitorManagerErrors: String, Error {
case Error1 = "1"
case Error2 = "2"
case Error3 = "3"
case Error4 = "4"
}
protocol VisitorManaging {
func currentVisitorEmail() throws -> String?
// Working
func isRegisteredVisitorBy(email: String, completion: @escaping (_ result: Bool?, _ error: VisitorManagerErrors?) -> Void)
// Working
func visitorLogInWith(data: VisitorAuthorizationData, completion: @escaping ((_ visitor: Visitor?, _ error: VisitorManagerErrors?) -> Void))
// Working
func registerNewVisitorBy(data: VisitorAuthorizationData, completion: @escaping ((_ visitor: Visitor?, _ error: VisitorManagerErrors?) -> Void))
func parseLoginDataToModel(_ email: String, _ password: String) -> VisitorAuthorizationData
}
class VisitorManager: VisitorManaging {
let apiManager = APIManager()
let dataManager = DataManager()
public func currentVisitorEmail() throws -> String? {
do {
guard let currentVisitor = try dataManager.currentVisitor() else { log.error(DataErrors.noCurrentVisior); throw DataErrors.noCurrentVisior }
return currentVisitor.email
} catch let error {
log.error(error)
throw error
}
}
/// Main Log In Entry Point
///
/// - Parameters:
/// - data: VisitorAuthorizationData with Email & Password
/// - completion: Returns Chached Visior Model or Error
public func visitorLogInWith(data: VisitorAuthorizationData, completion: @escaping ((_ visitor: Visitor?, _ error: VisitorManagerErrors?) -> Void)) {
// Getting SessionToken Via API
apiManager.visitorLogInWith(data: data) { (_sessionToken, _error) in
guard (_sessionToken != nil) else { log.error(_error as Any); return completion (nil, VisitorManagerErrors.Error1)}
// Getting Cached Visitor Via DataManager
self.dataManager.fetchVisitorBy(sessionToken: _sessionToken!, completion: { (_visitor, _error) in
guard (_visitor != nil) else {log.error(_error as Any); return completion(nil, VisitorManagerErrors.Error1)}
return completion(_visitor, nil)
})
}
}
/// Main Registration Point; Auto Loging After Successful Registration
///
/// - Parameters:
/// - data: VisitorAuthorizationData With Min Filled Properties
/// - completion: A Logged, Cached Visitor Model With SessionToken Inside
func registerNewVisitorBy(data: VisitorAuthorizationData, completion: @escaping ((_ visitor: Visitor?, _ error: VisitorManagerErrors?) -> Void)) {
// Registering Via API & Getting SessionToken
self.apiManager.visitorRegistrationWith(data: data) { (_sessionToken, _error) in
guard _sessionToken != nil else { log.error(_error as Any); return completion(nil, VisitorManagerErrors.Error1)}
self.dataManager.fetchVisitorBy(sessionToken: _sessionToken!, completion: { (_visitor, _error) in
guard _visitor != nil else { log.error(_error as Any); return completion(nil, VisitorManagerErrors.Error1)}
return completion(_visitor, nil)
})
}
}
/// Checks is user registred on server by provided email
///
/// - Parameters:
/// - email: Visitor Email
/// - completion: Bool of the answer; VisitorManagerError
public func isRegisteredVisitorBy(email: String, completion: @escaping (_ result: Bool?, _ error: VisitorManagerErrors?) -> Void) {
self.apiManager.isVisitorRegisteredBy(email: email) { (_result, _error) in
guard _result != nil else {log.error(_error as Any); return completion(nil, VisitorManagerErrors.Error1)}
return completion(_result, nil)
}
}
func parseLoginDataToModel(_ email: String, _ password: String) -> VisitorAuthorizationData {
let model = VisitorAuthorizationData(email: email, password: password)
return model
}
}
| apache-2.0 | d3b3ec3a81a0a707785691841141074b | 38.079646 | 153 | 0.641531 | 4.61442 | false | false | false | false |
jovito-royeca/Decktracker | ios/old/Decktracker/View/Cards/TopListViewController.swift | 1 | 13395 | //
// TopListViewController.swift
// Decktracker
//
// Created by Jovit Royeca on 11/19/14.
// Copyright (c) 2014 Jovito Royeca. All rights reserved.
//
import UIKit
class TopListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, InAppPurchaseViewControllerDelegate {
var viewButton:UIBarButtonItem?
var tblList:UITableView?
var colList:UICollectionView?
var cardIds:[String]?
var viewMode:String?
var viewLoadedOnce = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
hidesBottomBarWhenPushed = true
viewButton = UIBarButtonItem(image: UIImage(named: "list.png"), style: UIBarButtonItemStyle.Plain, target: self, action: "viewButtonTapped")
navigationItem.rightBarButtonItem = viewButton
if let value = NSUserDefaults.standardUserDefaults().stringForKey(kCardViewMode) {
if value == kCardViewModeList {
self.viewMode = kCardViewModeList
self.showTableView()
} else if value == kCardViewModeGrid2x2 {
self.viewMode = kCardViewModeGrid2x2
viewButton!.image = UIImage(named: "2x2.png")
self.showGridView()
} else if value == kCardViewModeGrid3x3 {
self.viewMode = kCardViewModeGrid3x3
viewButton!.image = UIImage(named: "3x3.png")
self.showGridView()
} else {
self.viewMode = kCardViewModeList
self.showTableView()
}
} else {
self.viewMode = kCardViewModeList
self.showTableView()
}
self.loadData()
self.viewLoadedOnce = false
#if !DEBUG
// send the screen to Google Analytics
if let tracker = GAI.sharedInstance().defaultTracker {
tracker.set(kGAIScreenName, value: self.navigationItem.title)
tracker.send(GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject])
}
#endif
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name:kFetchTopRatedDone, object:nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name:kFetchTopViewedDone, object:nil)
}
func viewButtonTapped() {
var initialSelection = 0
if self.viewMode == kCardViewModeList {
initialSelection = 0
} else if self.viewMode == kCardViewModeGrid2x2 {
initialSelection = 1
} else if self.viewMode == kCardViewModeGrid3x3 {
initialSelection = 2
}
let doneBlock = { (picker: ActionSheetStringPicker?, selectedIndex: NSInteger, selectedValue: AnyObject?) -> Void in
switch selectedIndex {
case 0:
self.viewMode = kCardViewModeList
self.viewButton!.image = UIImage(named: "list.png")
self.showTableView()
case 1:
self.viewMode = kCardViewModeGrid2x2
self.viewButton!.image = UIImage(named: "2x2.png")
self.showGridView()
case 2:
self.viewMode = kCardViewModeGrid3x3
self.viewButton!.image = UIImage(named: "3x3.png")
self.showGridView()
default:
break
}
NSUserDefaults.standardUserDefaults().setObject(self.viewMode, forKey: kCardViewMode)
NSUserDefaults.standardUserDefaults().synchronize()
self.loadData()
}
ActionSheetStringPicker.showPickerWithTitle("View As",
rows: [kCardViewModeList, kCardViewModeGrid2x2, kCardViewModeGrid3x3],
initialSelection: initialSelection,
doneBlock: doneBlock,
cancelBlock: nil,
origin: view)
}
func loadData() {
NSNotificationCenter.defaultCenter().removeObserver(self, name:kFetchTopRatedDone, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector:"updateData:", name:kFetchTopRatedDone, object:nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name:kFetchTopViewedDone, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector:"updateData:", name:kFetchTopViewedDone, object:nil)
}
func showTableView() {
let y = viewLoadedOnce ? 0 : UIApplication.sharedApplication().statusBarFrame.size.height + self.navigationController!.navigationBar.frame.size.height
let height = view.frame.size.height - y
let frame = CGRect(x:0, y:y, width:view.frame.width, height:height)
tblList = UITableView(frame: frame, style: UITableViewStyle.Plain)
tblList!.delegate = self
tblList!.dataSource = self
if colList != nil {
colList!.removeFromSuperview()
}
view.addSubview(tblList!)
}
func showGridView() {
let y = viewLoadedOnce ? 0 : UIApplication.sharedApplication().statusBarFrame.size.height + self.navigationController!.navigationBar.frame.size.height
let height = view.frame.size.height - y
let divisor:CGFloat = viewMode == kCardViewModeGrid2x2 ? 2 : 3
let frame = CGRect(x:0, y:y, width:view.frame.width, height:height)
let layout = CSStickyHeaderFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.headerReferenceSize = CGSize(width:view.frame.width, height: 22)
layout.itemSize = CGSize(width: frame.width/divisor, height: frame.height/divisor)
colList = UICollectionView(frame: frame, collectionViewLayout: layout)
colList!.dataSource = self
colList!.delegate = self
colList!.registerClass(CardImageCollectionViewCell.self, forCellWithReuseIdentifier: "Card")
colList!.backgroundColor = UIColor(patternImage: UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/Gray_Patterned_BG.jpg")!)
if tblList != nil {
tblList!.removeFromSuperview()
}
view.addSubview(colList!)
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return CGFloat(CARD_SUMMARY_VIEW_CELL_HEIGHT)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cardIds!.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cardId = cardIds![indexPath.row]
var cell:UITableViewCell?
var cardSummaryView:CardSummaryView?
if let x = tableView.dequeueReusableCellWithIdentifier(kCardInfoViewIdentifier) as UITableViewCell! {
cell = x
for subView in cell!.contentView.subviews {
if subView is CardSummaryView {
cardSummaryView = subView as? CardSummaryView
break
}
}
} else {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: kCardInfoViewIdentifier)
cardSummaryView = NSBundle.mainBundle().loadNibNamed("CardSummaryView", owner: self, options: nil).first as? CardSummaryView
cardSummaryView!.frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: CGFloat(CARD_SUMMARY_VIEW_CELL_HEIGHT))
cell!.contentView.addSubview(cardSummaryView!)
}
cell!.accessoryType = UITableViewCellAccessoryType.None
cell!.selectionStyle = UITableViewCellSelectionStyle.None
cardSummaryView!.displayCard(cardId)
cardSummaryView!.addRank(indexPath.row+1)
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cardId = cardIds![indexPath.row]
let card = DTCard(forPrimaryKey: cardId)
let dict = Database.sharedInstance().inAppSettingsForSet(card!.set.setId)
var view:UIViewController?
if dict != nil {
let view2 = InAppPurchaseViewController()
view2.productID = dict["In-App Product ID"] as! String
view2.delegate = self;
view2.productDetails = ["name" : dict["In-App Display Name"] as! String,
"description": dict["In-App Description"] as! String]
view = view2
} else {
let view2 = CardDetailsViewController()
view2.addButtonVisible = true
view2.cardId = cardId
view = view2
}
self.navigationController?.pushViewController(view!, animated:false)
}
// MARK: UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cardIds!.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cardId = cardIds![indexPath.row]
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Card", forIndexPath: indexPath) as! CardImageCollectionViewCell
cell.displayCard(cardId, cropped: false, showName: false, showSetIcon: false)
cell.addRank(indexPath.row+1)
return cell
}
// MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cardId = cardIds![indexPath.row]
let card = DTCard(forPrimaryKey: cardId)
let dict = Database.sharedInstance().inAppSettingsForSet(card!.set.setId)
var view:UIViewController?
if dict != nil {
let view2 = InAppPurchaseViewController()
view2.productID = dict["In-App Product ID"] as! String
view2.delegate = self;
view2.productDetails = ["name" : dict["In-App Display Name"] as! String,
"description": dict["In-App Description"] as! String]
view = view2
} else {
let view2 = CardDetailsViewController()
view2.addButtonVisible = true
view2.cardId = cardId
view = view2
}
self.navigationController?.pushViewController(view!, animated:false)
}
// MARK: UIScrollViewDelegate
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if scrollView.isKindOfClass(UITableView.classForCoder()) ||
scrollView.isKindOfClass(UICollectionView.classForCoder()) {
if navigationItem.title == "Top Rated" {
if cardIds!.count >= 100 {
return
} else {
Database.sharedInstance().fetchTopRated(10, skip: Int32(cardIds!.count))
}
} else if navigationItem.title == "Top Viewed" {
if cardIds!.count >= 100 {
return
} else {
Database.sharedInstance().fetchTopViewed(10, skip: Int32(cardIds!.count))
}
}
}
}
func updateData(sender: AnyObject) {
let notif = sender as! NSNotification
let dict = notif.userInfo as! [String: [String]]
let kardIds = dict["cardIds"]!
var paths = [NSIndexPath]()
for cardId in kardIds {
if !cardIds!.contains(cardId) {
cardIds!.append(cardId)
paths.append(NSIndexPath(forRow: cardIds!.count-1, inSection: 0))
FileManager.sharedInstance().downloadCardImage(cardId, immediately:false)
}
}
if paths.count > 0 {
if tblList != nil {
tblList!.beginUpdates()
tblList!.insertRowsAtIndexPaths(paths, withRowAnimation:UITableViewRowAnimation.Automatic)
tblList!.endUpdates()
}
if colList != nil {
colList!.performBatchUpdates({ () -> Void in
self.colList!.insertItemsAtIndexPaths(paths)
}, completion: nil)
}
}
}
// MARK: InAppPurchaseViewControllerDelegate
func productPurchaseCancelled() {
// empty implementation
}
func productPurchaseSucceeded(productID: String) {
Database.sharedInstance().loadInAppSets()
tblList!.reloadData()
}
}
| apache-2.0 | 3844022916ee1b4eb6de4250dd20179d | 38.747774 | 182 | 0.61732 | 5.386007 | false | false | false | false |
chrisjmendez/swift-exercises | Music/Apple/iTunesQueryAdvanced/iTunesQueryAdvanced/APIController.swift | 1 | 2715 | //
// APIController.swift
// iTunesQueryAdvanced
//
// Created by tommy trojan on 5/20/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
import Foundation
protocol APIControllerProtocol {
func didReceiveAPIResults(results: NSArray)
}
class APIController{
var delegate: APIControllerProtocol?
func searchItunesFor(searchTerm: String, searchCategory: String) {
// The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs
let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
// Now escape anything else that isn't URL-friendly
if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlPath = "http://itunes.apple.com/search?term=\(escapedSearchTerm)&media=\(searchCategory)"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
print("\(escapedSearchTerm) query complete.")
if(error != nil) {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
var err: NSError?
let jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
print("JSON Error \(err!.localizedDescription)")
}
//Trigger the delegate once the data has been parsed
if let results: NSArray = jsonResult["results"] as? NSArray {
self.delegate?.didReceiveAPIResults(results)
}
})
task.resume()
}
}
}
extension String {
/// Percent escape value to be added to a URL query value as specified in RFC 3986
/// - returns: Return precent escaped string.
func stringByReplacingSpaceWithPlusEncodingForQueryValue() -> String? {
let term = self.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
// Anything which is not URL-friendly is escaped
let escapedTerm = term.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
return escapedTerm
}
}
| mit | 32943acfb2797c67dc86c34fc7b66567 | 42.790323 | 167 | 0.642357 | 5.552147 | false | false | false | false |
rain2540/RGAppTools | Sources/Extensions/Foundation/NSDictionary+RGAppTools.swift | 1 | 1548 | //
// NSDictionary+RGAppTools.swift
// RGAppTools
//
// Created by RAIN on 16/2/5.
// Copyright © 2016-2017 Smartech. All rights reserved.
//
import Foundation
extension RGAppTools where Base: NSDictionary {
/// 检验 NSDictionary 中是否存在某个 key
/// - Parameter key: 待检验的 key
/// - Returns: 检验结果的布尔值
public func isHave(key: String) -> Bool {
return base.value(forKey: key) != nil
}
}
// MARK: - Main Bundle
extension NSDictionary {
/// 获取 Main Bundle 中某个文件的内容, 创建为 NSDictionary
/// - Parameters:
/// - name: 文件名
/// - ext: 文件扩展名
public convenience init?(
mainBundlePathForResource name: String?,
ofType ext: String?)
{
guard let path = Bundle.main.path(forResource: name, ofType: ext) else {
print("RGApptools: NSDictionary init with main bundle path for resource of type is nil")
return nil
}
self.init(contentsOfFile: path)
}
}
// MARK: - Check key exist or not
extension NSDictionary {
/// 检验 NSDictionary 中是否存在某个 key
/// - Parameter key: 待检验的 key
/// - Returns: 检验结果的布尔值
@available(*, deprecated, message: "Extensions directly on NSDictionary are deprecated. Use `NSDictionary.rat.isHave(key:)` instead.", renamed: "rat.isHave(key:)")
func rat_isHaveKey(_ key: String) -> Bool {
let keys = self.allKeys as! [String]
for aKey: String in keys {
if key == aKey {
return true
}
}
return false
}
}
| mpl-2.0 | 7bdabb7389480f2daa470999f2fe4fc2 | 21.555556 | 165 | 0.649543 | 3.700521 | false | false | false | false |
oliverkulpakko/ATMs | ATMs/RemoteService/RemoteService.swift | 1 | 2746 | //
// RemoteService.swift
// ATMs
//
// Created by Oliver Kulpakko on 25/12/2018.
// Copyright © 2018 East Studios. All rights reserved.
//
import Foundation
class RemoteService {
private init() {}
/// Shared instance
static let shared = RemoteService()
/// Base URL to use. It might change between different environments.
private let baseUrl = "https://eaststudios.net/api/ATMs"
func makeRequest<T: Decodable>(_ path: String,
method: HTTPMethod,
body: RequestBody?,
responseType: T.Type,
completion: @escaping (Result<T, Error>) -> Void) {
guard let url = URL(string: baseUrl + path) else {
completion(.failure(ErrorResponse.unknown))
return
}
var request = URLRequest(url: url)
request.httpMethod = method.rawValue.uppercased()
self.addHeaders(to: &request, body: body)
URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
guard let data = data, let response = response, error == nil else {
completion(.failure(error ?? ErrorResponse.unknown))
return
}
if let error = self.decodeError(from: data, response: response) {
completion(.failure(error))
return
}
let decoder = JSONDecoder()
do {
let result = try decoder.decode(responseType, from: data)
DispatchQueue.main.async {
completion(.success(result))
}
} catch {
DispatchQueue.main.async {
completion(.failure(error))
}
}
}).resume()
}
/// Add headers to a request and set the `httpBody` based on `body`.
private func addHeaders(to request: inout URLRequest, body: RequestBody?) {
if let body = body {
switch body {
case .dictionary(let dictionary):
request.httpBody = try? JSONSerialization.data(withJSONObject: dictionary)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
case .data(let data, let contentType):
request.httpBody = data
if let contentType = contentType {
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
}
}
}
}
/// Get an error from `data` and `response`.
///
/// - Returns: An optional error from `data` and `response`.
private func decodeError(from data: Data, response: URLResponse) -> Error? {
let httpUrlResponse = response as? HTTPURLResponse
let statusCode = httpUrlResponse?.statusCode ?? 500
if statusCode < 400 {
return nil
}
if let error = try? JSONDecoder().decode(ErrorResponse.self, from: data) {
return error
}
return HTTPError(response: response)
}
// MARK: Model
enum HTTPMethod: String {
case get
case post
case put
case delete
}
enum RequestBody {
case dictionary([String: Any])
case data(Data, contentType: String?)
}
}
| mit | 7d6763d7a86d900677f021088583657c | 23.72973 | 89 | 0.67541 | 3.734694 | false | false | false | false |
fgengine/quickly | Quickly/ViewControllers/QWebViewController.swift | 1 | 10171 | //
// Quickly
//
open class QWebViewController : QViewController, WKUIDelegate, WKNavigationDelegate, UIScrollViewDelegate, IQInputContentViewController, IQStackContentViewController, IQPageContentViewController, IQGroupContentViewController, IQModalContentViewController, IQDialogContentViewController, IQHamburgerContentViewController, IQJalousieContentViewController, IQLoadingViewDelegate {
public class WebView : WKWebView {
public override var safeAreaInsets: UIEdgeInsets {
get { return self.customInsets }
}
public var customInsets: UIEdgeInsets = UIEdgeInsets.zero {
didSet(oldValue) {
if self.customInsets != oldValue {
if #available(iOS 11.0, *) {
self.safeAreaInsetsDidChange()
} else {
self.scrollView.contentInset = UIEdgeInsets(
top: self.customInsets.top,
left: 0,
bottom: self.customInsets.bottom,
right: 0
)
self.scrollView.scrollIndicatorInsets = UIEdgeInsets(
top: self.customInsets.top,
left: self.customInsets.left,
bottom: self.customInsets.bottom,
right: self.customInsets.right
)
}
}
}
}
}
public var allowInvalidCertificates: Bool = false
public var localCertificateUrls: [URL] = []
public private(set) lazy var webView: WebView = {
let webView = WebView(frame: self.view.bounds, configuration: self.prepareConfiguration())
webView.uiDelegate = self
webView.navigationDelegate = self
if #available(iOS 11.0, *) {
webView.scrollView.contentInsetAdjustmentBehavior = .always
}
if #available(iOS 13.0, *) {
webView.scrollView.automaticallyAdjustsScrollIndicatorInsets = false
}
webView.scrollView.delegate = self
self.view.addSubview(webView)
return webView
}()
public var loadingView: QLoadingViewType? {
willSet {
guard let loadingView = self.loadingView else { return }
loadingView.removeFromSuperview()
loadingView.delegate = nil
}
didSet {
guard let loadingView = self.loadingView else { return }
loadingView.delegate = self
}
}
deinit {
if self.isLoaded == true {
self.webView.scrollView.delegate = nil
self.webView.navigationDelegate = nil
self.webView.uiDelegate = nil
}
}
open override func layout(bounds: CGRect) {
super.layout(bounds: bounds)
self.webView.frame = bounds
if let view = self.loadingView, view.superview == self.view {
self._updateFrame(loadingView: view, bounds: bounds)
}
}
open override func didChangeContentEdgeInsets() {
super.didChangeContentEdgeInsets()
if self.isLoaded == true {
self._updateContentInsets(webView: self.webView)
if let view = self.loadingView, view.superview != nil {
self._updateFrame(loadingView: view, bounds: self.view.bounds)
}
}
}
open func prepareConfiguration() -> WKWebViewConfiguration {
return WKWebViewConfiguration()
}
@discardableResult
open func load(url: URL) -> WKNavigation? {
let navigation = self.webView.load(URLRequest(url: url))
if navigation != nil {
self.startLoading()
}
return navigation
}
@discardableResult
open func load(request: URLRequest) -> WKNavigation? {
let navigation = self.webView.load(request)
if navigation != nil {
self.startLoading()
}
return navigation
}
@discardableResult
open func load(fileUrl: URL, readAccessURL: URL) -> WKNavigation? {
let navigation = self.webView.loadFileURL(fileUrl, allowingReadAccessTo: readAccessURL)
if navigation != nil {
self.startLoading()
}
return navigation
}
@discardableResult
open func load(html: String, baseUrl: URL?) -> WKNavigation? {
let navigation = self.webView.loadHTMLString(html, baseURL: baseUrl)
if navigation != nil {
self.startLoading()
}
return navigation
}
@discardableResult
open func load(data: Data, mimeType: String, encoding: String, baseUrl: URL) -> WKNavigation? {
let navigation = self.webView.load(data, mimeType: mimeType, characterEncodingName: encoding, baseURL: baseUrl)
if navigation != nil {
self.startLoading()
}
return navigation
}
open func canNavigationAction(with request: URLRequest) -> WKNavigationActionPolicy {
return .allow
}
open func isLoading() -> Bool {
guard let loadingView = self.loadingView else { return false }
return loadingView.isAnimating()
}
open func startLoading() {
guard let loadingView = self.loadingView else { return }
loadingView.start()
}
open func stopLoading() {
guard let loadingView = self.loadingView else { return }
loadingView.stop()
}
// MARK: WKUIDelegate
open func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if let url = navigationAction.request.url {
if navigationAction.targetFrame?.isMainFrame == true {
webView.load(navigationAction.request)
} else {
let application = UIApplication.shared
if application.canOpenURL(url) == true {
application.openURL(url)
}
}
}
return nil
}
// MARK: WKNavigationDelegate
open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
var actionPolicy: WKNavigationActionPolicy = .allow
let request = navigationAction.request
if let url = request.url, let sheme = url.scheme {
switch sheme {
case "tel", "mailto":
let application = UIApplication.shared
if application.canOpenURL(url) == true {
application.openURL(url)
}
actionPolicy = .cancel
break
default:
actionPolicy = .allow
break
}
}
decisionHandler(actionPolicy)
}
open func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let challenge = QImplAuthenticationChallenge(
localCertificateUrls: self.localCertificateUrls,
allowInvalidCertificates: self.allowInvalidCertificates,
challenge: challenge
)
completionHandler(challenge.disposition, challenge.credential)
}
open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.stopLoading()
}
open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
self.stopLoading()
}
// MARK: UIScrollViewDelegate
// MARK: IQContentViewController
public var contentOffset: CGPoint {
get {
guard self.isLoaded == true else { return CGPoint.zero }
return self.webView.scrollView.contentOffset
}
}
public var contentSize: CGSize {
get {
guard self.isLoaded == true else { return CGSize.zero }
return self.webView.scrollView.contentSize
}
}
open func notifyBeginUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.beginUpdateContent()
}
}
open func notifyUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.updateContent()
}
}
open func notifyFinishUpdateContent(velocity: CGPoint) -> CGPoint? {
if let viewController = self.contentOwnerViewController {
return viewController.finishUpdateContent(velocity: velocity)
}
return nil
}
open func notifyEndUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.endUpdateContent()
}
}
// MARK: IQModalContentViewController
open func modalShouldInteractive() -> Bool {
return true
}
// MARK: IQDialogContentViewController
open func dialogDidPressedOutside() {
}
// MARK: IQHamburgerContentViewController
open func hamburgerShouldInteractive() -> Bool {
return true
}
// MARK: IQJalousieContentViewController
open func jalousieShouldInteractive() -> Bool {
return true
}
// MARK: IQLoadingViewDelegate
open func willShow(loadingView: QLoadingViewType) {
self._updateFrame(loadingView: loadingView, bounds: self.view.bounds)
self.view.addSubview(loadingView)
}
open func didHide(loadingView: QLoadingViewType) {
loadingView.removeFromSuperview()
}
}
// MARK: Private
private extension QWebViewController {
func _updateContentInsets(webView: WKWebView) {
self.webView.customInsets = self.adjustedContentInset
}
func _updateFrame(loadingView: QLoadingViewType, bounds: CGRect) {
loadingView.frame = bounds
}
}
| mit | 11b124d5c77fbb948e6e44432c65af97 | 32.130293 | 377 | 0.603972 | 5.600771 | false | false | false | false |
austinzheng/swift-compiler-crashes | crashes-duplicates/03278-swift-printingdiagnosticconsumer-handlediagnostic.swift | 11 | 1070 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
private let a : String {
struct A<T where f: Int = c
() {
struct B<b: a {
class C<T where S.c(""""
func b: A<T, A {
struct A<h : A {
private let v: A? {
func g: A? {
class b: a() -> <T where f: A<h : () -> V {
class A : A {
class b: String {
class A {
typealias e = c() -> <b: b in c<A? {
struct c(""""""""""
struct A {
for b in c() {
class A {
typealias e = {
var b { func g: String {
protocol c : a<T : String {
let v: A.c() -> V {
func g: b = [Void{
func a() -> <h : A<h : () {
class C<T : A {
func a<h : a = Swift.c : A<T) -> Bool {
struct A.c() -> V {
class d<h : a {
if true {
() -> V {
struct A {
struct A {
struct A? {
struct c() -> <T where S.c {
for b { func a
if true {
protocol c {
class A {
struct A {
struct A {
struct A<T) -> Bool {
private let b { func g: a {
let v: a {
struct B<A<A.c : A? = [Void{
protocol A : Int = {
protocol c {
protocol A {
protocol c {
private let b { func a("
| mit | 4631be6c89643ebf00a6b4cfb488ce3c | 19.188679 | 87 | 0.571963 | 2.590799 | false | false | false | false |
nodes-ios/NStackSDK | NStackSDK/NStackSDK/Classes/Other/Extensions.swift | 1 | 980 | //
// Extensions.swift
// NStackSDK
//
// Created by Dominik Hádl on 12/08/16.
// Copyright © 2016 Nodes ApS. All rights reserved.
//
import Foundation
extension FileManager {
var documentsDirectory: URL? {
return urls(for: .documentDirectory, in: .userDomainMask).first
}
}
extension String {
func index(from: Int) -> Index {
return index(startIndex, offsetBy: from)
}
func substring(to: Int) -> String {
let toIndex = index(from: to)
return String(self[..<toIndex])
}
}
extension ISO8601DateFormatter {
convenience init(_ formatOptions: Options, timeZone: TimeZone = TimeZone(secondsFromGMT: 0)!) {
self.init()
self.formatOptions = formatOptions
self.timeZone = timeZone
}
}
extension Formatter {
static let iso8601 = ISO8601DateFormatter([.withInternetDateTime])
}
extension Date {
var iso8601: String {
return DateFormatter.iso8601.string(from: self)
}
}
| mit | dff9a1ecc661eb1cd963c1faf55b3025 | 21.227273 | 99 | 0.656442 | 4.109244 | false | false | false | false |
bricepollock/HTMLRenderingTableView | HTMLRenderingTableView/HTMLTableViewController.swift | 1 | 1836 | //
// HTMLTableViewController.swift
// HTMLRenderingTableView
//
// Created by Brice Pollock on 4/27/15.
// Copyright (c) 2015 Brice Pollock. All rights reserved.
//
import UIKit
class HTMLTableViewController: UITableViewController {
var htmlTextList = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
htmlTextList.append("normal text")
htmlTextList.append("<b>bolded</b>")
htmlTextList.append("<i>italics</i>")
htmlTextList.append("It is possible to have both <i>italic</i> and <b>bolded</b> text! Even on multi-lines which can sometimes be <b>problematic</b>.")
htmlTextList.append("Mixed text can also work using <b>NSAttributed String</b>, but it can be <i>slow</i> when paging thorugh the table view.")
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return htmlTextList.count
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 30
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("HTMLTableViewCell", forIndexPath: indexPath) as! HTMLTableViewCell
cell.configure(htmlTextList[indexPath.row])
// Possibly needed if you have exra HTML tags you need rendering
if indexPath.row == htmlTextList.count-1 {
cell.configureUsingDecoding(htmlTextList[indexPath.row])
}
return cell
}
}
| mit | c7dd0a0f151b6302795347785cb212a1 | 36.469388 | 159 | 0.691176 | 4.78125 | false | false | false | false |
deltaDNA/ios-sdk | Mocks/DDNANetworkRequestMock.swift | 1 | 728 | class DDNANetworkRequestMock: DDNANetworkRequest {
public var data: Data = Data()
public var response: URLResponse?
public var error: NSError?
convenience init(with Url: String, data: NSString?, statusCode: NSInteger, error: NSError?) {
self.init()
if let data = data {
self.data = data.data(using: String.Encoding.utf8.rawValue)!
}
self.response = HTTPURLResponse(url: URL(fileURLWithPath: Url), statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: nil)!
self.error = error
}
override func send() {
NSLog("I'm a fake network request")
super.handleResponse(self.data, response: self.response, error: self.error)
}
}
| apache-2.0 | 07af4de159fc403ba5affab3587d3b92 | 37.315789 | 140 | 0.651099 | 4.208092 | false | false | false | false |
abavisg/BarsAroundMe | BarsAroundMe/BarsAroundMeTests/PlacesAroundLocationURLFactorySpec.swift | 1 | 1026 | //
// PlacesAroundLocationURLFactorySpec.swift
// BarsAroundMe
//
// Created by Giorgos Ampavis on 19/03/2017.
// Copyright © 2017 Giorgos Ampavis. All rights reserved.
//
import Quick
import Nimble
@testable import BarsAroundMe
class PlacesAroundLocationURLFactorySpec: QuickSpec {
override func spec() {
let expectedURL = URL(string: "https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=bar&key=AIzaSyBwofsXbxWZ2rci34Zs019VMy80fZgtCYI")
let basePath = "https://maps.googleapis.com/maps/api/place/search/json"
let parameters = ["location":"-33.8670522,151.1957362"] as [String : Any]
let urlFactory = PlacesAroundLocationURLFactory(withBasePath: basePath, andParameters: parameters)
describe("The url() method") {
it("should return the expected url given the passed parameters") {
expect(urlFactory.url()).to(equal(expectedURL))
}
}
}
}
| mit | 4fdc7207845e18200dcd7be0b01c7d88 | 34.344828 | 193 | 0.678049 | 3.782288 | false | false | false | false |
CD1212/Doughnut | Pods/FeedKit/Sources/FeedKit/Models/Namespaces/Media/MediaEmbed.swift | 2 | 3098 | //
// MediaEmbed.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// Sometimes player-specific embed code is needed for a player to play any
/// video. <media:embed> allows inclusion of such information in the form of
/// key-value pairs.
public class MediaEmbed {
/// The element's attributes.
public class Attributes {
/// The location of the embeded media.
public var url: String?
/// The width size for the embeded Media.
public var width: Int?
/// The height size for the embeded Media.
public var height: Int?
}
/// The element's attributes.
public var attributes: Attributes?
/// Key-Value pairs with aditional parameters for the embeded Media.
public var mediaParams: [MediaParam]?
}
// MARK: - Initializers
extension MediaEmbed {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = MediaEmbed.Attributes(attributes: attributeDict)
}
}
extension MediaEmbed.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.url = attributeDict["url"]
self.width = Int(attributeDict["width"] ?? "")
self.height = Int(attributeDict["height"] ?? "")
}
}
// MARK: - Equatable
extension MediaEmbed: Equatable {
public static func ==(lhs: MediaEmbed, rhs: MediaEmbed) -> Bool {
return
lhs.mediaParams == rhs.mediaParams &&
lhs.attributes == rhs.attributes
}
}
extension MediaEmbed.Attributes: Equatable {
public static func ==(lhs: MediaEmbed.Attributes, rhs: MediaEmbed.Attributes) -> Bool {
return
lhs.url == rhs.url &&
lhs.width == rhs.width &&
lhs.height == rhs.height
}
}
| gpl-3.0 | f70cb9ac25bbabf17591f7b2749bbf68 | 28.788462 | 91 | 0.648806 | 4.569322 | false | false | false | false |
codestergit/swift | test/IDE/range_info_basics.swift | 4 | 20540 | func foo() -> Int{
var aaa = 1 + 2
aaa = aaa + 3
if aaa == 3 { aaa = 4 }
return aaa
}
func foo1() -> Int { return 0 }
class C { func foo() {} }
struct S { func foo() {} }
func foo2() {
let a = 3
var b = a.bigEndian
let c = a.byteSwapped
b = b.bigEndian.bigEndian.byteSwapped
print(b + c)
}
struct S1 {
var a = 3
func foo() -> Int { return 0 }
mutating func increment() -> S1 {
a = a + 1
return self
}
}
func foo3(s: inout S1) -> Int {
let b = s.a
let c = s.foo() + b
s = s.increment()
return c + b
}
func foo4(s: S1) -> Int {
let b = s.a
let c = s.foo() + b
return c + b
}
class C1 {
func getC() -> C1 { return self }
func take(another : C1) -> C1 {return another }
let c = C1()
}
func foo5(c : C1) -> C1 {
let a = c.c.getC().c.getC().getC().getC()
let b = a.c.c.c.c.getC().getC()
let d = a.c.getC().getC().c.c
return a.take(another: b).take(another: d)
}
func foo6() -> Int {
let a = { () -> Int in
let a = 3
var b = a.bigEndian
let c = a.byteSwapped
b = b.bigEndian.bigEndian.byteSwapped
print(b + c)
return { () -> Int in
let a = 3
var b = a.bigEndian
let c = a.byteSwapped
b = b.bigEndian.bigEndian.byteSwapped
print(b + c)
return 1
}()
}()
return a
}
func foo7(a : Int) -> Int {
switch a {
case 1:
return 0
case 2:
return 1
default:
return a
}
}
func foo8(a : [Int]) {
for v in a {
if v > 3 {
break
}
if v < 3 {
continue
}
}
var i : Int
i = 0
repeat {
print(i)
i = i + 1
if i < 10 {
continue
}
if i > 80 {
break
}
} while i < 100
}
func foo9(_ a: Int, _ b: Int) -> Int {
if a == b {
return 0
}
switch a {
case 1:
foo9(1, 2)
foo9(1, 2)
return foo9(2, 4)
default:
foo9(1, 2)
foo9(1, 2)
return foo9(2, 4)
}
return 0
}
func testInout(_ a : inout Int) {
var b = a + 1 + 1
b = b + 1
testInout(&b)
}
func test_no_pattern_binding(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
// RUN: %target-swift-ide-test -range -pos=8:1 -end-pos 8:32 -source-filename %s | %FileCheck %s -check-prefix=CHECK1
// RUN: %target-swift-ide-test -range -pos=9:1 -end-pos 9:26 -source-filename %s | %FileCheck %s -check-prefix=CHECK2
// RUN: %target-swift-ide-test -range -pos=10:1 -end-pos 10:27 -source-filename %s | %FileCheck %s -check-prefix=CHECK3
// RUN: %target-swift-ide-test -range -pos=3:1 -end-pos=4:26 -source-filename %s | %FileCheck %s -check-prefix=CHECK4
// RUN: %target-swift-ide-test -range -pos=3:1 -end-pos=5:13 -source-filename %s | %FileCheck %s -check-prefix=CHECK5
// RUN: %target-swift-ide-test -range -pos=4:1 -end-pos=5:13 -source-filename %s | %FileCheck %s -check-prefix=CHECK6
// RUN: %target-swift-ide-test -range -pos=14:1 -end-pos=17:15 -source-filename %s | %FileCheck %s -check-prefix=CHECK7
// RUN: %target-swift-ide-test -range -pos=31:1 -end-pos=33:15 -source-filename %s | %FileCheck %s -check-prefix=CHECK8
// RUN: %target-swift-ide-test -range -pos=37:1 -end-pos=39:15 -source-filename %s | %FileCheck %s -check-prefix=CHECK9
// RUN: %target-swift-ide-test -range -pos=49:1 -end-pos=50:34 -source-filename %s | %FileCheck %s -check-prefix=CHECK10
// RUN: %target-swift-ide-test -range -pos=49:1 -end-pos=51:32 -source-filename %s | %FileCheck %s -check-prefix=CHECK11
// RUN: %target-swift-ide-test -range -pos=49:1 -end-pos=52:45 -source-filename %s | %FileCheck %s -check-prefix=CHECK12
// RUN: %target-swift-ide-test -range -pos=57:1 -end-pos=61:17 -source-filename %s | %FileCheck %s -check-prefix=CHECK13
// RUN: %target-swift-ide-test -range -pos=57:1 -end-pos=69:8 -source-filename %s | %FileCheck %s -check-prefix=CHECK14
// RUN: %target-swift-ide-test -range -pos=63:1 -end-pos=66:44 -source-filename %s | %FileCheck %s -check-prefix=CHECK15
// RUN: %target-swift-ide-test -range -pos=63:1 -end-pos=68:15 -source-filename %s | %FileCheck %s -check-prefix=CHECK16
// RUN: %target-swift-ide-test -range -pos=67:1 -end-pos=67:19 -source-filename %s | %FileCheck %s -check-prefix=CHECK17
// RUN: %target-swift-ide-test -range -pos=76:1 -end-pos=79:13 -source-filename %s | %FileCheck %s -check-prefix=CHECK18
// RUN: %target-swift-ide-test -range -pos=76:1 -end-pos=77:13 -source-filename %s | %FileCheck %s -check-prefix=CHECK19
// RUN: %target-swift-ide-test -range -pos=78:1 -end-pos=81:13 -source-filename %s | %FileCheck %s -check-prefix=CHECK20
// RUN: %target-swift-ide-test -range -pos=87:1 -end-pos=89:6 -source-filename %s | %FileCheck %s -check-prefix=CHECK21
// RUN: %target-swift-ide-test -range -pos=90:1 -end-pos=92:6 -source-filename %s | %FileCheck %s -check-prefix=CHECK22
// RUN: %target-swift-ide-test -range -pos=99:1 -end-pos=101:6 -source-filename %s | %FileCheck %s -check-prefix=CHECK23
// RUN: %target-swift-ide-test -range -pos=102:1 -end-pos=104:6 -source-filename %s | %FileCheck %s -check-prefix=CHECK24
// RUN: %target-swift-ide-test -range -pos=87:1 -end-pos=92:6 -source-filename %s | %FileCheck %s -check-prefix=CHECK25
// RUN: %target-swift-ide-test -range -pos=97:1 -end-pos=104:6 -source-filename %s | %FileCheck %s -check-prefix=CHECK26
// RUN: %target-swift-ide-test -range -pos=109:6 -end-pos=111:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-INVALID
// RUN: %target-swift-ide-test -range -pos=114:1 -end-pos=115:15 -source-filename %s | %FileCheck %s -check-prefix=CHECK27
// RUN: %target-swift-ide-test -range -pos=118:1 -end-pos=119:15 -source-filename %s | %FileCheck %s -check-prefix=CHECK27
// RUN: %target-swift-ide-test -range -pos=126:11 -end-pos=126:12 -source-filename %s | %FileCheck %s -check-prefix=CHECK-INT
// RUN: %target-swift-ide-test -range -pos=126:11 -end-pos=126:20 -source-filename %s | %FileCheck %s -check-prefix=CHECK-INT
// RUN: %target-swift-ide-test -range -pos=127:7 -end-pos=127:8 -source-filename %s | %FileCheck %s -check-prefix=CHECK-INT
// RUN: %target-swift-ide-test -range -pos=127:3 -end-pos=127:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-INT-LVALUE
// RUN: %target-swift-ide-test -range -pos=128:13 -end-pos=128:15 -source-filename %s | %FileCheck %s -check-prefix=CHECK-INT-INOUT
// RUN: %target-swift-ide-test -range -pos=118:1 -end-pos=120:22 -source-filename %s | %FileCheck %s -check-prefix=CHECK-INT
// RUN: %target-swift-ide-test -range -pos=133:1 -end-pos=135:65 -source-filename %s | %FileCheck %s -check-prefix=CHECK-NO-PATTERN
// CHECK-NO-PATTERN: <Kind>MultiStatement</Kind>
// CHECK-NO-PATTERN-NEXT: <Content>for key in parameters.keys.sorted(by: <) {
// CHECK-NO-PATTERN-NEXT: }
// CHECK-NO-PATTERN-NEXT: return components.map { "\($0)=\($1)" }.joined(separator: "&")</Content>
// CHECK-NO-PATTERN-NEXT: <Type>String</Type>
// CHECK-NO-PATTERN-NEXT: <Context>swift_ide_test.(file).test_no_pattern_binding(_:)</Context>
// CHECK-NO-PATTERN-NEXT: <Declared>key</Declared><OutscopeReference>false</OutscopeReference>
// CHECK-NO-PATTERN-NEXT: <Referenced>parameters</Referenced><Type>[String : Any]</Type>
// CHECK-NO-PATTERN-NEXT: <Referenced>components</Referenced><Type>[(String, String)]</Type>
// CHECK-NO-PATTERN-NEXT: <Referenced>$0</Referenced><Type>String</Type>
// CHECK-NO-PATTERN-NEXT: <Referenced>$1</Referenced><Type>String</Type>
// CHECK-NO-PATTERN-NEXT: <ASTNodes>2</ASTNodes>
// CHECK-NO-PATTERN-NEXT: <end>
// CHECK-INVALID: <Kind>Invalid</Kind>
// CHECK-INT: <Type>Int</Type>
// CHECK-INT-LVALUE: <Type>@lvalue Int</Type>
// CHECK-INT-INOUT: <Type>inout Int</Type>
// CHECK1: <Kind>SingleDecl</Kind>
// CHECK1-NEXT: <Content>func foo1() -> Int { return 0 }</Content>
// CHECK1-NEXT: <Context>swift_ide_test.(file)</Context>
// CHECK1-NEXT: <Declared>foo1</Declared><OutscopeReference>false</OutscopeReference>
// CHECK1-NEXT: <ASTNodes>1</ASTNodes>
// CHECK1-NEXT: <end>
// CHECK2: <Kind>SingleDecl</Kind>
// CHECK2-NEXT: <Content>class C { func foo() {} }</Content>
// CHECK2-NEXT: <Context>swift_ide_test.(file)</Context>
// CHECK2-NEXT: <Declared>C</Declared><OutscopeReference>false</OutscopeReference>
// CHECK2-NEXT: <Declared>foo</Declared><OutscopeReference>false</OutscopeReference>
// CHECK2-NEXT: <ASTNodes>1</ASTNodes>
// CHECK2-NEXT: <end>
// CHECK3: <Kind>SingleDecl</Kind>
// CHECK3-NEXT: <Content>struct S { func foo() {} }</Content>
// CHECK3-NEXT: <Context>swift_ide_test.(file)</Context>
// CHECK3-NEXT: <Declared>S</Declared><OutscopeReference>false</OutscopeReference>
// CHECK3-NEXT: <Declared>foo</Declared><OutscopeReference>false</OutscopeReference>
// CHECK3-NEXT: <ASTNodes>1</ASTNodes>
// CHECK3-NEXT: <end>
// CHECK4: <Kind>MultiStatement</Kind>
// CHECK4-NEXT: <Content>aaa = aaa + 3
// CHECK4-NEXT: if aaa == 3 { aaa = 4 }</Content>
// CHECK4-NEXT: <Type>Void</Type>
// CHECK4-NEXT: <Context>swift_ide_test.(file).foo()</Context>
// CHECK4-NEXT: <Referenced>aaa</Referenced><Type>@lvalue Int</Type>
// CHECK4-NEXT: <ASTNodes>2</ASTNodes>
// CHECK4-NEXT: <end>
// CHECK5: <Kind>MultiStatement</Kind>
// CHECK5-NEXT: <Content>aaa = aaa + 3
// CHECK5-NEXT: if aaa == 3 { aaa = 4 }
// CHECK5-NEXT: return aaa</Content>
// CHECK5-NEXT: <Type>Int</Type>
// CHECK5-NEXT: <Context>swift_ide_test.(file).foo()</Context>
// CHECK5-NEXT: <Referenced>aaa</Referenced><Type>@lvalue Int</Type>
// CHECK5-NEXT: <ASTNodes>3</ASTNodes>
// CHECK5-NEXT: <end>
// CHECK6: <Kind>MultiStatement</Kind>
// CHECK6-NEXT: if aaa == 3 { aaa = 4 }
// CHECK6-NEXT: return aaa</Content>
// CHECK6-NEXT: <Type>Int</Type>
// CHECK6-NEXT: <Context>swift_ide_test.(file).foo()</Context>
// CHECK6-NEXT: <Referenced>aaa</Referenced><Type>@lvalue Int</Type>
// CHECK6-NEXT: <ASTNodes>2</ASTNodes>
// CHECK6-NEXT: <end>
// CHECK7: <Kind>MultiStatement</Kind>
// CHECK7-NEXT: <Content>var b = a.bigEndian
// CHECK7-NEXT: let c = a.byteSwapped
// CHECK7-NEXT: b = b.bigEndian.bigEndian.byteSwapped
// CHECK7-NEXT: print(b + c)</Content>
// CHECK7-NEXT: <Type>Void</Type>
// CHECK7-NEXT: <Context>swift_ide_test.(file).foo2()</Context>
// CHECK7-NEXT: <Declared>b</Declared><OutscopeReference>false</OutscopeReference>
// CHECK7-NEXT: <Declared>c</Declared><OutscopeReference>false</OutscopeReference>
// CHECK7-NEXT: <Referenced>a</Referenced><Type>Int</Type>
// CHECK7-NEXT: <Referenced>b</Referenced><Type>@lvalue Int</Type>
// CHECK7-NEXT: <Referenced>c</Referenced><Type>Int</Type>
// CHECK7-NEXT: <ASTNodes>4</ASTNodes>
// CHECK7-NEXT: <end>
// CHECK8: <Kind>MultiStatement</Kind>
// CHECK8-NEXT: <Content>let c = s.foo() + b
// CHECK8-NEXT: s = s.increment()
// CHECK8-NEXT: return c + b</Content>
// CHECK8-NEXT: <Type>Int</Type>
// CHECK8-NEXT: <Context>swift_ide_test.(file).foo3(s:)</Context>
// CHECK8-NEXT: <Declared>c</Declared><OutscopeReference>false</OutscopeReference>
// CHECK8-NEXT: <Referenced>s</Referenced><Type>@lvalue S1</Type>
// CHECK8-NEXT: <Referenced>b</Referenced><Type>Int</Type>
// CHECK8-NEXT: <Referenced>c</Referenced><Type>Int</Type>
// CHECK8-NEXT: <ASTNodes>3</ASTNodes>
// CHECK8-NEXT: <end>
// CHECK9: <Kind>MultiStatement</Kind>
// CHECK9-NEXT: <Content>let b = s.a
// CHECK9-NEXT: let c = s.foo() + b
// CHECK9-NEXT: return c + b</Content>
// CHECK9-NEXT: <Type>Int</Type>
// CHECK9-NEXT: <Context>swift_ide_test.(file).foo4(s:)</Context>
// CHECK9-NEXT: <Declared>b</Declared><OutscopeReference>false</OutscopeReference>
// CHECK9-NEXT: <Declared>c</Declared><OutscopeReference>false</OutscopeReference>
// CHECK9-NEXT: <Referenced>s</Referenced><Type>S1</Type>
// CHECK9-NEXT: <Referenced>b</Referenced><Type>Int</Type>
// CHECK9-NEXT: <Referenced>c</Referenced><Type>Int</Type>
// CHECK9-NEXT: <ASTNodes>3</ASTNodes>
// CHECK9-NEXT: <end>
// CHECK10: <Kind>MultiStatement</Kind>
// CHECK10-NEXT: <Content>let a = c.c.getC().c.getC().getC().getC()
// CHECK10-NEXT: let b = a.c.c.c.c.getC().getC()</Content>
// CHECK10-NEXT: <Type>Void</Type>
// CHECK10-NEXT: <Context>swift_ide_test.(file).foo5(c:)</Context>
// CHECK10-NEXT: <Declared>a</Declared><OutscopeReference>true</OutscopeReference>
// CHECK10-NEXT: <Declared>b</Declared><OutscopeReference>true</OutscopeReference>
// CHECK10-NEXT: <Referenced>c</Referenced><Type>C1</Type>
// CHECK10-NEXT: <Referenced>a</Referenced><Type>C1</Type>
// CHECK10-NEXT: <ASTNodes>2</ASTNodes>
// CHECK10-NEXT: <end>
// CHECK11: <Kind>MultiStatement</Kind>
// CHECK11-NEXT: <Content>let a = c.c.getC().c.getC().getC().getC()
// CHECK11-NEXT: let b = a.c.c.c.c.getC().getC()
// CHECK11-NEXT: let d = a.c.getC().getC().c.c</Content>
// CHECK11-NEXT: <Type>Void</Type>
// CHECK11-NEXT: <Context>swift_ide_test.(file).foo5(c:)</Context>
// CHECK11-NEXT: <Declared>a</Declared><OutscopeReference>true</OutscopeReference>
// CHECK11-NEXT: <Declared>b</Declared><OutscopeReference>true</OutscopeReference>
// CHECK11-NEXT: <Declared>d</Declared><OutscopeReference>true</OutscopeReference>
// CHECK11-NEXT: <Referenced>c</Referenced><Type>C1</Type>
// CHECK11-NEXT: <Referenced>a</Referenced><Type>C1</Type>
// CHECK11-NEXT: <ASTNodes>3</ASTNodes>
// CHECK11-NEXT: <end>
// CHECK12: <Kind>MultiStatement</Kind>
// CHECK12-NEXT: <Content>let a = c.c.getC().c.getC().getC().getC()
// CHECK12-NEXT: let b = a.c.c.c.c.getC().getC()
// CHECK12-NEXT: let d = a.c.getC().getC().c.c
// CHECK12-NEXT: return a.take(another: b).take(another: d)</Content>
// CHECK12-NEXT: <Type>C1</Type>
// CHECK12-NEXT: <Context>swift_ide_test.(file).foo5(c:)</Context>
// CHECK12-NEXT: <Declared>a</Declared><OutscopeReference>false</OutscopeReference>
// CHECK12-NEXT: <Declared>b</Declared><OutscopeReference>false</OutscopeReference>
// CHECK12-NEXT: <Declared>d</Declared><OutscopeReference>false</OutscopeReference>
// CHECK12-NEXT: <Referenced>c</Referenced><Type>C1</Type>
// CHECK12-NEXT: <Referenced>a</Referenced><Type>C1</Type>
// CHECK12-NEXT: <Referenced>b</Referenced><Type>C1</Type>
// CHECK12-NEXT: <Referenced>d</Referenced><Type>C1</Type>
// CHECK12-NEXT: <ASTNodes>4</ASTNodes>
// CHECK12-NEXT: <end>
// CHECK13: <Kind>MultiStatement</Kind>
// CHECK13-NEXT: <Content>let a = 3
// CHECK13-NEXT: var b = a.bigEndian
// CHECK13-NEXT: let c = a.byteSwapped
// CHECK13-NEXT: b = b.bigEndian.bigEndian.byteSwapped
// CHECK13-NEXT: print(b + c)</Content>
// CHECK13-NEXT: <Type>Void</Type>
// CHECK13-NEXT: <Context>swift_ide_test.(file).foo6().explicit closure discriminator=0</Context>
// CHECK13-NEXT: <Declared>a</Declared><OutscopeReference>false</OutscopeReference>
// CHECK13-NEXT: <Declared>b</Declared><OutscopeReference>false</OutscopeReference>
// CHECK13-NEXT: <Declared>c</Declared><OutscopeReference>false</OutscopeReference>
// CHECK13-NEXT: <Referenced>a</Referenced><Type>Int</Type>
// CHECK13-NEXT: <Referenced>b</Referenced><Type>@lvalue Int</Type>
// CHECK13-NEXT: <Referenced>c</Referenced><Type>Int</Type>
// CHECK13-NEXT: <ASTNodes>5</ASTNodes>
// CHECK13-NEXT: <end>
// CHECK14: <Kind>MultiStatement</Kind>
// CHECK14-NEXT: <Content>let a = 3
// CHECK14-NEXT: var b = a.bigEndian
// CHECK14-NEXT: let c = a.byteSwapped
// CHECK14-NEXT: b = b.bigEndian.bigEndian.byteSwapped
// CHECK14-NEXT: print(b + c)
// CHECK14-NEXT: return { () -> Int in
// CHECK14-NEXT: let a = 3
// CHECK14-NEXT: var b = a.bigEndian
// CHECK14-NEXT: let c = a.byteSwapped
// CHECK14-NEXT: b = b.bigEndian.bigEndian.byteSwapped
// CHECK14-NEXT: print(b + c)
// CHECK14-NEXT: return 1
// CHECK14-NEXT: }()</Content>
// CHECK14-NEXT: <Type>Int</Type>
// CHECK14-NEXT: <Context>swift_ide_test.(file).foo6().explicit closure discriminator=0</Context>
// CHECK14-NEXT: <Declared>a</Declared><OutscopeReference>false</OutscopeReference>
// CHECK14-NEXT: <Declared>b</Declared><OutscopeReference>false</OutscopeReference>
// CHECK14-NEXT: <Declared>c</Declared><OutscopeReference>false</OutscopeReference>
// CHECK14-NEXT: <Declared>a</Declared><OutscopeReference>false</OutscopeReference>
// CHECK14-NEXT: <Declared>b</Declared><OutscopeReference>false</OutscopeReference>
// CHECK14-NEXT: <Declared>c</Declared><OutscopeReference>false</OutscopeReference>
// CHECK14-NEXT: <Referenced>a</Referenced><Type>Int</Type>
// CHECK14-NEXT: <Referenced>b</Referenced><Type>@lvalue Int</Type>
// CHECK14-NEXT: <Referenced>c</Referenced><Type>Int</Type>
// CHECK14-NEXT: <Referenced>a</Referenced><Type>Int</Type>
// CHECK14-NEXT: <Referenced>b</Referenced><Type>@lvalue Int</Type>
// CHECK14-NEXT: <Referenced>c</Referenced><Type>Int</Type>
// CHECK14-NEXT: <ASTNodes>6</ASTNodes>
// CHECK14-NEXT: <end>
// CHECK15: <Kind>MultiStatement</Kind>
// CHECK15-NEXT: <Content>let a = 3
// CHECK15-NEXT: var b = a.bigEndian
// CHECK15-NEXT: let c = a.byteSwapped
// CHECK15-NEXT: b = b.bigEndian.bigEndian.byteSwapped</Content>
// CHECK15-NEXT: <Type>Void</Type>
// CHECK15-NEXT: <Context>swift_ide_test.(file).foo6().explicit closure discriminator=0.explicit closure discriminator=0</Context>
// CHECK15-NEXT: <Declared>a</Declared><OutscopeReference>false</OutscopeReference>
// CHECK15-NEXT: <Declared>b</Declared><OutscopeReference>true</OutscopeReference>
// CHECK15-NEXT: <Declared>c</Declared><OutscopeReference>true</OutscopeReference>
// CHECK15-NEXT: <Referenced>a</Referenced><Type>Int</Type>
// CHECK15-NEXT: <Referenced>b</Referenced><Type>@lvalue Int</Type>
// CHECK15-NEXT: <ASTNodes>4</ASTNodes>
// CHECK15-NEXT: <end>
// CHECK16: <Kind>MultiStatement</Kind>
// CHECK16-NEXT: <Content>let a = 3
// CHECK16-NEXT: var b = a.bigEndian
// CHECK16-NEXT: let c = a.byteSwapped
// CHECK16-NEXT: b = b.bigEndian.bigEndian.byteSwapped
// CHECK16-NEXT: print(b + c)
// CHECK16-NEXT: return 1</Content>
// CHECK16-NEXT: <Type>Int</Type>
// CHECK16-NEXT: <Context>swift_ide_test.(file).foo6().explicit closure discriminator=0.explicit closure discriminator=0</Context>
// CHECK16-NEXT: <Declared>a</Declared><OutscopeReference>false</OutscopeReference>
// CHECK16-NEXT: <Declared>b</Declared><OutscopeReference>false</OutscopeReference>
// CHECK16-NEXT: <Declared>c</Declared><OutscopeReference>false</OutscopeReference>
// CHECK16-NEXT: <Referenced>a</Referenced><Type>Int</Type>
// CHECK16-NEXT: <Referenced>b</Referenced><Type>@lvalue Int</Type>
// CHECK16-NEXT: <Referenced>c</Referenced><Type>Int</Type>
// CHECK16-NEXT: <ASTNodes>6</ASTNodes>
// CHECK16-NEXT: <end>
// CHECK17: <Kind>SingleExpression</Kind>
// CHECK17-NEXT: <Content>print(b + c)</Content>
// CHECK17-NEXT: <Type>()</Type>
// CHECK17-NEXT: <Context>swift_ide_test.(file).foo6().explicit closure discriminator=0.explicit closure discriminator=0</Context>
// CHECK17-NEXT: <Referenced>b</Referenced><Type>Int</Type>
// CHECK17-NEXT: <Referenced>c</Referenced><Type>Int</Type>
// CHECK17-NEXT: <ASTNodes>1</ASTNodes>
// CHECK17-NEXT: <end>
// CHECK18: <Kind>MultiStatement</Kind>
// CHECK18-NEXT: <Content>case 1:
// CHECK18-NEXT: return 0
// CHECK18-NEXT: case 2:
// CHECK18-NEXT: return 1</Content>
// CHECK18-NEXT: <Type>Void</Type>
// CHECK18-NEXT: <Context>swift_ide_test.(file).foo7(a:)</Context>
// CHECK18-NEXT: <Entry>Multi</Entry>
// CHECK18-NEXT: <ASTNodes>2</ASTNodes>
// CHECK18-NEXT: <end>
// CHECK19: <Kind>SingleStatement</Kind>
// CHECK19-NEXT: <Content>case 1:
// CHECK19-NEXT: return 0</Content>
// CHECK19-NEXT: <Type>Void</Type>
// CHECK19-NEXT: <Context>swift_ide_test.(file).foo7(a:)</Context>
// CHECK19-NEXT: <ASTNodes>1</ASTNodes>
// CHECK19-NEXT: <end>
// CHECK20: <Kind>MultiStatement</Kind>
// CHECK20-NEXT: <Content>case 2:
// CHECK20-NEXT: return 1
// CHECK20-NEXT: default:
// CHECK20-NEXT: return a</Content>
// CHECK20-NEXT: <Type>Void</Type>
// CHECK20-NEXT: <Context>swift_ide_test.(file).foo7(a:)</Context>
// CHECK20-NEXT: <Entry>Multi</Entry>
// CHECK20-NEXT: <ASTNodes>2</ASTNodes>
// CHECK20-NEXT: <end>
// CHECK21: <Orphan>Break</Orphan>
// CHECK22: <Orphan>Continue</Orphan>
// CHECK23: <Orphan>Continue</Orphan>
// CHECK24: <Orphan>Break</Orphan>
// CHECK25: <Orphan>Break</Orphan>
// CHECK26: <Orphan>Continue</Orphan>
// CHECK27: <Kind>MultiStatement</Kind>
// CHECK27-NEXT: <Content>foo9(1, 2)
// CHECK27-NEXT: foo9(1, 2)</Content>
// CHECK27-NEXT: <Type>Void</Type>
// CHECK27-NEXT: <Context>swift_ide_test.(file).foo9(_:_:)</Context>
// CHECK27-NEXT: <Referenced>foo9</Referenced><Type>(Int, Int) -> Int</Type>
// CHECK27-NEXT: <ASTNodes>2</ASTNodes>
// CHECK27-NEXT: <end>
| apache-2.0 | cf722d202f1e4c5da0b47b5d30b6b5a4 | 43.172043 | 131 | 0.678189 | 2.855951 | false | true | false | false |
ZwxWhite/V2EX | V2EX/Pods/PagingMenuController/Pod/Classes/PagingMenuController.swift | 1 | 20531 | //
// PagingMenuController.swift
// PagingMenuController
//
// Created by Yusuke Kita on 3/18/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import UIKit
@objc public protocol PagingMenuControllerDelegate: class {
optional func willMoveToMenuPage(page: Int)
optional func didMoveToMenuPage(page: Int)
}
public class PagingMenuController: UIViewController, UIScrollViewDelegate {
public weak var delegate: PagingMenuControllerDelegate?
private var options: PagingMenuOptions!
public private(set) var menuView: MenuView!
public private(set) var currentPage: Int = 0
public private(set) var currentViewController: UIViewController!
public private(set) var visiblePagingViewControllers = [UIViewController]()
public private(set) var pagingViewControllers = [UIViewController]() {
willSet {
options.menuItemCount = newValue.count
}
}
private var contentScrollView: UIScrollView!
private var contentView: UIView!
private var menuItemTitles: [String] {
get {
return pagingViewControllers.map {
return $0.title ?? "Menu"
}
}
}
private enum PagingViewPosition {
case Left
case Center
case Right
case Unknown
init(order: Int) {
switch order {
case 0: self = .Left
case 1: self = .Center
case 2: self = .Right
default: self = .Unknown
}
}
}
private var currentPosition: PagingViewPosition = .Left
private let visiblePagingViewNumber: Int = 3
private var previousIndex: Int {
guard case .Infinite = options.menuDisplayMode else { return currentPage - 1 }
return currentPage - 1 < 0 ? options.menuItemCount - 1 : currentPage - 1
}
private var nextIndex: Int {
guard case .Infinite = options.menuDisplayMode else { return currentPage + 1 }
return currentPage + 1 > options.menuItemCount - 1 ? 0 : currentPage + 1
}
private let ExceptionName = "PMCException"
// MARK: - Lifecycle
public init(viewControllers: [UIViewController], options: PagingMenuOptions) {
super.init(nibName: nil, bundle: nil)
setup(viewControllers: viewControllers, options: options)
}
convenience public init(viewControllers: [UIViewController]) {
self.init(viewControllers: viewControllers, options: PagingMenuOptions())
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// position properly for Infinite mode
menuView.moveToMenu(page: currentPage, animated: false)
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// fix unnecessary inset for menu view when implemented by programmatically
menuView.contentInset.top = 0
// position paging views correctly after view size is decided
if let currentViewController = currentViewController {
contentScrollView.contentOffset.x = currentViewController.view!.frame.minX
}
}
override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
menuView.updateMenuViewConstraints(size: size)
coordinator.animateAlongsideTransition({ [unowned self] (_) -> Void in
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
// reset selected menu item view position
switch self.options.menuDisplayMode {
case .Standard, .Infinite:
self.menuView.moveToMenu(page: self.currentPage, animated: true)
default: break
}
}, completion: nil)
}
public func setup(viewControllers viewControllers: [UIViewController], options: PagingMenuOptions) {
self.options = options
pagingViewControllers = viewControllers
visiblePagingViewControllers.reserveCapacity(visiblePagingViewNumber)
// validate
validateDefaultPage()
validatePageNumbers()
// cleanup
cleanup()
currentPage = options.defaultPage
constructMenuView()
constructContentScrollView()
layoutMenuView()
layoutContentScrollView()
constructContentView()
layoutContentView()
constructPagingViewControllers()
layoutPagingViewControllers()
currentPosition = currentPagingViewPosition()
currentViewController = pagingViewControllers[currentPage]
moveToMenuPage(currentPage, animated: false)
}
public func rebuild(viewControllers: [UIViewController], options: PagingMenuOptions) {
// cleanup properties to avoid memory leaks. This could also be placed inside the cleanup method, or in within didSet{} of the pagingViewController
visiblePagingViewControllers.removeAll()
currentViewController = nil
for childViewController in childViewControllers {
childViewController.view.removeFromSuperview()
childViewController.removeFromParentViewController()
}
// perform setup
setup(viewControllers: viewControllers, options: options)
view.setNeedsLayout()
view.layoutIfNeeded()
}
// MARK: - UISCrollViewDelegate
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
guard scrollView.isEqual(contentScrollView) else { return }
let position = currentPagingViewPosition()
// set new page number according to current moving direction
switch position {
case .Left: currentPage = previousIndex
case .Right: currentPage = nextIndex
default: return
}
delegate?.willMoveToMenuPage?(currentPage)
menuView.moveToMenu(page: currentPage, animated: true)
currentViewController = pagingViewControllers[currentPage]
contentScrollView.contentOffset.x = currentViewController.view!.frame.minX
constructPagingViewControllers()
layoutPagingViewControllers()
view.setNeedsLayout()
view.layoutIfNeeded()
currentPosition = currentPagingViewPosition()
delegate?.didMoveToMenuPage?(currentPage)
}
// MARK: - UIGestureRecognizer
internal func handleTapGesture(recognizer: UITapGestureRecognizer) {
let tappedMenuView = recognizer.view as! MenuItemView
guard let tappedPage = menuView.menuItemViews.indexOf(tappedMenuView) where tappedPage != currentPage else { return }
let page = targetPage(tappedPage: tappedPage)
moveToMenuPage(page, animated: true)
}
internal func handleSwipeGesture(recognizer: UISwipeGestureRecognizer) {
var newPage = currentPage
if recognizer.direction == .Left {
newPage = min(nextIndex, menuView.menuItemViews.count - 1)
} else if recognizer.direction == .Right {
newPage = max(previousIndex, 0)
} else {
return
}
moveToMenuPage(newPage, animated: true)
}
// MARK: - Constructor
private func constructMenuView() {
menuView = MenuView(menuItemTitles: menuItemTitles, options: options)
menuView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(menuView)
addTapGestureHandlers()
addSwipeGestureHandlersIfNeeded()
}
private func layoutMenuView() {
let viewsDictionary = ["menuView": menuView]
let metrics = ["height": options.menuHeight]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuView]|", options: [], metrics: nil, views: viewsDictionary)
let verticalConstraints: [NSLayoutConstraint]
switch options.menuPosition {
case .Top:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[menuView(height)]", options: [], metrics: metrics, views: viewsDictionary)
case .Bottom:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView(height)]|", options: [], metrics: metrics, views: viewsDictionary)
}
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
menuView.setNeedsLayout()
menuView.layoutIfNeeded()
}
private func constructContentScrollView() {
contentScrollView = UIScrollView(frame: CGRectZero)
contentScrollView.delegate = self
contentScrollView.pagingEnabled = true
contentScrollView.showsHorizontalScrollIndicator = false
contentScrollView.showsVerticalScrollIndicator = false
contentScrollView.scrollsToTop = false
contentScrollView.bounces = false
contentScrollView.scrollEnabled = options.scrollEnabled
contentScrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(contentScrollView)
}
private func layoutContentScrollView() {
let viewsDictionary = ["contentScrollView": contentScrollView, "menuView": menuView]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentScrollView]|", options: [], metrics: nil, views: viewsDictionary)
let verticalConstraints: [NSLayoutConstraint]
switch options.menuPosition {
case .Top:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView][contentScrollView]|", options: [], metrics: nil, views: viewsDictionary)
case .Bottom:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentScrollView][menuView]", options: [], metrics: nil, views: viewsDictionary)
}
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
}
private func constructContentView() {
contentView = UIView(frame: CGRectZero)
contentView.translatesAutoresizingMaskIntoConstraints = false
contentScrollView.addSubview(contentView)
}
private func layoutContentView() {
let viewsDictionary = ["contentView": contentView, "contentScrollView": contentScrollView]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]|", options: [], metrics: nil, views: viewsDictionary)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView(==contentScrollView)]|", options: [], metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
}
private func constructPagingViewControllers() {
for (index, pagingViewController) in pagingViewControllers.enumerate() {
// construct three child view controllers at a maximum, previous(optional), current and next(optional)
if !shouldLoadPage(index) {
// remove unnecessary child view controllers
if isVisiblePagingViewController(pagingViewController) {
pagingViewController.willMoveToParentViewController(nil)
pagingViewController.view!.removeFromSuperview()
pagingViewController.removeFromParentViewController()
if let viewIndex = visiblePagingViewControllers.indexOf(pagingViewController) {
visiblePagingViewControllers.removeAtIndex(viewIndex)
}
}
continue
}
// ignore if it's already added
if isVisiblePagingViewController(pagingViewController) {
continue
}
pagingViewController.view!.frame = CGRectZero
pagingViewController.view!.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(pagingViewController.view!)
addChildViewController(pagingViewController as UIViewController)
pagingViewController.didMoveToParentViewController(self)
visiblePagingViewControllers.append(pagingViewController)
}
}
private func layoutPagingViewControllers() {
// cleanup
NSLayoutConstraint.deactivateConstraints(contentView.constraints)
var viewsDictionary: [String: AnyObject] = ["contentScrollView": contentScrollView]
for (index, pagingViewController) in pagingViewControllers.enumerate() {
if !shouldLoadPage(index) {
continue
}
viewsDictionary["pagingView"] = pagingViewController.view!
var horizontalVisualFormat = String()
// only one view controller
if (options.menuItemCount == options.minumumSupportedViewCount) {
horizontalVisualFormat = "H:|[pagingView(==contentScrollView)]|"
} else {
if case .Infinite = options.menuDisplayMode {
if index == currentPage {
viewsDictionary["previousPagingView"] = pagingViewControllers[previousIndex].view
viewsDictionary["nextPagingView"] = pagingViewControllers[nextIndex].view
horizontalVisualFormat = "H:[previousPagingView][pagingView(==contentScrollView)][nextPagingView]"
} else if index == previousIndex {
horizontalVisualFormat = "H:|[pagingView(==contentScrollView)]"
} else if index == nextIndex {
horizontalVisualFormat = "H:[pagingView(==contentScrollView)]|"
}
} else {
if index == 0 || index == previousIndex {
horizontalVisualFormat = "H:|[pagingView(==contentScrollView)]"
} else {
viewsDictionary["previousPagingView"] = pagingViewControllers[index - 1].view
if index == pagingViewControllers.count - 1 || index == nextIndex {
horizontalVisualFormat = "H:[previousPagingView][pagingView(==contentScrollView)]|"
} else {
horizontalVisualFormat = "H:[previousPagingView][pagingView(==contentScrollView)]"
}
}
}
}
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(horizontalVisualFormat, options: [], metrics: nil, views: viewsDictionary)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[pagingView(==contentScrollView)]|", options: [], metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
}
view.setNeedsLayout()
view.layoutIfNeeded()
}
// MARK: - Cleanup
private func cleanup() {
if let menuView = self.menuView, let contentScrollView = self.contentScrollView {
menuView.removeFromSuperview()
contentScrollView.removeFromSuperview()
}
currentPage = options.defaultPage
}
// MARK: - Gesture handler
private func addTapGestureHandlers() {
menuView.menuItemViews.forEach { $0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTapGesture:")) }
}
private func addSwipeGestureHandlersIfNeeded() {
switch options.menuDisplayMode {
case .Standard(_, _, .PagingEnabled): break
case .Standard: return
case .SegmentedControl: return
case .Infinite: break
}
let leftSwipeGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipeGesture:")
leftSwipeGesture.direction = .Left
menuView.panGestureRecognizer.requireGestureRecognizerToFail(leftSwipeGesture)
menuView.addGestureRecognizer(leftSwipeGesture)
let rightSwipeGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipeGesture:")
rightSwipeGesture.direction = .Right
menuView.panGestureRecognizer.requireGestureRecognizerToFail(rightSwipeGesture)
menuView.addGestureRecognizer(rightSwipeGesture)
}
// MARK: - Page controller
private func moveToMenuPage(page: Int, animated: Bool) {
let lastPage = currentPage
currentPage = page
currentViewController = pagingViewControllers[page]
menuView.moveToMenu(page: currentPage, animated: animated)
delegate?.willMoveToMenuPage?(currentPage)
// hide paging views if it's moving to far away
hidePagingViewsIfNeeded(lastPage)
let duration = animated ? options.animationDuration : 0
UIView.animateWithDuration(duration, animations: {
[unowned self] () -> Void in
self.contentScrollView.contentOffset.x = self.currentViewController.view!.frame.minX
}) { [unowned self] (_) -> Void in
// show paging views
self.visiblePagingViewControllers.forEach { $0.view.alpha = 1 }
// reconstruct visible paging views
self.constructPagingViewControllers()
self.layoutPagingViewControllers()
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
self.currentPosition = self.currentPagingViewPosition()
self.delegate?.didMoveToMenuPage?(self.currentPage)
}
}
private func hidePagingViewsIfNeeded(lastPage: Int) {
guard lastPage != previousIndex && lastPage != nextIndex else { return }
visiblePagingViewControllers.forEach { $0.view.alpha = 0 }
}
private func shouldLoadPage(index: Int) -> Bool {
if case .Infinite = options.menuDisplayMode {
guard index == currentPage || index == previousIndex || index == nextIndex else { return false }
} else {
guard index >= previousIndex && index <= nextIndex else { return false }
}
return true
}
private func isVisiblePagingViewController(pagingViewController: UIViewController) -> Bool {
return childViewControllers.contains(pagingViewController)
}
// MARK: - Page calculator
private func currentPagingViewPosition() -> PagingViewPosition {
let pageWidth = contentScrollView.frame.width
let order = Int(ceil((contentScrollView.contentOffset.x - pageWidth / 2) / pageWidth))
if case .Infinite = options.menuDisplayMode {
return PagingViewPosition(order: order)
}
// consider left edge menu as center position
guard currentPage == 0 && contentScrollView.contentSize.width < (pageWidth * CGFloat(visiblePagingViewNumber)) else { return PagingViewPosition(order: order) }
return PagingViewPosition(order: order + 1)
}
private func targetPage(tappedPage tappedPage: Int) -> Int {
guard case let .Standard(_, _, scrollingMode) = options.menuDisplayMode else { return tappedPage }
guard case .PagingEnabled = scrollingMode else { return tappedPage }
return tappedPage < currentPage ? currentPage - 1 : currentPage + 1
}
// MARK: - Validator
private func validateDefaultPage() {
guard options.defaultPage >= options.menuItemCount || options.defaultPage < 0 else { return }
NSException(name: ExceptionName, reason: "default page is invalid", userInfo: nil).raise()
}
private func validatePageNumbers() {
guard case .Infinite = options.menuDisplayMode else { return }
guard options.menuItemCount < visiblePagingViewNumber else { return }
NSException(name: ExceptionName, reason: "the number of view controllers should be more than three with Infinite display mode", userInfo: nil).raise()
}
} | mit | 44ed6c8198a285cab495f8582757a961 | 40.731707 | 176 | 0.653451 | 6.255637 | false | false | false | false |
brentdax/swift | test/SILGen/local_recursion.swift | 2 | 5878 | // RUN: %target-swift-emit-silgen -parse-as-library -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -enable-astscope-lookup -parse-as-library -enable-sil-ownership %s | %FileCheck %s
// CHECK-LABEL: sil hidden @$s15local_recursionAA_1yySi_SitF : $@convention(thin) (Int, Int) -> () {
// CHECK: bb0([[X:%0]] : @trivial $Int, [[Y:%1]] : @trivial $Int):
func local_recursion(_ x: Int, y: Int) {
func self_recursive(_ a: Int) {
self_recursive(x + a)
}
// Invoke local functions by passing all their captures.
// CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE:@\$s15local_recursionAA_1yySi_SitF14self_recursiveL_yySiF]]
// CHECK: apply [[SELF_RECURSIVE_REF]]([[X]], [[X]])
self_recursive(x)
// CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE]]
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[SELF_RECURSIVE_REF]]([[X]])
// CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]]
// CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]]
let sr = self_recursive
// CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]]
// CHECK: apply [[B]]([[Y]])
// CHECK: end_borrow [[B]]
// CHECK: destroy_value [[CLOSURE_COPY]]
// CHECK: end_borrow [[BORROWED_CLOSURE]]
sr(y)
func mutually_recursive_1(_ a: Int) {
mutually_recursive_2(x + a)
}
func mutually_recursive_2(_ b: Int) {
mutually_recursive_1(y + b)
}
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1:@\$s15local_recursionAA_1yySi_SitF20mutually_recursive_1L_yySiF]]
// CHECK: apply [[MUTUALLY_RECURSIVE_REF]]([[X]], [[Y]], [[X]])
mutually_recursive_1(x)
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]]
_ = mutually_recursive_1
func transitive_capture_1(_ a: Int) -> Int {
return x + a
}
func transitive_capture_2(_ b: Int) -> Int {
return transitive_capture_1(y + b)
}
// CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE:@\$s15local_recursionAA_1yySi_SitF20transitive_capture_2L_yS2iF]]
// CHECK: apply [[TRANS_CAPTURE_REF]]([[X]], [[X]], [[Y]])
transitive_capture_2(x)
// CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE]]
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[TRANS_CAPTURE_REF]]([[X]], [[Y]])
// CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]]
// CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]]
let tc = transitive_capture_2
// CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]]
// CHECK: apply [[B]]([[X]])
// CHECK: end_borrow [[B]]
// CHECK: destroy_value [[CLOSURE_COPY]]
// CHECK: end_borrow [[BORROWED_CLOSURE]]
tc(x)
// CHECK: [[CLOSURE_REF:%.*]] = function_ref @$s15local_recursionAA_1yySi_SitFySiXEfU_
// CHECK: apply [[CLOSURE_REF]]([[X]], [[X]], [[Y]])
let _: Void = {
self_recursive($0)
transitive_capture_2($0)
}(x)
// CHECK: [[CLOSURE_REF:%.*]] = function_ref @$s15local_recursionAA_1yySi_SitFySicfU0_
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[CLOSURE_REF]]([[X]], [[Y]])
// CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]]
// CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]]
// CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]]
// CHECK: apply [[B]]([[X]])
// CHECK: end_borrow [[B]]
// CHECK: destroy_value [[CLOSURE_COPY]]
// CHECK: end_borrow [[BORROWED_CLOSURE]]
let f: (Int) -> () = {
self_recursive($0)
transitive_capture_2($0)
}
f(x)
}
// CHECK: sil private [[SELF_RECURSIVE]]
// CHECK: bb0([[A:%0]] : @trivial $Int, [[X:%1]] : @trivial $Int):
// CHECK: [[SELF_REF:%.*]] = function_ref [[SELF_RECURSIVE]]
// CHECK: apply [[SELF_REF]]({{.*}}, [[X]])
// CHECK: sil private [[MUTUALLY_RECURSIVE_1]]
// CHECK: bb0([[A:%0]] : @trivial $Int, [[Y:%1]] : @trivial $Int, [[X:%2]] : @trivial $Int):
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_2:@\$s15local_recursionAA_1yySi_SitF20mutually_recursive_2L_yySiF]]
// CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[X]], [[Y]])
// CHECK: sil private [[MUTUALLY_RECURSIVE_2]]
// CHECK: bb0([[B:%0]] : @trivial $Int, [[X:%1]] : @trivial $Int, [[Y:%2]] : @trivial $Int):
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]]
// CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[Y]], [[X]])
// CHECK: sil private [[TRANS_CAPTURE_1:@\$s15local_recursionAA_1yySi_SitF20transitive_capture_1L_yS2iF]]
// CHECK: bb0([[A:%0]] : @trivial $Int, [[X:%1]] : @trivial $Int):
// CHECK: sil private [[TRANS_CAPTURE]]
// CHECK: bb0([[B:%0]] : @trivial $Int, [[X:%1]] : @trivial $Int, [[Y:%2]] : @trivial $Int):
// CHECK: [[TRANS_CAPTURE_1_REF:%.*]] = function_ref [[TRANS_CAPTURE_1]]
// CHECK: apply [[TRANS_CAPTURE_1_REF]]({{.*}}, [[X]])
func plus<T>(_ x: T, _ y: T) -> T { return x }
func toggle<T, U>(_ x: T, _ y: U) -> U { return y }
func generic_local_recursion<T, U>(_ x: T, y: U) {
func self_recursive(_ a: T) {
self_recursive(plus(x, a))
}
self_recursive(x)
_ = self_recursive
func transitive_capture_1(_ a: T) -> U {
return toggle(a, y)
}
func transitive_capture_2(_ b: U) -> U {
return transitive_capture_1(toggle(b, x))
}
transitive_capture_2(y)
_ = transitive_capture_2
func no_captures() {}
no_captures()
_ = no_captures
func transitive_no_captures() {
no_captures()
}
transitive_no_captures()
_ = transitive_no_captures
}
func local_properties(_ x: Int, y: Int) -> Int {
var self_recursive: Int {
return x + self_recursive
}
var transitive_capture_1: Int {
return x
}
var transitive_capture_2: Int {
return transitive_capture_1 + y
}
func transitive_capture_fn() -> Int {
return transitive_capture_2
}
return self_recursive + transitive_capture_fn()
}
| apache-2.0 | e7f85aa620deb04207f1a70e233dcd5e | 35.283951 | 146 | 0.599694 | 3.077487 | false | false | false | false |
yeahdongcn/RSBarcodes_Swift | Source/RSCode39Generator.swift | 1 | 2747 | //
// RSCode39Generator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/10/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import Foundation
let CODE39_ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*"
// http://www.barcodesymbols.com/code39.htm
// http://www.barcodeisland.com/code39.phtml
@available(macCatalyst 14.0, *)
open class RSCode39Generator: RSAbstractCodeGenerator {
let CODE39_CHARACTER_ENCODINGS = [
"1010011011010",
"1101001010110",
"1011001010110",
"1101100101010",
"1010011010110",
"1101001101010",
"1011001101010",
"1010010110110",
"1101001011010",
"1011001011010",
"1101010010110",
"1011010010110",
"1101101001010",
"1010110010110",
"1101011001010",
"1011011001010",
"1010100110110",
"1101010011010",
"1011010011010",
"1010110011010",
"1101010100110",
"1011010100110",
"1101101010010",
"1010110100110",
"1101011010010",
"1011011010010",
"1010101100110",
"1101010110010",
"1011010110010",
"1010110110010",
"1100101010110",
"1001101010110",
"1100110101010",
"1001011010110",
"1100101101010",
"1001101101010",
"1001010110110",
"1100101011010",
"1001101011010",
"1001001001010",
"1001001010010",
"1001010010010",
"1010010010010",
"1001011011010"
]
func encodeCharacterString(_ characterString:String) -> String {
let location = CODE39_ALPHABET_STRING.location(characterString)
return CODE39_CHARACTER_ENCODINGS[location]
}
// MAKR: RSAbstractCodeGenerator
override open func isValid(_ contents: String) -> Bool {
if contents.length() > 0
&& contents.range(of: "*") == nil
&& contents == contents.uppercased() {
for character in contents {
let location = CODE39_ALPHABET_STRING.location(String(character))
if location == NSNotFound {
return false
}
}
return true
}
return false
}
override open func initiator() -> String {
return self.encodeCharacterString("*")
}
override open func terminator() -> String {
return self.encodeCharacterString("*")
}
override open func barcode(_ contents: String) -> String {
var barcode = ""
for character in contents {
barcode += self.encodeCharacterString(String(character))
}
return barcode
}
}
| mit | e800b017fbda61ac993eaeb3db17caa0 | 26.19802 | 81 | 0.571533 | 4.24575 | false | false | false | false |
Solar1011/- | 我的微博/我的微博/Classes/Module/Home/StatusCell/StatusForwardCell.swift | 1 | 2658 | //
// StatusForwardCell.swift
// 我的微博
//
// Created by teacher on 15/8/2.
// Copyright © 2015年 itheima. All rights reserved.
//
import UIKit
class StatusForwardCell: StatusCell {
/// `重写`属性 didSet 不会覆盖父类的方法!子类只需要继续设置自己的相关内容即可!
/// 需要和父类保持同样的行为
override var status: Status? {
didSet {
let name = status?.retweeted_status?.user?.name ?? ""
let text = status?.retweeted_status?.text ?? ""
forwardLabel.text = "@" + name + ":" + text
}
}
/// 设置界面
override func setupUI() {
super.setupUI()
// 1. 添加控件
contentView.insertSubview(backButton, belowSubview: pictureView)
contentView.insertSubview(forwardLabel, aboveSubview: backButton)
// 排版时测试
// forwardLabel.text = "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈"
// 2. 设置布局
// 1> 背景按钮
backButton.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size: nil, offset: CGPoint(x: -statusCellControlMargin, y: statusCellControlMargin))
backButton.ff_AlignVertical(type: ff_AlignType.TopRight, referView: bottomView, size: nil)
// 2> 转发文本
forwardLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: backButton, size: nil, offset: CGPoint(x: statusCellControlMargin, y: statusCellControlMargin))
// 3> 配图视图
let cons = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: forwardLabel, size: CGSize(width: 290, height: 290), offset: CGPoint(x: 0, y: statusCellControlMargin))
pictureWidthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
pictureHeightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
pictureTopCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
}
// MARK: - 懒加载控件
/// 转发文字
private lazy var forwardLabel: UILabel = {
let label = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
label.numberOfLines = 0
label.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 2 * statusCellControlMargin
return label
}()
private lazy var backButton: UIButton = {
let btn = UIButton()
btn.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
return btn
}()
}
| mit | e011aa6933b1bcc22ccd6491dad4d2b5 | 35.074627 | 193 | 0.63674 | 4.410584 | false | false | false | false |
apegroup/APEReactiveNetworking | Example/Project/Scenes/Login/Controllers/LoginViewController.swift | 1 | 5307 | // This file is a example created for the template project
import UIKit
import ReactiveSwift
import APEReactiveNetworking
import ReactiveObjC
import ReactiveObjCBridge
class LoginViewController: UIViewController {
//MARK: Properties
private let userApi = UserApiFactory.make()
//MARK: Outlets
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var registerButton: UIButton!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var dismissButton: UIBarButtonItem!
//MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
bindUIWithSignals()
}
//MARK: - Private
private func setupUI() {
usernameTextField.layer.borderWidth = 1
passwordTextField.layer.borderWidth = 1
}
private func bindUIWithSignals() {
//Connect the dismiss button
dismissButton.rac_command = RACCommand { [weak self] _ -> RACSignal in
return RACSignal.createSignal { (subscriber: RACSubscriber!) -> RACDisposable! in
self?.dismiss(animated: true, completion: nil)
return RACDisposable()
}.deliverOnMainThread()
}
//Connect the register button
registerButton.rac_command = RACCommand(signal: { [weak self] _ -> RACSignal in
return RACSignal.createSignal { (subscriber: RACSubscriber!) -> RACDisposable in
let disposable = self?.registerUserSignal()
.on(terminated: { subscriber.sendCompleted() })
.start()
return RACDisposable {
disposable?.dispose()
}}.deliverOnMainThread()
})
//Connect the login button
loginButton.rac_command = RACCommand(signal: { [weak self] _ -> RACSignal in
return RACSignal.createSignal { (subscriber: RACSubscriber!) -> RACDisposable in
let disposable = self?.loginUserSignal()
.on(terminated: { subscriber.sendCompleted() })
.start()
return RACDisposable {
disposable?.dispose()
}}.deliverOnMainThread()
})
let isValidUsernameSignal = usernameTextField.rac_textSignal().toSignalProducer()
.map { text in DataValidator().isValidUsername(text as! String) }
let isValidPasswordSignal = passwordTextField.rac_textSignal().toSignalProducer()
.map { text in DataValidator().isValidPassword(text as! String) }
//Mark textfields as green when input is valid
isValidUsernameSignal.on(value: { [weak self] isValid in
let color = isValid ? UIColor.green : UIColor.clear
self?.usernameTextField.layer.borderColor = color.cgColor
}).start()
isValidPasswordSignal.on(value: { [weak self] isValid in
let color = isValid ? UIColor.green : UIColor.clear
self?.passwordTextField.layer.borderColor = color.cgColor
}).start()
/*
Enable the register and the login buttons iff:
- input is valid
- no execution is in place
*/
let isValidInputSignal = isValidUsernameSignal.combineLatest(with: isValidPasswordSignal)
.map { (isValid: (username:Bool, password:Bool)) in isValid.username && isValid.password }
let isExecutingSignal = loginButton.rac_command.executing.combineLatest(with: registerButton.rac_command.executing)
.or()
.toSignalProducer()
.map { $0 as! Bool }
isValidInputSignal.combineLatest(with: isExecutingSignal).map { [weak self] (info: (isValidInput:Bool, requestInProgress:Bool)) in
let shouldEnable = info.isValidInput && !info.requestInProgress
self?.loginButton.isEnabled = shouldEnable
self?.registerButton.isEnabled = shouldEnable
}.start()
}
//MARK: - Register
private func registerUserSignal() -> SignalProducer<NetworkDataResponse<AuthResponse>, Network.OperationError> {
return userApi.register(username: usernameTextField.text ?? "",
password: passwordTextField.text ?? "")
.on(value: handleSuccess, failed: handleError)
}
//MARK: - Login
private func loginUserSignal() -> SignalProducer<NetworkDataResponse<AuthResponse>, Network.OperationError> {
return userApi.login(username: usernameTextField.text ?? "",
password: passwordTextField.text ?? "")
.on(value: handleSuccess, failed: handleError)
}
private func handleSuccess(_ authResponse: NetworkDataResponse<AuthResponse>) {
guard KeychainManager.save(jwtToken: authResponse.parsedData.accessToken) else {
return handleError()
}
dismiss(animated: true)
}
private func handleError(_ error: Network.OperationError? = nil) {
print("received error: \(error?.description ?? "")")
}
}
| mit | 89ae0fd5350240b2233d39f86d88295d | 37.737226 | 138 | 0.609384 | 5.510903 | false | false | false | false |
jjorgemoura/countdownz | countdownz/AppDelegate.swift | 1 | 4692 | //
// AppDelegate.swift
// countdownz
//
// Created by Jorge Moura on 05/03/2017.
// Copyright © 2017 Jorge Moura. 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: "countdownz")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate.
//You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate.
//You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 92ccd42c1ffc5e95a034b54aaf8a0e5b | 45.445545 | 155 | 0.672351 | 5.820099 | false | false | false | false |
TonyStark106/NiceKit | NiceKit/Sources/Extension/Class/NSAttributedString+Nice.swift | 1 | 2838 | //
// NSAttributedString+Nice.swift
// Pods
//
// Created by 吕嘉豪 on 2017/4/20.
//
//
import Foundation
import SwiftyAttributes
extension Nice where Base: NSAttributedString {
/// EZSE: Adds bold attribute to NSAttributedString and returns it
#if os(iOS)
public func bold() -> NSAttributedString {
guard let copy = base.mutableCopy() as? NSMutableAttributedString else { return base }
let range = (base.string as NSString).range(of: base.string)
copy.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)], range: range)
return copy
}
#endif
/// EZSE: Adds underline attribute to NSAttributedString and returns it
public func underline() -> NSAttributedString {
guard let copy = base.mutableCopy() as? NSMutableAttributedString else { return base }
let range = (base.string as NSString).range(of: base.string)
copy.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue], range: range)
return copy
}
#if os(iOS)
/// EZSE: Adds italic attribute to NSAttributedString and returns it
public func italic() -> NSAttributedString {
guard let copy = base.mutableCopy() as? NSMutableAttributedString else { return base }
let range = (base.string as NSString).range(of: base.string)
copy.addAttributes([NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)], range: range)
return copy
}
/// EZSE: Adds strikethrough attribute to NSAttributedString and returns it
public func strikethrough() -> NSAttributedString {
guard let copy = base.mutableCopy() as? NSMutableAttributedString else { return base }
let range = (base.string as NSString).range(of: base.string)
let attributes = [
NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)]
copy.addAttributes(attributes, range: range)
return copy
}
#endif
/// EZSE: Adds color attribute to NSAttributedString and returns it
public func color(_ color: UIColor) -> NSAttributedString {
guard let copy = base.mutableCopy() as? NSMutableAttributedString else { return base }
let range = (base.string as NSString).range(of: base.string)
copy.addAttributes([NSForegroundColorAttributeName: color], range: range)
return copy
}
}
/// EZSE: Appends one NSAttributedString to another NSAttributedString and returns it
public func += (left: inout NSAttributedString, right: NSAttributedString) {
let ns = NSMutableAttributedString(attributedString: left)
ns.append(right)
left = ns
}
| mit | c5c7589a8b96cd2fe1e3ae20f767aa8b | 34.4 | 119 | 0.676201 | 5.23475 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Internals/Audio File/AKAudioFile+ConvenienceInitializers.swift | 1 | 9014 | //
// AKAudioFile+ConvenienceInitializers.swift
// AudioKit
//
// Created by Laurent Veliscek, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
import AVFoundation
extension AKAudioFile {
/// Opens a file for reading.
///
/// - parameter name: Filename, including hte extension
/// - parameter baseDir: Location of file, can be set to .Resources, .Documents or .Temp
///
/// - returns: An initialized AKAudioFile for reading, or nil if init failed
///
public convenience init(readFileName name: String,
baseDir: BaseDirectory = .Resources) throws {
let filePath: String
let fileNameWithExtension = name
switch baseDir {
case .Temp:
filePath = (NSTemporaryDirectory() as String) + name
case .Documents:
filePath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) + "/" + name
case .Resources:
func resourcePath(name: String?) -> String? {
return NSBundle.mainBundle().pathForResource(name, ofType: "")
}
let path = resourcePath(name)
if path == nil {
print("ERROR: AKAudioFile cannot find \"\(name)\" in resources")
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorFileDoesNotExist, userInfo: nil)
}
filePath = path!
}
let fileUrl = NSURL(fileURLWithPath: filePath)
do {
try self.init(forReading: fileUrl)
} catch let error as NSError {
print("Error: AKAudioFile: \"\(name)\" doesn't seem to be a valid AudioFile")
print(error.localizedDescription)
throw error
}
}
/// Initialize file for recording / writing purpose
///
/// Default is a .caf AKAudioFile with AudioKit settings
/// If file name is an empty String, a unique Name will be set
/// If no baseDir is set, baseDir will be the Temp Directory
///
/// From Apple doc: The file type to create is inferred from the file extension of fileURL.
/// This method will overwrite a file at the specified URL if a file already exists.
///
/// Note: It seems that Apple's AVAudioFile class has a bug with .wav files. They cannot be set
/// with a floating Point encoding. As a consequence, such files will fail to record properly.
/// So it's better to use .caf (or .aif) files for recording purpose.
///
/// Example of use: to create a temp .caf file with a unique name for recording:
/// let recordFile = AKAudioFile()
///
/// - Parameters:
/// - name: the name of the file without its extension (String).
/// - ext: the extension of the file without "." (String).
/// - baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp
/// - settings: The settings of the file to create.
/// - format: The processing commonFormat to use when writing.
/// - interleaved: Bool (Whether to use an interleaved processing format.)
///
public convenience init(writeIn baseDir: BaseDirectory = .Temp,
name: String = "",
settings: [String : AnyObject] = AKSettings.audioFormat.settings)
throws {
let fileNameWithExtension: String
// Create a unique file name if fileName == ""
if name == "" {
fileNameWithExtension = NSUUID().UUIDString + ".caf"
} else {
fileNameWithExtension = name + ".caf"
}
var filePath: String
switch baseDir {
case .Temp:
filePath = (NSTemporaryDirectory() as String) + fileNameWithExtension
case .Documents:
filePath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) + "/" + fileNameWithExtension
case .Resources:
print( "ERROR AKAudioFile: cannot create a file in applications resources")
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotCreateFile, userInfo: nil)
}
let nsurl = NSURL(string: filePath)
guard nsurl != nil else {
print( "ERROR AKAudioFile: directory \"\(filePath)\" isn't valid")
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotCreateFile, userInfo: nil)
}
// Directory exists ?
let directoryPath = nsurl!.URLByDeletingLastPathComponent
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath((directoryPath?.absoluteString)!) == false {
print( "ERROR AKAudioFile: directory \"\(directoryPath)\" doesn't exist")
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotCreateFile, userInfo: nil)
}
// AVLinearPCMIsNonInterleaved cannot be set to false (ignored but throw a warning)
var fixedSettings = settings
fixedSettings[ AVLinearPCMIsNonInterleaved] = NSNumber(bool: false)
do {
try self.init(forWriting: nsurl!, settings: fixedSettings)
} catch let error as NSError {
print( "ERROR AKAudioFile: Couldn't create an AKAudioFile...")
print( "Error: \(error)")
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotCreateFile, userInfo: nil)
}
}
/// Instantiate a file from Floats Arrays.
///
/// To create a stereo file, you pass [leftChannelFloats, rightChannelFloats]
/// where leftChannelFloats and rightChannelFloats are 2 arrays of FLoat values.
/// Arrays must both have the same number of Floats.
///
/// - Parameters:
/// - floatsArrays: An array of Arrays of floats
/// - name: the name of the file without its extension (String).
/// - baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp
///
/// - Returns: a .caf AKAudioFile set to AudioKit settings (32 bits float @ 44100 Hz)
///
public convenience init(createFileFromFloats floatsArrays: [[Float]],
baseDir: BaseDirectory = .Temp,
name: String = "") throws {
let channelCount = floatsArrays.count
var fixedSettings = AKSettings.audioFormat.settings
fixedSettings[AVNumberOfChannelsKey] = channelCount
try self.init(writeIn: baseDir, name: name)
// create buffer for floats
let format = AVAudioFormat(standardFormatWithSampleRate: 44100,
channels: AVAudioChannelCount (channelCount))
let buffer = AVAudioPCMBuffer(PCMFormat: format,
frameCapacity: AVAudioFrameCount(floatsArrays[0].count))
// Fill the buffers
for channel in 0..<channelCount {
let channelNData = buffer.floatChannelData[channel]
for f in 0..<Int(buffer.frameCapacity) {
channelNData[f] = floatsArrays[channel][f]
}
}
// set the buffer frameLength
buffer.frameLength = buffer.frameCapacity
// Write the buffer in file
do {
try self.writeFromBuffer(buffer)
} catch let error as NSError {
print( "ERROR AKAudioFile: cannot writeFromBuffer Error: \(error)")
throw error
}
}
/// Convenience init to instantiate a file from an AVAudioPCMBuffer.
///
/// - Parameters:
/// - buffer: the :AVAudioPCMBuffer that will be used to fill the AKAudioFile
/// - baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp
/// - name: the name of the file without its extension (String).
///
/// - Returns: a .caf AKAudioFile set to AudioKit settings (32 bits float @ 44100 Hz)
///
public convenience init(fromAVAudioPCMBuffer buffer: AVAudioPCMBuffer,
baseDir: BaseDirectory = .Temp,
name: String = "") throws {
try self.init(writeIn: baseDir,
name: name)
// Write the buffer in file
do {
try self.writeFromBuffer(buffer)
} catch let error as NSError {
print( "ERROR AKAudioFile: cannot writeFromBuffer Error: \(error)")
throw error
}
}
}
| mit | bc7e39d39a7802075a8548befacdc3fe | 41.116822 | 141 | 0.575391 | 5.406719 | false | false | false | false |
dreamsxin/swift | test/decl/inherit/inherit.swift | 2 | 1868 | // RUN: %target-parse-verify-swift
class A { }
protocol P { }
// Duplicate inheritance
class B : A, A { } // expected-error{{duplicate inheritance from 'A'}}{{12-15=}}
// Duplicate inheritance from protocol
class B2 : P, P { } // expected-error{{duplicate inheritance from 'P'}}{{13-16=}}
// Multiple inheritance
class C : B, A { } // expected-error{{multiple inheritance from classes 'B' and 'A'}}
// Superclass in the wrong position
class D : P, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{12-15=}}{{11-11=A, }}
// Struct inheriting a class
struct S : A { } // expected-error{{non-class type 'S' cannot inherit from class 'A'}}
// Protocol inheriting a class
protocol Q : A { } // expected-error{{non-class type 'Q' cannot inherit from class 'A'}}
// Extension inheriting a class
extension C : A { } // expected-error{{extension of type 'C' cannot inherit from class 'A'}}
// Keywords in inheritance clauses
struct S2 : struct { } // expected-error{{expected identifier for type name}}
// Protocol composition in inheritance clauses
struct S3 : P, protocol<P> { } // expected-error{{duplicate inheritance from 'P'}}
// expected-error@-1{{protocol composition is neither allowed nor needed here}}{{16-25=}}{{26-27=}}
struct S4 : protocol< { } // expected-error{{expected identifier for type name}}
// expected-error@-1{{protocol composition is neither allowed nor needed here}}{{13-23=}}
class GenericBase<T> {}
class GenericSub<T> : GenericBase<T> {} // okay
class InheritGenericParam<T> : T {} // expected-error {{inheritance from non-protocol, non-class type 'T'}}
class InheritBody : T { // expected-error {{use of undeclared type 'T'}}
typealias T = A
}
class InheritBodyBad : fn { // expected-error {{use of undeclared type 'fn'}}
func fn() {}
}
| apache-2.0 | de6ce4d6af5cecef9c955472266e46db | 39.608696 | 130 | 0.667024 | 3.820041 | false | false | false | false |
nohana/NohanaImagePicker | NohanaImagePicker/PickedAssetList.swift | 1 | 4465 | /*
* Copyright (C) 2016 nohana, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
class PickedAssetList: ItemList {
var assetlist: Array<Asset> = []
weak var nohanaImagePickerController: NohanaImagePickerController?
// MARK: - ItemList
typealias Item = Asset
var title: String {
return "Selected Assets"
}
func update(_ handler:(() -> Void)?) {
fatalError("not supported")
}
subscript (index: Int) -> Item {
return assetlist[index]
}
// MARK: - CollectionType
var startIndex: Int {
return 0
}
var endIndex: Int {
return assetlist.count
}
// MARK: - Manage assetlist
func pick(asset: Asset) -> Bool {
guard canPick(asset: asset) else {
return false
}
assetlist.append(asset)
let assetsCountAfterPicking = self.count
if asset is PhotoKitAsset {
let originalAsset = (asset as! PhotoKitAsset).originalAsset
nohanaImagePickerController!.delegate?.nohanaImagePicker?(nohanaImagePickerController!, didPickPhotoKitAsset: originalAsset, pickedAssetsCount: assetsCountAfterPicking)
NotificationCenter.default.post(
Notification(
name: NotificationInfo.Asset.PhotoKit.didPick,
object: nohanaImagePickerController,
userInfo: [
NotificationInfo.Asset.PhotoKit.didPickUserInfoKeyAsset : originalAsset,
NotificationInfo.Asset.PhotoKit.didPickUserInfoKeyPickedAssetsCount : assetsCountAfterPicking
]
)
)
}
return true
}
func drop(asset: Asset) -> Bool {
let assetsCountBeforeDropping = self.count
if asset is PhotoKitAsset {
if let canDrop = nohanaImagePickerController!.delegate?.nohanaImagePicker?(nohanaImagePickerController!, willDropPhotoKitAsset: (asset as! PhotoKitAsset).originalAsset, pickedAssetsCount: assetsCountBeforeDropping), !canDrop {
return false
}
}
assetlist = assetlist.filter { $0.identifier != asset.identifier }
let assetsCountAfterDropping = self.count
if asset is PhotoKitAsset {
let originalAsset = (asset as! PhotoKitAsset).originalAsset
nohanaImagePickerController!.delegate?.nohanaImagePicker?(nohanaImagePickerController!, didDropPhotoKitAsset: originalAsset, pickedAssetsCount: assetsCountAfterDropping)
NotificationCenter.default.post(
Notification(
name: NotificationInfo.Asset.PhotoKit.didDrop,
object: nohanaImagePickerController,
userInfo: [
NotificationInfo.Asset.PhotoKit.didDropUserInfoKeyAsset : originalAsset,
NotificationInfo.Asset.PhotoKit.didDropUserInfoKeyPickedAssetsCount : assetsCountAfterDropping
]
)
)
}
return true
}
func isPicked(_ asset: Asset) -> Bool {
return assetlist.contains { $0.identifier == asset.identifier }
}
func canPick(asset: Asset) -> Bool {
guard !isPicked(asset) else {
return false
}
let assetsCountBeforePicking = self.count
if asset is PhotoKitAsset {
if let canPick = nohanaImagePickerController!.delegate?.nohanaImagePicker?(nohanaImagePickerController!, willPickPhotoKitAsset: (asset as! PhotoKitAsset).originalAsset, pickedAssetsCount: assetsCountBeforePicking), !canPick {
return false
}
}
guard nohanaImagePickerController!.maximumNumberOfSelection == 0 || assetsCountBeforePicking < nohanaImagePickerController!.maximumNumberOfSelection else {
return false
}
return true
}
}
| apache-2.0 | 15dd59f4834446de7329d3c334211d59 | 35.900826 | 238 | 0.642777 | 5.011223 | false | false | false | false |
dps923/winter2017 | notes/Project_Templates/WebServiceModel/Classes/WebServiceRequest.swift | 2 | 4043 | //
// WebServiceRequest.swift
// Classes
//
// Created by Peter McIntyre on 2015-02-16.
// Copyright (c) 2017 School of ICT, Seneca College. All rights reserved.
//
import UIKit
class WebServiceRequest {
// MARK: - Properties
var urlBase = "https://ict.senecacollege.ca/api"
var httpMethod = "GET"
var headerAccept = "application/json"
var headerContentType = "application/json"
// MARK: - Public methods
func sendRequest(toUrlPath urlPath: String, dataKeyName: String?, completion: @escaping ([AnyObject])->Void) {
// Assemble the URL
guard let url = URL(string: "\(urlBase)\(urlPath)") else {
print("Failed to construct url with \(urlBase)\(urlPath)")
return
}
// Diagnostic
print(url.description)
// Create a session configuration object
let sessionConfig = URLSessionConfiguration.default
// Create a session object
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: OperationQueue.main)
// ^^^ Beware: there is a `URLSession.shared` available, this will respond off the main thread.
// This URLSession uses OperationQueue.main, which directs it to callback on the main thread only.
// Create a request object
let request = NSMutableURLRequest(url: url)
// Set its important properties
request.httpMethod = httpMethod
request.setValue(headerAccept, forHTTPHeaderField: "Accept")
// Define a network task; after it's created, it's in a "suspended" state
let task: URLSessionDataTask = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if let error = error {
print("Task request error: \(error.localizedDescription)")
} else if let data = data {
// FYI, show some details about the response
// This code is interesting during development, but you would not leave it in production/deployed code
let r = response as? HTTPURLResponse
print("Response data...\nStatus code: \(r?.statusCode)\nHeaders:\n\(r?.allHeaderFields.description)")
var results: Any! = nil
// Attempt to deserialize the data from the response
do {
results = try JSONSerialization.jsonObject(with: data)
} catch {
print("json error: \(error.localizedDescription)")
return
}
// The request was successful, and deserialization was successful.
if let dataKeyName = dataKeyName {
// Therefore, extract the data we want from the dictionary, and call the completion callback.
// This version of the code works only with
// top/first level key-value pairs in the source JSON data
if let resultDict = results as? NSDictionary, let extractedData = resultDict[dataKeyName] as? [AnyObject] {
completion(extractedData)
} else {
print("Error extracting from json dict for key \(dataKeyName)")
}
} else {
completion(results as! [AnyObject])
}
} else {
let r = response as? HTTPURLResponse
print("No data!\nStatus code: \(r?.statusCode)\nHeaders:\n\(r?.allHeaderFields.description)")
}
// Finally, reference the app's network activity indicator in the status bar
UIApplication.shared.isNetworkActivityIndicatorVisible = false
})
// Force the task to execute
task.resume()
// Reference the app's network activity indicator in the status bar
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
}
| mit | 8c5772ee965323afb324b86ea0af6402 | 39.43 | 127 | 0.593124 | 5.383489 | false | false | false | false |
AlexLittlejohn/OMDBMovies | OMDBMovies/ViewControllers/MovieDetailViewController.swift | 1 | 5693 | //
// MovieDetailViewController.swift
// OMDBMovies
//
// Created by Alex Littlejohn on 2016/04/05.
// Copyright © 2016 Alex Littlejohn. All rights reserved.
//
import UIKit
class MovieDetailViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var genreKeyLabel: UILabel!
@IBOutlet weak var genreValueLabel: UILabel!
@IBOutlet weak var starringKeyLabel: UILabel!
@IBOutlet weak var starringValueLabel: UILabel!
@IBOutlet weak var directorsKeyLabel: UILabel!
@IBOutlet weak var directorsValueLabel: UILabel!
@IBOutlet weak var writersKeyLabel: UILabel!
@IBOutlet weak var writersValueLabel: UILabel!
@IBOutlet weak var plotKeyLabel: UILabel!
@IBOutlet weak var plotValueLabel: UILabel!
@IBOutlet weak var languageKeyLabel: UILabel!
@IBOutlet weak var languageValueLabel: UILabel!
@IBOutlet weak var metacriticKeyLabel: UILabel!
@IBOutlet weak var metacriticValueLabel: UILabel!
@IBOutlet weak var imdbKeyLabel: UILabel!
@IBOutlet weak var imdbValueLabel: UILabel!
@IBOutlet weak var imageSpinner: UIActivityIndicatorView!
@IBOutlet weak var emptyStateView: EmptyStateView!
let titleView = MovieDetailTitleView(frame: CGRect(x: 0, y: 0, width: Metrics.Detail.TitleViewWidth, height: Typography.Detail.Title!.lineHeight + Typography.Detail.Subtitle!.lineHeight))
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = titleView
imageView.backgroundColor = Colors.Detail.ImageBackground
let keyFont = Typography.Detail.Key
genreKeyLabel.font = keyFont
starringKeyLabel.font = keyFont
directorsKeyLabel.font = keyFont
writersKeyLabel.font = keyFont
plotKeyLabel.font = keyFont
languageKeyLabel.font = keyFont
metacriticKeyLabel.font = keyFont
imdbKeyLabel.font = keyFont
let valueFont = Typography.Detail.Value
genreValueLabel.font = valueFont
starringValueLabel.font = valueFont
directorsValueLabel.font = valueFont
writersValueLabel.font = valueFont
plotValueLabel.font = valueFont
languageValueLabel.font = valueFont
metacriticValueLabel.font = valueFont
imdbValueLabel.font = valueFont
let keyColor = Colors.Detail.Key
genreKeyLabel.textColor = keyColor
starringKeyLabel.textColor = keyColor
directorsKeyLabel.textColor = keyColor
writersKeyLabel.textColor = keyColor
plotKeyLabel.textColor = keyColor
languageKeyLabel.textColor = keyColor
metacriticKeyLabel.textColor = keyColor
imdbKeyLabel.textColor = keyColor
let valueColor = Colors.Detail.Value
genreValueLabel.textColor = valueColor
starringValueLabel.textColor = valueColor
directorsValueLabel.textColor = valueColor
writersValueLabel.textColor = valueColor
plotValueLabel.textColor = valueColor
languageValueLabel.textColor = valueColor
metacriticValueLabel.textColor = valueColor
imdbValueLabel.textColor = valueColor
genreKeyLabel.text = localizedString("genreKey")
starringKeyLabel.text = localizedString("starKey")
directorsKeyLabel.text = localizedString("directorKey")
writersKeyLabel.text = localizedString("writerKey")
plotKeyLabel.text = localizedString("plotKey")
languageKeyLabel.text = localizedString("languageKey")
metacriticKeyLabel.text = localizedString("metacriticKey")
imdbKeyLabel.text = localizedString("imdbKey")
emptyStateView.configureWithState(.Working)
imageSpinner.startAnimating()
}
func configureWithMovie(movie: FullMovie) {
emptyStateView.configureWithState(.None)
genreValueLabel.text = movie.genre.joinWithSeparator(", ")
starringValueLabel.text = movie.actors.joinWithSeparator(", ")
directorsValueLabel.text = movie.directors.joinWithSeparator(", ")
writersValueLabel.text = movie.writers.joinWithSeparator(", ")
plotValueLabel.text = movie.plot
languageValueLabel.text = movie.languages.joinWithSeparator(", ")
metacriticValueLabel.text = movie.metascore
imdbValueLabel.text = movie.imdbRating
let genreKey = movie.genre.count > 1 ? "genresKey" : "genreKey"
let starKey = movie.actors.count > 1 ? "starsKey" : "starKey"
let directorKey = movie.directors.count > 1 ? "directorsKey" : "directorKey"
let writerKey = movie.writers.count > 1 ? "writersKey" : "writerKey"
let languageKey = movie.languages.count > 1 ? "languagesKey" : "languageKey"
genreKeyLabel.text = localizedString(genreKey)
starringKeyLabel.text = localizedString(starKey)
directorsKeyLabel.text = localizedString(directorKey)
writersKeyLabel.text = localizedString(writerKey)
languageKeyLabel.text = localizedString(languageKey)
titleView.configureWithMovie(movie)
// We do this after we get the rest of the data so the user has something to look at while we wait for the image to download
ImageRequest(urlString: largeImageURL(movie)).work { (image, error) in
self.imageSpinner.stopAnimating()
guard let image = image else {
self.imageView.image = UIImage(named: "Placeholder")
return
}
self.imageView.image = image
}
}
}
| mit | 40f48be1ac38bd7e0a2262a8f92e8c78 | 39.94964 | 191 | 0.683064 | 5.014978 | false | false | false | false |
ahoppen/swift | test/Distributed/distributed_actor_initialization.swift | 4 | 1624 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift
// RUN: %target-swift-frontend -typecheck -verify -disable-availability-checking -I %t 2>&1 %s
// REQUIRES: concurrency
// REQUIRES: distributed
import Distributed
import FakeDistributedActorSystems
@available(SwiftStdlib 5.5, *)
typealias DefaultDistributedActorSystem = FakeActorSystem
// ==== ----------------------------------------------------------------------------------------------------------------
distributed actor OK0 { }
distributed actor OK1 {
var x: Int = 1
// ok, since all fields are initialized, the constructor can be synthesized
}
distributed actor OK2 {
var x: Int
init(x: Int, system: FakeActorSystem) { // ok
self.x = x
}
}
// NOTE: keep in mind this is only through typechecking, so no explicit
// actorSystem is being assigned here.
distributed actor OK3 {
init() {}
}
distributed actor OK4 {
init(x: String) {
}
}
distributed actor OK5 {
var x: Int = 1
init(system: FakeActorSystem, too many: FakeActorSystem) {
}
}
distributed actor OK6 {
var x: Int
init(y: Int, system: FakeActorSystem) {
self.x = y
}
}
distributed actor OKMulti {
convenience init(y: Int, system: FakeActorSystem) { // ok
self.init(actorSystem: system)
}
}
distributed actor OKMultiDefaultValues {
convenience init(y: Int, system: FakeActorSystem, x: Int = 1234) { // ok
self.init(actorSystem: system)
}
}
| apache-2.0 | 3840d1b23cf26fb3e7c0197fb81ea52b | 21.873239 | 219 | 0.66564 | 3.894484 | false | false | false | false |
CoderLala/DouYZBTest | DouYZB/DouYZB/Classes/Tools/Extension/Common.swift | 1 | 451 | //
// Common.swift
// DouYZB
//
// Created by 黄金英 on 17/1/26.
// Copyright © 2017年 黄金英. All rights reserved.
//
import Foundation
import UIKit
let kStatusBarHeight : CGFloat = 20.0
let kNavigationBarHeight : CGFloat = 44.0
let kNavgationBHeight : CGFloat = 64.0
//let kTabBarHeight : CGFloat = 44.0
let kTabBarHeight : CGFloat = 50.0
let kScreenWidth = UIScreen.main.bounds.width
let kScreenHeight = UIScreen.main.bounds.height
| mit | d7e6f560b479de1c320539eab767c673 | 20.8 | 47 | 0.731651 | 3.40625 | false | false | false | false |
Authman2/Pix | Pods/Hero/Sources/HeroDebugView.swift | 1 | 6669 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
#if os(iOS)
protocol HeroDebugViewDelegate {
func onProcessSliderChanged(progress: Float)
func onPerspectiveChanged(translation: CGPoint, rotation: CGFloat, scale: CGFloat)
func on3D(wants3D: Bool)
func onDisplayArcCurve(wantsCurve: Bool)
func onDone()
}
class HeroDebugView: UIView {
var backgroundView: UIView!
var debugSlider: UISlider!
var perspectiveButton: UIButton!
var doneButton: UIButton!
var arcCurveButton: UIButton?
var delegate: HeroDebugViewDelegate?
var panGR: UIPanGestureRecognizer!
var pinchGR: UIPinchGestureRecognizer!
var showControls: Bool = false {
didSet {
layoutSubviews()
}
}
var showOnTop: Bool = false
var rotation: CGFloat = CGFloat(M_PI / 6)
var scale: CGFloat = 0.6
var translation: CGPoint = .zero
var progress: Float {
return debugSlider.value
}
init(initialProcess: Float, showCurveButton: Bool, showOnTop: Bool) {
super.init(frame:.zero)
self.showOnTop = showOnTop
backgroundView = UIView(frame:.zero)
backgroundView.backgroundColor = UIColor(white: 1.0, alpha: 0.95)
backgroundView.layer.shadowColor = UIColor.darkGray.cgColor
backgroundView.layer.shadowOpacity = 0.3
backgroundView.layer.shadowRadius = 5
backgroundView.layer.shadowOffset = CGSize.zero
addSubview(backgroundView)
doneButton = UIButton(type: .system)
doneButton.setTitle("Done", for: .normal)
doneButton.addTarget(self, action: #selector(onDone), for: .touchUpInside)
backgroundView.addSubview(doneButton)
perspectiveButton = UIButton(type: .system)
perspectiveButton.setTitle("3D View", for: .normal)
perspectiveButton.addTarget(self, action: #selector(onPerspective), for: .touchUpInside)
backgroundView.addSubview(perspectiveButton)
if showCurveButton {
arcCurveButton = UIButton(type: .system)
arcCurveButton!.setTitle("Show Arcs", for: .normal)
arcCurveButton!.addTarget(self, action: #selector(onDisplayArcCurve), for: .touchUpInside)
backgroundView.addSubview(arcCurveButton!)
}
debugSlider = UISlider(frame: .zero)
debugSlider.layer.zPosition = 1000
debugSlider.minimumValue = 0
debugSlider.maximumValue = 1
debugSlider.addTarget(self, action: #selector(onSlide), for: .valueChanged)
debugSlider.isUserInteractionEnabled = true
debugSlider.value = initialProcess
backgroundView.addSubview(debugSlider)
panGR = UIPanGestureRecognizer(target: self, action: #selector(pan))
panGR.delegate = self
panGR.maximumNumberOfTouches = 1
addGestureRecognizer(panGR)
pinchGR = UIPinchGestureRecognizer(target: self, action: #selector(pinch))
pinchGR.delegate = self
addGestureRecognizer(pinchGR)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func layoutSubviews() {
super.layoutSubviews()
var backgroundFrame = bounds
backgroundFrame.size.height = 72
if showOnTop {
backgroundFrame.origin.y = showControls ? 0 : -80
} else {
backgroundFrame.origin.y = bounds.maxY - CGFloat(showControls ? 72.0 : -8.0)
}
backgroundView.frame = backgroundFrame
var sliderFrame = bounds.insetBy(dx: 10, dy: 0)
sliderFrame.size.height = 44
sliderFrame.origin.y = 28
debugSlider.frame = sliderFrame
perspectiveButton.sizeToFit()
perspectiveButton.frame.origin = CGPoint(x:bounds.maxX - perspectiveButton.bounds.width - 10, y: 4)
doneButton.sizeToFit()
doneButton.frame.origin = CGPoint(x:10, y: 4)
arcCurveButton?.sizeToFit()
arcCurveButton?.center = CGPoint(x: center.x, y: doneButton.center.y)
}
var startRotation: CGFloat = 0
@objc public func pan() {
if panGR.state == .began {
startRotation = rotation
}
rotation = startRotation + panGR.translation(in: nil).x / 150
if rotation > CGFloat(M_PI) {
rotation -= CGFloat(2 * M_PI)
} else if rotation < -CGFloat(M_PI) {
rotation += CGFloat(2 * M_PI)
}
delegate?.onPerspectiveChanged(translation:translation, rotation: rotation, scale:scale)
}
var startLocation: CGPoint = .zero
var startTranslation: CGPoint = .zero
var startScale: CGFloat = 1
@objc public func pinch() {
switch pinchGR.state {
case .began:
startLocation = pinchGR.location(in: nil)
startTranslation = translation
startScale = scale
fallthrough
case .changed:
if pinchGR.numberOfTouches >= 2 {
scale = min(1, max(0.2, startScale * pinchGR.scale))
translation = startTranslation + pinchGR.location(in: nil) - startLocation
delegate?.onPerspectiveChanged(translation:translation, rotation: rotation, scale:scale)
}
default:
break
}
}
@objc public func onDone() {
delegate?.onDone()
}
@objc public func onPerspective() {
perspectiveButton.isSelected = !perspectiveButton.isSelected
delegate?.on3D(wants3D: perspectiveButton.isSelected)
}
@objc public func onDisplayArcCurve() {
arcCurveButton!.isSelected = !arcCurveButton!.isSelected
delegate?.onDisplayArcCurve(wantsCurve: arcCurveButton!.isSelected)
}
@objc public func onSlide() {
delegate?.onProcessSliderChanged(progress: debugSlider.value)
}
}
extension HeroDebugView:UIGestureRecognizerDelegate {
public override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return perspectiveButton.isSelected
}
}
#endif
| gpl-3.0 | f50105cd48db0e7e941063a0595b408b | 33.734375 | 103 | 0.723197 | 4.291506 | false | false | false | false |
DonMag/ScratchPad | Swift3/scratchy/XC8.playground/Pages/switchy.xcplaygroundpage/Contents.swift | 1 | 1449 | //: [Previous](@previous)
import Foundation
import UIKit
//import PlaygroundSupport
import XCPlayground
var str = "Hello, playground"
//: [Next](@next)
class SwitchViewController : UIViewController {
var hasInternet = true
var switchy: UISwitch = UISwitch()
var previousState = true
var lstr = 0
override func loadView() {
// UI
let view = UIView()
view.backgroundColor = UIColor.redColor()
view.bounds = CGRect(x: 0, y: 0, width: 200, height: 200)
switchy.on = true
view.addSubview(switchy)
self.switchy.addTarget(self, action: #selector(stateChanged(_:)), forControlEvents: .ValueChanged)
// Layout
// switchy.translatesAutoresizingMaskIntoConstraints = false
self.switchy.center = CGPoint(x: 100, y: 100)
// NSLayoutConstraint.activate([
// switchy.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
// switchy.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
// ])
self.view = view
}
func stateChanged(switchy: UISwitch) {
print("Hey switch! ", switchy.on)
lstr = lstr + 1
print("now: ", lstr)
if (!self.hasInternet) {
print("hey there's no internet, dummy")
switchy.on = self.previousState
}
}
func stateChanged(inetswitchy: UISwitch) {
}
}
let vc = SwitchViewController()
vc.hasInternet = true
XCPlaygroundPage.currentPage.liveView = vc
//XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
| mit | ae1b37de004add509381da0117c3b8e5 | 18.581081 | 100 | 0.696342 | 3.613466 | false | false | false | false |
MattKiazyk/AlamoImage | ImageView-ios.swift | 3 | 2106 | //
// ImageView.swift
// AlamoImage
//
// Created by Guillermo Chiacchio on 6/5/15.
//
//
import Alamofire
import Foundation
#if os(iOS)
/**
UIImageView extension to support and handle the request of a remote image, to be downloaded and set. iOS Only.
*/
extension UIImageView {
/// A reference to handle the `Request`, if any, for the `UIImage` instance.
public var request: Alamofire.Request? {
get {
return associatedObject(self, &imageRequestPropertyKey) as! Alamofire.Request?
}
set {
setAssociatedObject(self, &imageRequestPropertyKey, newValue)
}
}
/**
Creates a request using `Alamofire`, and sets the returned image into the `UIImageview` instance. This method cancels any previous request for the same `UIImageView` instance. It also automatically adds and retrieves the image to/from the global `AlamoImage.imageCache` cache instance if any.
:param: URLStringConv The URL for the image.
:param: placeholder An optional `UIImage` instance to be set until the requested image is available.
:param: success The code to be executed if the request finishes successfully.
:param: failure The code to be executed if the request finishes with some error.
*/
public func requestImage(URLStringConv: URLStringConvertible, placeholder: UIImage? = nil,
success _success: (UIImageView, NSURLRequest?, NSHTTPURLResponse?, UIImage?) -> Void = { (imageView, _, _, theImage) in
imageView.image = theImage
},
failure _failure: (UIImageView, NSURLRequest?, NSHTTPURLResponse?, NSError?) -> Void = { (_, _, _, _) in }
)
{
if (placeholder != nil) {
self.image = placeholder
}
self.request?.cancel()
self.request = UIImage.requestImage(URLStringConv,
success: { (req, res, img) in
_success(self, req, res, img)
},
failure: { (req, res, err) in
_failure(self, req, res, err)
}
)
}
}
#endif
| mit | 4cbac030b3d7d13f3b8f70618317c3f7 | 33.52459 | 296 | 0.62868 | 4.56833 | false | false | false | false |
austinzheng/swift | validation-test/compiler_crashers_fixed/01297-swift-type-walk.swift | 65 | 820 | // 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
// RUN: not %target-swift-frontend %s -typecheck
func ^(r: l, k) -> k {
? {
h (s : t?) q u {
g let d = s {
}
}
e}
let u : [Int?] = [n{
c v: j t.v == m>(n: o<t>) {
}
}
class a<f : g, g : g where f.f == g> {
}
protocol g {
typealias f
}
struct c<h : g> : g {
typealias e = a<c<h>, f>
func r<t>() {
f f {
}
}
struct i<o : u> {
}
func r<o>() -> [i<o>] {
}
class g<t : g> {
}
class g: g {
}
class n : h {
}
func i() -> l func o() -> m {
}
class d<c>: NSObject {
}
func c<b:c
| apache-2.0 | bbce24871e9ff44b68b25623fb4f14f7 | 17.222222 | 79 | 0.585366 | 2.5387 | false | false | false | false |
alessioros/mobilecodegenerator3 | examples/ParkTraining/completed/ios/ParkTraining/ParkTraining/ExerciseEditViewController.swift | 2 | 6651 |
import UIKit
import CoreData
class ExerciseEditViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate
{
@IBOutlet weak var editSaveButton: UIButton!
@IBOutlet weak var editDeleteButton: UIButton!
@IBOutlet weak var editNameEditText: UITextField!
@IBOutlet weak var editRepsSpinner: UIPickerView!
var editSetsSpinnerDataSource = ["1", "2", "3"]
var numSets: Int = 1
@IBOutlet weak var editSetsSpinner: UIPickerView!
var editRepsSpinnerDataSource = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
var numReps: Int = 1
var exerciseIndex: Int = 0
var exercise: NSManagedObject!
override func viewDidLoad() {
super.viewDidLoad()
editSaveButton.layer.cornerRadius = 36
editDeleteButton.layer.cornerRadius = 36
self.editRepsSpinner.dataSource = self
self.editRepsSpinner.delegate = self
self.editSetsSpinner.dataSource = self
self.editSetsSpinner.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//Legge l'esercizio
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Exercise")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
self.exercise = results[self.exerciseIndex] as! NSManagedObject
} catch {
print("Error")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//aggiorna ui
let name = self.exercise.valueForKey("name") as? String
let sets = self.exercise.valueForKey("sets") as! Int
let reps = self.exercise.valueForKey("reps") as! Int
self.editNameEditText.text = name
self.editSetsSpinner.selectRow(sets-1, inComponent: 0, animated: true)
self.editRepsSpinner.selectRow(reps-1, inComponent: 0, animated: true)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
@IBAction func editSaveButtonTouchDown(sender: UIButton) {
// Changes background color of button when clicked
sender.backgroundColor = UIColor(red: 0.050980393, green: 0.7411765, blue: 0.20392157, alpha: 1)
//TODO Implement the action
}
@IBAction func editSaveButtonTouchUpInside(sender: UIButton) {
// Restore original background color of button after click
sender.backgroundColor = UIColor(red: 0.03529412, green: 0.9411765, blue: 0.23529412, alpha: 1)
//TODO Implement the action
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
self.exercise.setValue(self.editNameEditText.text, forKey: "name")
self.exercise.setValue(self.numSets, forKey: "sets")
self.exercise.setValue(self.numReps, forKey: "reps")
do {
try managedContext.save()
} catch {
print("error")
}
navigationController?.popViewControllerAnimated(true)
}
@IBAction func editDeleteButtonTouchDown(sender: UIButton) {
// Changes background color of button when clicked
sender.backgroundColor = UIColor(red: 0.7019608, green: 0.019607844, blue: 0.019607844, alpha: 1)
//TODO Implement the action
}
@IBAction func editDeleteButtonTouchUpInside(sender: UIButton) {
// Restore original background color of button after click
sender.backgroundColor = UIColor(red: 0.8, green: 0.0, blue: 0.0, alpha: 1)
//TODO Implement the action
//Create the AlertController
let deleteExerciseDialog: UIAlertController = UIAlertController(title: "Delete Exercise", message: "Are you sure?", preferredStyle: .Alert)
//Create and add the Cancel action
let deleteExerciseDialogCancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Just dismiss the alert
}
//Create and add the Ok action
let deleteExerciseDialogOkAction: UIAlertAction = UIAlertAction(title: "Ok", style: .Default) { action -> Void in
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
managedContext.deleteObject(self.exercise)
do {
try managedContext.save()
} catch {
print("error")
}
self.navigationController?.popViewControllerAnimated(true)
}
deleteExerciseDialog.addAction(deleteExerciseDialogCancelAction)
deleteExerciseDialog.addAction(deleteExerciseDialogOkAction)
//Present the AlertController
self.presentViewController(deleteExerciseDialog, animated: true, completion: nil)
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == self.editRepsSpinner {
return editRepsSpinnerDataSource.count
}
if pickerView == self.editSetsSpinner {
return editSetsSpinnerDataSource.count
}
return 0
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == self.editRepsSpinner {
self.numReps = Int(editRepsSpinnerDataSource[row])!
return editRepsSpinnerDataSource[row]
}
if pickerView == self.editSetsSpinner {
self.numSets = Int(editSetsSpinnerDataSource[row])!
return editSetsSpinnerDataSource[row]
}
return nil
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == self.editRepsSpinner {
self.numReps = Int(editRepsSpinnerDataSource[row])!
}
if pickerView == self.editSetsSpinner {
self.numSets = Int(editSetsSpinnerDataSource[row])!
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
| gpl-3.0 | 7981098a4a451fb65e5e058da42acc73 | 35.543956 | 147 | 0.667268 | 4.733808 | false | false | false | false |
izandotnet/ULAQ | ULAQ/UnlockSkinManager.swift | 1 | 1011 | //
// UnlockSkinManager.swift
// ULAQ
//
// Created by Rohaizan Roosley on 07/05/2017.
// Copyright © 2017 Rohaizan Roosley. All rights reserved.
//
import Foundation
class UnlockSkinManager{
func getUnlocks()->Int{
let defaults = UserDefaults.standard
var value = defaults.integer(forKey: unlockConstant)
if value == 0 {
value = 1
defaults.set(value, forKey: unlockConstant)
}
return value
}
func increamentUnlock(){
if(self.getUnlocks() > 5){
}else{
let defaults = UserDefaults.standard
var value = defaults.integer(forKey: unlockConstant)
value += 1
defaults.set(value, forKey: unlockConstant)
}
}
func buyPremium(){
let defaults = UserDefaults.standard
defaults.set(true , forKey: premiumPurchaseConstant)
defaults.set(6, forKey: unlockConstant)
}
}
| mit | 11eea82cd413732241c85220458e87a7 | 21.444444 | 64 | 0.567327 | 4.391304 | false | false | false | false |
jevy-wangfei/FeedMeIOS | FeedMeIOS/Address.swift | 2 | 1540 | //
// Address.swift
// FeedMeIOS
//
// Created by Jun Chen on 28/03/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import Foundation
class Address {
var userName: String?
var addressLine1: String?
var addressLine2: String?
var suburb: String! = "Canberra"
var state: String! = "ACT"
var postcode: String?
var phone: String?
var selected: Bool! = false
init(userName: String?, addressLine1: String?, addressLine2: String?, postcode: String?, phone: String?, suburb: String?, state: String?, selected: Bool?) {
self.userName = userName
self.addressLine1 = addressLine1
self.addressLine2 = addressLine2
self.postcode = postcode
self.phone = phone
self.suburb = suburb
self.state = state
}
func toSimpleAddressString() -> String {
return addressLine1! + " " + addressLine2! + ", " + suburb + " " + state + " " + postcode!
}
func toFormattedString() -> String {
var formattedAddressString = userName!
formattedAddressString += ("\n" + addressLine1!)
formattedAddressString += ("\n" + addressLine2! + ", " + suburb + ", " + state + " " + postcode!)
formattedAddressString += ("\n" + phone!)
return formattedAddressString
}
func isSelected() -> Bool {
return self.selected
}
func setAsSelected() {
self.selected = true
}
func setAsDeselected() {
self.selected = false
}
}
| mit | d354de078ceb4616488b03952e9c6bc8 | 26 | 160 | 0.588044 | 4.159459 | false | false | false | false |
ivlevAstef/DITranquillity | Samples/SampleHabr/SampleHabr/App/AppDelegate.swift | 1 | 1093 | //
// AppDelegate.swift
// SampleHabr
//
// Created by Alexander Ivlev on 26/09/16.
// Copyright © 2016 Alexander Ivlev. All rights reserved.
//
import UIKit
import DITranquillity
func dilog(level: DILogLevel, msg: String) {
switch level {
case .error:
print("ERR: " + msg)
case .warning:
print("WRN: " + msg)
case .info:
print("INF: " + msg)
case .verbose, .none:
break
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
public func applicationDidFinishLaunching(_ application: UIApplication) {
DISetting.Log.fun = dilog
let container = DIContainer()
container.append(framework: AppFramework.self)
if !container.validate() {
fatalError()
}
container.initializeSingletonObjects()
window = UIWindow(frame: UIScreen.main.bounds)
let storyboard: UIStoryboard = container.resolve(name: "Main") // Получаем наш Main storyboard
window!.rootViewController = storyboard.instantiateInitialViewController()
window!.makeKeyAndVisible()
}
}
| mit | e07928fa9bd9be59440720f7ec6bf4aa | 21.520833 | 98 | 0.692877 | 4.079245 | false | false | false | false |
codebreaker01/Currency-Converter | CurrencyConverter/WebServices/WebServiceClient.swift | 1 | 2886 | //
// WebServiceClient.swift
// CurrencyConverter
//
// Created by Jaikumar Bhambhwani on 4/25/15.
// Copyright (c) 2015 Jaikumar Bhambhwani. All rights reserved.
//
import Foundation
import Alamofire
public class WebServiceClient {
// MARK: - Singleton Instance
static let sharedInstance = WebServiceClient()
// MARK: - Web Services
public func buildCurrencyList(completion:(() -> Void)?) {
if let currencySymbolSource = DataManager.sharedInstance.currencySymbolSource() {
// Get available Currency List
Alamofire.request(.GET, kURLForCurrencies)
.responseJSON { (_, _, availableCurrencyJSON, _) in
if let availableCurrency = availableCurrencyJSON as? Dictionary<String, String> {
DataManager.sharedInstance.aggregateCurrencyListDataSources(currencySymbolSource, availableCurrencySource: availableCurrency)
completion?()
}
}
}
}
public func getCurrencyRates(completion:(() -> Void)?) {
let params = [
"base" : "USD",
"apiKey" : kJSONRatesAPIKey
]
Alamofire.request(.GET, kURLForExchangeRate, parameters: params)
.responseJSON { (_, _, results, _) in
if let json = results as? Dictionary<String, AnyObject> {
if let rates = json["rates"] as? Dictionary<String, String> {
DataManager.sharedInstance.manageExchangeRates(json["base"] as! String, lastUpdated: json["utctime"] as! String, rates:rates)
DataManager.sharedInstance.aggregateCurrencyWithCurrencyRates()
completion?()
}
}
}
}
public func getHistoricalRates(from:NSString!, to:NSString!, start:NSDate!, end:NSDate!, completion:(() -> Void)?) {
let params = [
"from" : from,
"to" : to,
"dateStart" : start,
"dateEnd" : end,
"apiKey" : kJSONRatesAPIKey
]
Alamofire.request(.GET, kURLForHistoricalData, parameters: params)
.responseJSON { (_, _, results, _) in
if let json = results as? Dictionary<String, AnyObject> {
if let rates = json["rates"] as? Dictionary<String, String> {
DataManager.sharedInstance.manageHistoricalData(json["from"] as! String, to:json["to"] as! String, rates:rates)
completion?()
}
}
}
}
} | mit | 370a06cfbfdefee09626066ef85ea761 | 33.783133 | 149 | 0.510395 | 5.435028 | false | false | false | false |
hackersatcambridge/hac-website | Sources/HaCWebsiteLib/Views/Page.swift | 2 | 1765 | import HaCTML
import Foundation
struct Page: Nodeable {
let title: String
let postFixElements: Nodeable
let content: Nodeable
init(title: String = defaultTitle, postFixElements: Nodeable = Fragment(), content: Nodeable) {
self.title = title
self.postFixElements = postFixElements
self.content = content
}
public var node: Node {
return Fragment(
El.Doctype,
El.Html[Attr.lang => "en"].containing(
El.Head.containing(
El.Meta[Attr.charset => "UTF-8"],
El.Meta[Attr.name => "viewport", Attr.content => "width=device-width, initial-scale=1"],
El.Link[Attr.rel => "icon", Attr.type => "favicon/png", Attr.href => Assets.publicPath("/images/favicon.png")],
El.Title.containing(title),
Page.stylesheet(forUrl: Assets.publicPath("/styles/main.css")),
postFixElements
)
),
El.Body.containing(
errorReport,
content,
GAScript()
)
)
}
func render() -> String {
return node.render()
}
/// Get a view of the `swift build` output if it didn't exit with exit code zero
private var errorReport: Node? {
if let errorData = try? Data(contentsOf: URL(fileURLWithPath: "swift_build.log")) {
return Fragment(
El.Pre.containing(
El.Code[Attr.className => "BuildOutput__Error"].containing(String(data: errorData, encoding: String.Encoding.utf8) as String!)
)
)
} else {
return nil
}
}
private static let defaultTitle = "Cambridge's student tech society | Hackers at Cambridge"
public static func stylesheet(forUrl urlString: String) -> Node {
return El.Link[Attr.rel => "stylesheet", Attr.type => "text/css", Attr.href => urlString]
}
}
| mit | bbfeea59c76b9b2a4b68d271e775b940 | 29.431034 | 136 | 0.631161 | 3.957399 | false | false | false | false |
andersklenke/ApiModel | Source/Object+ApiModel.swift | 1 | 2913 | import Foundation
import RealmSwift
extension Object {
public class func localId() -> ApiId {
return "APIMODELLOCAL-\(NSUUID().UUIDString)"
}
public func isApiSaved() -> Bool {
if let pk = self.dynamicType.primaryKey() {
if let idValue = self[pk] as? String {
return !idValue.isEmpty
} else if let idValue = self[pk] as? Int {
return idValue != 0
} else {
return false
}
} else {
return false
}
}
public var isLocal: Bool {
get {
if let pk = self.dynamicType.primaryKey() {
if let id = self[pk] as? NSString {
return id.rangeOfString("APIMODELLOCAL-").location == 0
}
}
return false
}
}
public var unlocalId: ApiId {
get {
if isLocal {
return ""
} else if let
pk = self.dynamicType.primaryKey(),
id = self[pk] as? ApiId {
return id
} else {
return ""
}
}
}
public func modifyStoredObject(modifyingBlock: () -> ()) {
if let realm = realm {
realm.write(modifyingBlock)
} else {
modifyingBlock()
}
}
public func saveStoredObject() {
modifyStoredObject {}
}
public func removeEmpty(fieldsToRemoveIfEmpty: [String], var data: [String:AnyObject]) -> [String:AnyObject] {
for field in fieldsToRemoveIfEmpty {
if data[field] == nil {
data.removeValueForKey(field)
} else if let value = data[field] as? String where value.isEmpty {
data.removeValueForKey(field)
}
}
return data
}
public func apiRouteWithReplacements(url: String) -> String {
var pieces = url.componentsSeparatedByString(":")
var pathComponents: [String] = []
while pieces.count > 0 {
pathComponents.append(pieces.removeAtIndex(0))
if pieces.count == 0 {
break
}
let methodName = pieces.removeAtIndex(0)
if let value: AnyObject = self[methodName] {
pathComponents.append(value.description)
}
}
return "".join(pathComponents)
}
public func apiUrlForRoute(resource: String) -> String {
return "\(api().configuration.host)\(apiRouteWithReplacements(resource))"
}
/*
Not possible because calling methods on protocol types is not implmented yet.
public func apiUrlForRoute(resource: ApiRoutesAction) -> String {
let apiRoutes = (self.dynamicType as! ApiTransformable).dynamicType.apiRoutes()
return apiUrlForRoute(apiRoutes.getAction(resource))
}*/
}
| mit | 31e903321a3d86c1be91fde6e056bae6 | 27.841584 | 114 | 0.532441 | 4.97099 | false | false | false | false |
vasilyjp/tech_salon_ios_twitter_client | TwitterClient/Tweet.swift | 1 | 1143 | //
// Tweet.swift
// TwitterClient
//
// Created by Nicholas Maccharoli on 2016/09/26.
// Copyright © 2016 Vasily inc. All rights reserved.
//
import Foundation
struct Tweet {
let authorScreenName: String
let authorName: String
let tweetText: String
let profileImageURL: URL
let id: Int64
init?(dictionary: [String: AnyObject]) {
guard let user = dictionary["user"] as? NSDictionary else { return nil }
guard let screenName = user["screen_name"] as? String else { return nil }
guard let name = user["name"] as? String else { return nil }
guard let tweetText = dictionary["text"] as? String else { return nil }
guard let profileImageUrlString = user["profile_image_url_https"] as? String else { return nil }
guard let profileImageURL = URL(string: profileImageUrlString) else { return nil }
guard let id = (dictionary["id"] as? NSNumber)?.int64Value else { return nil }
self.authorScreenName = screenName
self.authorName = name
self.tweetText = tweetText
self.profileImageURL = profileImageURL
self.id = id
}
}
| mit | 56b4b524125d1d0280243dd23e013e66 | 33.606061 | 104 | 0.660245 | 4.358779 | false | false | false | false |
roambotics/swift | test/Constraints/array_literal.swift | 4 | 12818 | // RUN: %target-typecheck-verify-swift -disable-availability-checking
struct IntList : ExpressibleByArrayLiteral {
typealias Element = Int
init(arrayLiteral elements: Int...) {}
}
struct DoubleList : ExpressibleByArrayLiteral {
typealias Element = Double
init(arrayLiteral elements: Double...) {}
}
struct IntDict : ExpressibleByArrayLiteral {
typealias Element = (String, Int)
init(arrayLiteral elements: Element...) {}
}
final class DoubleDict : ExpressibleByArrayLiteral {
typealias Element = (String, Double)
init(arrayLiteral elements: Element...) {}
}
final class List<T> : ExpressibleByArrayLiteral {
typealias Element = T
init(arrayLiteral elements: T...) {}
}
final class Dict<K,V> : ExpressibleByArrayLiteral {
typealias Element = (K,V)
init(arrayLiteral elements: (K,V)...) {}
}
infix operator =>
func => <K, V>(k: K, v: V) -> (K,V) { return (k,v) }
func useIntList(_ l: IntList) {}
func useDoubleList(_ l: DoubleList) {}
func useIntDict(_ l: IntDict) {}
func useDoubleDict(_ l: DoubleDict) {}
func useList<T>(_ l: List<T>) {}
func useDict<K,V>(_ d: Dict<K,V>) {}
useIntList([1,2,3])
useIntList([1.0,2,3]) // expected-error{{cannot convert value of type 'Double' to expected element type 'Int'}}
useIntList([nil]) // expected-error {{'nil' is not compatible with expected element type 'Int'}}
useDoubleList([1.0,2,3])
useDoubleList([1.0,2.0,3.0])
useIntDict(["Niners" => 31, "Ravens" => 34])
useIntDict(["Niners" => 31, "Ravens" => 34.0]) // expected-error{{cannot convert value of type 'Double' to expected element type 'Int'}}
// <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands
useDoubleDict(["Niners" => 31, "Ravens" => 34.0])
useDoubleDict(["Niners" => 31.0, "Ravens" => 34])
useDoubleDict(["Niners" => 31.0, "Ravens" => 34.0])
// Generic slices
useList([1,2,3])
useList([1.0,2,3])
useList([1.0,2.0,3.0])
useDict(["Niners" => 31, "Ravens" => 34])
useDict(["Niners" => 31, "Ravens" => 34.0])
useDict(["Niners" => 31.0, "Ravens" => 34.0])
// Fall back to [T] if no context is otherwise available.
var a = [1,2,3]
var a2 : [Int] = a
var b = [1,2,3.0]
var b2 : [Double] = b
var arrayOfStreams = [1..<2, 3..<4]
struct MyArray : ExpressibleByArrayLiteral {
typealias Element = Double
init(arrayLiteral elements: Double...) {
}
}
var myArray : MyArray = [2.5, 2.5]
// Inference for tuple elements.
var x1 = [1]
x1[0] = 0
var x2 = [(1, 2)]
x2[0] = (3, 4)
var x3 = [1, 2, 3]
x3[0] = 4
func trailingComma() {
_ = [1, ]
_ = [1, 2, ]
_ = ["a": 1, ]
_ = ["a": 1, "b": 2, ]
}
func longArray() {
var _=["1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]
}
[1,2].map // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/25563498> Type checker crash assigning array literal to type conforming to ArrayProtocol
func rdar25563498<T : ExpressibleByArrayLiteral>(t: T) {
var x: T = [1] // expected-error {{cannot convert value of type 'Int' to expected element type 'T.ArrayLiteralElement'}}
}
func rdar25563498_ok<T : ExpressibleByArrayLiteral>(t: T) -> T
where T.ArrayLiteralElement : ExpressibleByIntegerLiteral {
let x: T = [1]
return x
}
class A { }
class B : A { }
class C : A { }
/// Check for defaulting the element type to 'Any' / 'Any?'.
func defaultToAny(i: Int, s: String) {
let a1 = [1, "a", 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: Int = a1 // expected-error{{value of type '[Any]'}}
let a2: Array = [1, "a", 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: Int = a2 // expected-error{{value of type '[Any]'}}
let a3 = [1, "a", nil, 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let _: Int = a3 // expected-error{{value of type '[Any?]'}}
let a4: Array = [1, "a", nil, 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let _: Int = a4 // expected-error{{value of type '[Any?]'}}
let a5 = []
// expected-error@-1{{empty collection literal requires an explicit type}}
let _: Int = a5 // expected-error{{value of type '[Any]'}}
let _: [Any] = []
let _: [Any] = [1, "a", 3.5]
let _: [Any] = [1, "a", [3.5, 3.7, 3.9]]
let _: [Any] = [1, "a", [3.5, "b", 3]]
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: [Any] = [1, [2, [3]]]
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
func f1() -> [Any] {
[]
}
let _: [Any?] = [1, "a", nil, 3.5]
let _: [Any?] = [1, "a", nil, [3.5, 3.7, 3.9]]
let _: [Any?] = [1, "a", nil, [3.5, "b", nil]]
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let _: [Any?] = [1, [2, [3]]]
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: [Any?] = [1, nil, [2, nil, [3]]]
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let a6 = [B(), C()]
let _: Int = a6 // expected-error{{value of type '[A]'}}
let a7: some Collection = [1, "Swift"]
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}} {{41-41= as [Any]}}
let _: (any Sequence)? = [1, "Swift"]
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: any Sequence = [1, nil, "Swift"]
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let _ = [1, true, ([], 1)]
// expected-error@-1 {{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
// expected-warning@-2 {{empty collection literal requires an explicit type}}
let _ = true ? [] : []
// expected-warning@-1{{empty collection literal requires an explicit type}}
let _ = (true, ([1, "Swift"]))
//expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _ = ([1, true])
//expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
func f2<T>(_: [T]) {}
func f3<T>() -> [T]? {}
f2([])
// expected-warning@-1{{empty collection literal requires an explicit type}}
f2([1, nil, ""])
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
_ = f3() ?? []
// expected-warning@-1{{empty collection literal requires an explicit type}}
}
func noInferAny(iob: inout B, ioc: inout C) {
var b = B()
var c = C()
let _ = [b, c, iob, ioc] // do not infer [Any] when elements are lvalues or inout
let _: [A] = [b, c, iob, ioc] // do not infer [Any] when elements are lvalues or inout
b = B()
c = C()
}
/// Check handling of 'nil'.
protocol Proto1 {}
protocol Proto2 {}
struct Nilable: ExpressibleByNilLiteral {
init(nilLiteral: ()) {}
}
func joinWithNil<T>(s: String, a: Any, t: T, m: T.Type, p: Proto1 & Proto2, arr: [Int], opt: Int?, iou: Int!, n: Nilable) {
let a1 = [s, nil]
let _: Int = a1 // expected-error{{value of type '[String?]'}}
let a2 = [nil, s]
let _: Int = a2 // expected-error{{value of type '[String?]'}}
let a3 = ["hello", nil]
let _: Int = a3 // expected-error{{value of type '[String?]'}}
let a4 = [nil, "hello"]
let _: Int = a4 // expected-error{{value of type '[String?]'}}
let a5 = [(s, s), nil]
let _: Int = a5 // expected-error{{value of type '[(String, String)?]'}}
let a6 = [nil, (s, s)]
let _: Int = a6 // expected-error{{value of type '[(String, String)?]'}}
let a7 = [("hello", "world"), nil]
let _: Int = a7 // expected-error{{value of type '[(String, String)?]'}}
let a8 = [nil, ("hello", "world")]
let _: Int = a8 // expected-error{{value of type '[(String, String)?]'}}
let a9 = [{ $0 * 2 }, nil]
let _: Int = a9 // expected-error{{value of type '[((Int) -> Int)?]'}}
let a10 = [nil, { $0 * 2 }]
let _: Int = a10 // expected-error{{value of type '[((Int) -> Int)?]'}}
let a11 = [a, nil]
let _: Int = a11 // expected-error{{value of type '[Any?]'}}
let a12 = [nil, a]
let _: Int = a12 // expected-error{{value of type '[Any?]'}}
let a13 = [t, nil]
let _: Int = a13 // expected-error{{value of type '[T?]'}}
let a14 = [nil, t]
let _: Int = a14 // expected-error{{value of type '[T?]'}}
let a15 = [m, nil]
let _: Int = a15 // expected-error{{value of type '[T.Type?]'}}
let a16 = [nil, m]
let _: Int = a16 // expected-error{{value of type '[T.Type?]'}}
let a17 = [p, nil]
let _: Int = a17 // expected-error{{value of type '[(any Proto1 & Proto2)?]'}}
let a18 = [nil, p]
let _: Int = a18 // expected-error{{value of type '[(any Proto1 & Proto2)?]'}}
let a19 = [arr, nil]
let _: Int = a19 // expected-error{{value of type '[[Int]?]'}}
let a20 = [nil, arr]
let _: Int = a20 // expected-error{{value of type '[[Int]?]'}}
let a21 = [opt, nil]
let _: Int = a21 // expected-error{{value of type '[Int?]'}}
let a22 = [nil, opt]
let _: Int = a22 // expected-error{{value of type '[Int?]'}}
let a23 = [iou, nil]
let _: Int = a23 // expected-error{{value of type '[Int?]'}}
let a24 = [nil, iou]
let _: Int = a24 // expected-error{{value of type '[Int?]'}}
let a25 = [n, nil]
let _: Int = a25 // expected-error{{value of type '[Nilable]'}}
let a26 = [nil, n]
let _: Int = a26 // expected-error{{value of type '[Nilable]'}}
}
struct OptionSetLike : ExpressibleByArrayLiteral {
typealias Element = OptionSetLike
init() { }
init(arrayLiteral elements: OptionSetLike...) { }
static let option: OptionSetLike = OptionSetLike()
}
func testOptionSetLike(b: Bool) {
let _: OptionSetLike = [ b ? [] : OptionSetLike.option, OptionSetLike.option]
let _: OptionSetLike = [ b ? [] : .option, .option]
}
// Join of class metatypes - <rdar://problem/30233451>
class Company<T> {
init(routes: [() -> T]) { }
}
class Person { }
class Employee: Person { }
class Manager: Person { }
let routerPeople = Company(
routes: [
{ () -> Employee.Type in
_ = ()
return Employee.self
},
{ () -> Manager.Type in
_ = ()
return Manager.self
}
]
)
// Same as above but with existentials
protocol Fruit {}
protocol Tomato : Fruit {}
struct Chicken : Tomato {}
protocol Pear : Fruit {}
struct Beef : Pear {}
let routerFruit = Company(
routes: [
{ () -> Tomato.Type in
_ = ()
return Chicken.self
},
{ () -> Pear.Type in
_ = ()
return Beef.self
}
]
)
// https://github.com/apple/swift/issues/46371
do {
let x: [Int] = [1, 2, 3]
// Infer '[[Int]]'.
// FIXME: As noted in the issue, this was the behavior in Swift 3, but
// it seems like the wrong choice and is less by design than by accident.
let _ = [x.reversed(), x]
}
// Conditional conformance
protocol P { }
struct PArray<T> { }
extension PArray : ExpressibleByArrayLiteral where T: P {
typealias ArrayLiteralElement = T
init(arrayLiteral elements: T...) { }
}
extension Int: P { }
func testConditional(i: Int, s: String) {
let _: PArray<Int> = [i, i, i]
let _: PArray<String> = [s, s, s] // expected-error{{cannot convert value of type '[String]' to specified type 'PArray<String>'}}
}
// https://github.com/apple/swift/issues/50912
do {
enum Enum: ExpressibleByStringLiteral {
case text(String)
init(stringLiteral value: String) {
self = .text(value)
}
}
let _: [Enum] = [Enum("hello")]
let _: [Enum] = [.text("hello")]
let _: [Enum] = ["hello", Enum.text("world")]
let _: [Enum] = ["hello", .text("world")]
}
struct TestMultipleOverloadedInits {
var x: Double
func foo() {
let _ = [Float(x), Float(x), Float(x), Float(x)]
}
}
| apache-2.0 | b7d20599dbbe1789b8b5b0e47c420957 | 30.493857 | 178 | 0.61398 | 3.229529 | false | false | false | false |
jlainog/Messages | Messages/Messages/ChannelFacade.swift | 1 | 1662 | //
// ChannelFacade.swift
// Messages
//
// Created by Gustavo Mario Londoño Correa on 3/10/17.
// Copyright © 2017 JLainoG. All rights reserved.
//
import Foundation
typealias ChannelListHandler = ( [Channel] ) -> Void
protocol ChannelServiceProtocol {
static func didRemoveChannel(completionHandler: @escaping (Channel) -> Void)
static func listAndObserveChannels(completionHandler: @escaping (Channel) -> Void)
static func dismmissChannelObservers()
static func create(channel: Channel)
static func delete(channel: Channel)
}
struct ChannelFacade: ChannelServiceProtocol {
static let nodeKey: String = "channels"
static let service = FireBaseService<Channel>()
static func listAndObserveChannels(completionHandler: @escaping (Channel) -> Void) {
service.listAndObserve(atNodeKey: nodeKey) { (firebaseObject) in
guard let newObject = firebaseObject else { return }
completionHandler(newObject as! Channel)
}
}
static func didRemoveChannel(completionHandler: @escaping (Channel) -> Void) {
service.didRemoveObject(atNodeKey: nodeKey) { (firebaseObject) in
guard let newObject = firebaseObject else { return }
completionHandler(newObject as! Channel)
}
}
static func create(channel: Channel) {
service.create(withNodeKey: nodeKey, object: channel)
}
static func delete(channel: Channel) {
service.delete(withNodeKey: nodeKey, object: channel)
}
internal static func dismmissChannelObservers() {
service.dismmissObservers()
}
}
| mit | 685a2f8ffb23382eaa499e7e235fad56 | 30.320755 | 88 | 0.677108 | 4.474394 | false | false | false | false |
XWJACK/Music | Music/Modules/Center/MusicCenterViewController.swift | 1 | 4615 | //
// MusicCenterViewController.swift
// Music
//
// Created by Jack on 5/3/17.
// Copyright © 2017 Jack. All rights reserved.
//
import UIKit
class MusicCenterViewController: MusicTableViewController {
private var dataSources: [(title: String, image: UIImage?, clouse: ((IndexPath) -> ())?)] = []
private var isCalculating: Bool = false
private var cache: String = ""
private let cacheIndexPath: IndexPath = IndexPath(row: 0, section: 0)
override func viewDidLoad() {
super.viewDidLoad()
title = "Center"
musicNavigationBar.leftButton.isHidden = true
tableView.register(MusicTableViewCell.self, forCellReuseIdentifier: MusicTableViewCell.reuseIdentifier)
tableView.register(MusicCenterClearCacheTableViewCell.self, forCellReuseIdentifier: MusicCenterClearCacheTableViewCell.reuseIdentifier)
dataSources = [("Clear Cache", #imageLiteral(resourceName: "center_delete"), clearCache),
("About", #imageLiteral(resourceName: "center_about"), about),
("Regist Server", #imageLiteral(resourceName: "center_registe"), registe)]
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard !isCalculating else { return }
isCalculating = true
tableView.reloadRows(at: [cacheIndexPath], with: .none)
MusicFileManager.default.calculateCache {
self.isCalculating = false
self.cache = ByteCountFormatter.string(fromByteCount: $0, countStyle: .binary)
self.tableView.reloadRows(at: [self.cacheIndexPath], with: .none)
}
}
private func clearCache(_ indexPath: IndexPath) {
guard let cell = self.tableView.cellForRow(at: indexPath) as? MusicCenterClearCacheTableViewCell else { return }
cell.indicator.isHidden = false
MusicFileManager.default.clearCache {
self.cache = "Zero KB"
cell.indicator.isHidden = true
cell.cacheLabel.text = self.cache
}
}
private func about(_ indexPath: IndexPath) {
}
private func registe(_ indexPath: IndexPath) {
let controller = UIAlertController(title: "Register", message: nil, preferredStyle: .alert)
controller.addTextField { (textField) in
textField.placeholder = "Your server Address"
textField.keyboardType = .asciiCapable
}
controller.addAction(UIAlertAction(title: "Registe", style: .default, handler: { (action) in
guard let baseURLString = controller.textFields?.first?.text else { return }
API.baseURLString = baseURLString
self.tableView.reloadData()
}))
controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(controller, animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSources.count - (API.baseURLString == nil ? 0 : 1)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
super.tableView(tableView, didSelectRowAt: indexPath)
dataSources[indexPath.row].clouse?(indexPath)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let block: (MusicTableViewCell) -> () = {
$0.indexPath = indexPath
$0.leftPadding = 50
$0.textLabel?.text = self.dataSources[indexPath.row].title
$0.textLabel?.textColor = .white
$0.imageView?.image = self.dataSources[indexPath.row].image
$0.imageView?.tintColor = .black
}
if indexPath == cacheIndexPath {
let cell = tableView.dequeueReusableCell(withIdentifier: MusicCenterClearCacheTableViewCell.reuseIdentifier, for: indexPath) as! MusicCenterClearCacheTableViewCell
block(cell)
cell.indicator.isHidden = !isCalculating
if isCalculating { cell.indicator.startAnimating() }
else { cell.indicator.stopAnimating() }
cell.cacheLabel.text = cache
cell.cacheLabel.isHidden = isCalculating
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: MusicTableViewCell.reuseIdentifier, for: indexPath) as! MusicTableViewCell
block(cell)
return cell
}
}
}
| mit | 9f022c6582c1f4c0b1a856c50b150dca | 40.196429 | 175 | 0.642393 | 5.115299 | false | false | false | false |
kenwilcox/iOS8SwiftTodayExtension | iOS8SwiftTodayExtension WatchKit Extension/InterfaceController.swift | 1 | 1216 | //
// InterfaceController.swift
// iOS8SwiftTodayExtension WatchKit Extension
//
// Created by Kenneth Wilcox on 1/3/15.
// Copyright (c) 2015 Kenneth Wilcox. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet var versionLabel: WKInterfaceLabel!
@IBOutlet var bigText: WKInterfaceLabel!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
let os = NSProcessInfo().operatingSystemVersion
let version = "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)"
versionLabel.setText(version)
// Just trying to see how much text you can easily put in a label
var data = ""
for i in 1...100 {
data += "Some line or so \(i)\n"
if i % 5 == 0 {
data += "\n"
}
}
bigText.setText(data)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| mit | b91ac24d299a7c2546e488c95783e03b | 24.87234 | 86 | 0.675987 | 4.554307 | false | false | false | false |
caronae/caronae-ios | CaronaeUITests/CaronaeUITests.swift | 1 | 4812 | import XCTest
import SimulatorStatusMagic
class CaronaeUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
SDStatusBarManager.sharedInstance().timeString = "09:41"
SDStatusBarManager.sharedInstance().enableOverrides()
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
let app = XCUIApplication()
setupSnapshot(app)
app.launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
SDStatusBarManager.sharedInstance().disableOverrides()
}
func testTakeScreenshots() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let app = XCUIApplication()
let elementsQuery = app.scrollViews.otherElements
let navigationBar = app.navigationBars.firstMatch
let authenticateButton = elementsQuery.buttons["Entrar com universidade"]
_ = authenticateButton.waitForExistence(timeout: 5)
if !authenticateButton.exists {
// SignOut user
app.tabBars.buttons["Menu"].tap()
elementsQuery.buttons["Meu perfil"].tap()
elementsQuery.buttons["ButtonSignout"].tap()
app.collectionViews.cells["Sair"].tap()
}
snapshot("2_SignIn")
var didShowDialog = false
expectation(for: NSPredicate() { _, _ in
app.tap()
return didShowDialog
}, evaluatedWith: NSNull())
addUIInterruptionMonitor(withDescription: "Sign In") { alert -> Bool in
alert.buttons.element(boundBy: 1).tap()
didShowDialog = true
return true
}
authenticateButton.tap()
waitForExpectations(timeout: 15)
_ = app.tables.cells.element(boundBy: 0).waitForExistence(timeout: 10)
app.tables.cells.element(boundBy: 0).tap()
snapshot("3_Ride")
navigationBar.buttons["Chat"].tap()
snapshot("5_Chat")
navigationBar.buttons["Carona"].tap()
app.navigationBars.buttons.element(boundBy: 0).tap()
snapshot("0_AllRides")
app.tabBars.buttons["Minhas"].tap()
snapshot("4_MyRides")
navigationBar.children(matching: .button).element.tap()
fillCreateRide()
app.swipeDown()
snapshot("1_CreateRide")
}
private func fillCreateRide() {
let app = XCUIApplication()
let elementsQuery = app.scrollViews.otherElements
elementsQuery.buttons["Bairro"].tap()
app.tables.staticTexts["Zona Sul"].tap()
app.tables.staticTexts["Botafogo"].tap()
let referenceTextField = elementsQuery.textFields["Referência Ex: Shopping Tijuca"]
referenceTextField.tap()
referenceTextField.typeText("Samaritano")
let routeTextField = elementsQuery.textFields["Rota Ex: Maracanã, Leopoldina, Linha Vermelha"]
routeTextField.tap()
routeTextField.typeText("Túnel Santa Barbara, Linha Vermelha")
elementsQuery.buttons["Centro Universitário"].tap()
app.tables.staticTexts["Cidade Universitária"].tap()
app.tables.staticTexts["CCMN"].tap()
app.swipeUp()
let increaseSlotsButton = elementsQuery.steppers.buttons.element(boundBy: 1)
increaseSlotsButton.tap()
increaseSlotsButton.tap()
let descriptionTextView = elementsQuery.textViews["notes"]
descriptionTextView.tap()
descriptionTextView.typeText("Podemos combinar algum outro caminho.")
elementsQuery.buttons["Ter"].tap()
elementsQuery.buttons["Qui"].tap()
elementsQuery.buttons["date"].tap()
let pickerWheelsQuery = app.datePickers.pickerWheels
pickerWheelsQuery.element(boundBy: 1).adjust(toPickerWheelValue: "08")
pickerWheelsQuery.element(boundBy: 2).adjust(toPickerWheelValue: "00")
app.toolbars.buttons["OK"].tap()
}
}
| gpl-3.0 | 3e8670d5c8a6f78c28a7c2e8e9f561f5 | 35.12782 | 182 | 0.623517 | 4.858443 | false | true | false | false |
lukejmann/FBLA2017 | Pods/Presentr/Presentr/PresentrController.swift | 1 | 16045 | //
// PresentrPresentationController.swift
// OneUP
//
// Created by Daniel Lozano on 4/27/16.
// Copyright © 2016 Icalia Labs. All rights reserved.
//
import UIKit
/// Presentr's custom presentation controller. Handles the position and sizing for the view controller's.
class PresentrController: UIPresentationController, UIAdaptivePresentationControllerDelegate {
/// Presentation type must be passed in to make all the sizing and position decisions.
let presentationType: PresentationType
/// Should the presented controller dismiss on background tap.
let dismissOnTap: Bool
/// Should the presented controller dismiss on background Swipe.
let dismissOnSwipe: Bool
/// DismissSwipe direction
let dismissOnSwipeDirection: DismissSwipeDirection
/// Should the presented controller use animation when dismiss on background tap.
let dismissAnimated: Bool
/// How the presented view controller should respond in response to keyboard presentation.
let keyboardTranslationType: KeyboardTranslationType
/// The frame used for a current context presentation. If nil, normal presentation.
let contextFrameForPresentation: CGRect?
/// If contextFrameForPresentation is set, this handles what happens when tap outside context frame.
let shouldIgnoreTapOutsideContext: Bool
/// A custom background view to be added on top of the regular background view.
let customBackgroundView: UIView?
fileprivate var conformingPresentedController: PresentrDelegate? {
return presentedViewController as? PresentrDelegate
}
fileprivate var shouldObserveKeyboard: Bool {
return conformingPresentedController != nil ||
(keyboardTranslationType != .none && presentationType == .popup) // TODO: Work w/other types?
}
fileprivate var containerFrame: CGRect {
return contextFrameForPresentation ?? containerView?.bounds ?? CGRect()
}
fileprivate var keyboardIsShowing: Bool = false
// MARK: Background Views
fileprivate var chromeView = UIView()
fileprivate var backgroundView = PassthroughBackgroundView()
fileprivate var visualEffect: UIVisualEffect?
// MARK: Swipe gesture
fileprivate var presentedViewIsBeingDissmissed: Bool = false
fileprivate var presentedViewFrame: CGRect = CGRect.zero
fileprivate var presentedViewCenter: CGPoint = CGPoint.zero
// MARK: - Init
init(presentedViewController: UIViewController,
presentingViewController: UIViewController?,
presentationType: PresentationType,
roundCorners: Bool?,
cornerRadius: CGFloat,
dropShadow: PresentrShadow?,
dismissOnTap: Bool,
dismissOnSwipe: Bool,
dismissOnSwipeDirection: DismissSwipeDirection,
backgroundColor: UIColor,
backgroundOpacity: Float,
blurBackground: Bool,
blurStyle: UIBlurEffectStyle,
customBackgroundView: UIView?,
keyboardTranslationType: KeyboardTranslationType,
dismissAnimated: Bool,
contextFrameForPresentation: CGRect?,
shouldIgnoreTapOutsideContext: Bool) {
self.presentationType = presentationType
self.dismissOnTap = dismissOnTap
self.dismissOnSwipe = dismissOnSwipe
self.dismissOnSwipeDirection = dismissOnSwipeDirection
self.keyboardTranslationType = keyboardTranslationType
self.dismissAnimated = dismissAnimated
self.contextFrameForPresentation = contextFrameForPresentation
self.shouldIgnoreTapOutsideContext = shouldIgnoreTapOutsideContext
self.customBackgroundView = customBackgroundView
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
setupBackground(backgroundColor, backgroundOpacity: backgroundOpacity, blurBackground: blurBackground, blurStyle: blurStyle)
setupCornerRadius(roundCorners: roundCorners, cornerRadius: cornerRadius)
addDropShadow(shadow: dropShadow)
if dismissOnSwipe {
setupDismissOnSwipe()
}
if shouldObserveKeyboard {
registerKeyboardObserver()
}
}
// MARK: - Setup
private func setupDismissOnSwipe() {
let swipe = UIPanGestureRecognizer(target: self, action: #selector(presentedViewSwipe))
presentedViewController.view.addGestureRecognizer(swipe)
}
private func setupBackground(_ backgroundColor: UIColor, backgroundOpacity: Float, blurBackground: Bool, blurStyle: UIBlurEffectStyle) {
let tap = UITapGestureRecognizer(target: self, action: #selector(chromeViewTapped))
chromeView.addGestureRecognizer(tap)
if !shouldIgnoreTapOutsideContext {
let tap = UITapGestureRecognizer(target: self, action: #selector(chromeViewTapped))
backgroundView.addGestureRecognizer(tap)
}
if blurBackground {
visualEffect = UIBlurEffect(style: blurStyle)
} else {
chromeView.backgroundColor = backgroundColor.withAlphaComponent(CGFloat(backgroundOpacity))
}
}
private func setupCornerRadius(roundCorners: Bool?, cornerRadius: CGFloat) {
let shouldRoundCorners = roundCorners ?? presentationType.shouldRoundCorners
if shouldRoundCorners {
presentedViewController.view.layer.cornerRadius = cornerRadius
presentedViewController.view.layer.masksToBounds = true
} else {
presentedViewController.view.layer.cornerRadius = 0
}
}
private func addDropShadow(shadow: PresentrShadow?) {
guard let shadow = shadow else {
presentedViewController.view.layer.masksToBounds = true
presentedViewController.view.layer.shadowOpacity = 0
return
}
presentedViewController.view.layer.masksToBounds = false
if let shadowColor = shadow.shadowColor?.cgColor {
presentedViewController.view.layer.shadowColor = shadowColor
}
if let shadowOpacity = shadow.shadowOpacity {
presentedViewController.view.layer.shadowOpacity = shadowOpacity
}
if let shadowOffset = shadow.shadowOffset {
presentedViewController.view.layer.shadowOffset = shadowOffset
}
if let shadowRadius = shadow.shadowRadius {
presentedViewController.view.layer.shadowRadius = shadowRadius
}
}
fileprivate func registerKeyboardObserver() {
NotificationCenter.default.addObserver(self, selector: #selector(PresentrController.keyboardWasShown(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(PresentrController.keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}
fileprivate func removeObservers() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
}
// MARK: - UIPresentationController
extension PresentrController {
// MARK: Presentation
override var frameOfPresentedViewInContainerView: CGRect {
var presentedViewFrame = CGRect.zero
let containerBounds = containerFrame
let size = self.size(forChildContentContainer: presentedViewController, withParentContainerSize: containerBounds.size)
let origin: CGPoint
// If the Presentation Type's calculate center point returns nil
// this means that the user provided the origin, not a center point.
if let center = getCenterPointFromType() {
origin = calculateOrigin(center, size: size)
} else {
origin = getOriginFromType() ?? CGPoint(x: 0, y: 0)
}
presentedViewFrame.size = size
presentedViewFrame.origin = origin
return presentedViewFrame
}
override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize {
let width = getWidthFromType(parentSize)
let height = getHeightFromType(parentSize)
return CGSize(width: CGFloat(width), height: CGFloat(height))
}
override func containerViewWillLayoutSubviews() {
guard !keyboardIsShowing else {
return // prevent resetting of presented frame when the frame is being translated
}
chromeView.frame = containerFrame
presentedView!.frame = frameOfPresentedViewInContainerView
}
// MARK: Animation
override func presentationTransitionWillBegin() {
guard let containerView = containerView else {
return
}
setupBackgroundView()
backgroundView.frame = containerView.bounds
chromeView.frame = containerFrame
containerView.insertSubview(backgroundView, at: 0)
containerView.insertSubview(chromeView, at: 1)
if let customBackgroundView = customBackgroundView {
chromeView.addSubview(customBackgroundView)
}
var blurEffectView: UIVisualEffectView?
if visualEffect != nil {
let view = UIVisualEffectView()
view.frame = chromeView.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
chromeView.insertSubview(view, at: 0)
blurEffectView = view
} else {
chromeView.alpha = 0.0
}
guard let coordinator = presentedViewController.transitionCoordinator else {
chromeView.alpha = 1.0
return
}
coordinator.animate(alongsideTransition: { _ in
blurEffectView?.effect = self.visualEffect
self.chromeView.alpha = 1.0
}, completion: nil)
}
override func dismissalTransitionWillBegin() {
guard let coordinator = presentedViewController.transitionCoordinator else {
chromeView.alpha = 0.0
return
}
coordinator.animate(alongsideTransition: { _ in
self.chromeView.alpha = 0.0
}, completion: nil)
}
// MARK: - Animation Helper's
func setupBackgroundView() {
if shouldIgnoreTapOutsideContext {
backgroundView.shouldPassthrough = true
backgroundView.passthroughViews = presentingViewController.view.subviews
} else {
backgroundView.shouldPassthrough = false
backgroundView.passthroughViews = []
}
}
}
// MARK: - Sizing, Position
fileprivate extension PresentrController {
func getWidthFromType(_ parentSize: CGSize) -> Float {
guard let size = presentationType.size() else {
if case .dynamic = presentationType {
return Float(presentedViewController.view.systemLayoutSizeFitting(UILayoutFittingCompressedSize).width)
}
return 0
}
return size.width.calculateWidth(parentSize)
}
func getHeightFromType(_ parentSize: CGSize) -> Float {
guard let size = presentationType.size() else {
if case .dynamic = presentationType {
return Float(presentedViewController.view.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height)
}
return 0
}
return size.height.calculateHeight(parentSize)
}
func getCenterPointFromType() -> CGPoint? {
let containerBounds = containerFrame
let position = presentationType.position()
return position.calculateCenterPoint(containerBounds)
}
func getOriginFromType() -> CGPoint? {
let position = presentationType.position()
return position.calculateOrigin()
}
func calculateOrigin(_ center: CGPoint, size: CGSize) -> CGPoint {
let x: CGFloat = center.x - size.width / 2
let y: CGFloat = center.y - size.height / 2
return CGPoint(x: x, y: y)
}
}
// MARK: - Gesture Handling
extension PresentrController {
func chromeViewTapped(gesture: UIGestureRecognizer) {
guard dismissOnTap else {
return
}
guard conformingPresentedController?.presentrShouldDismiss?(keyboardShowing: keyboardIsShowing) ?? true else {
return
}
if gesture.state == .ended {
if shouldObserveKeyboard {
removeObservers()
}
presentingViewController.dismiss(animated: dismissAnimated, completion: nil)
}
}
func presentedViewSwipe(gesture: UIPanGestureRecognizer) {
guard dismissOnSwipe else {
return
}
guard conformingPresentedController?.presentrShouldDismiss?(keyboardShowing: keyboardIsShowing) ?? true else {
return
}
if gesture.state == .began {
presentedViewFrame = presentedViewController.view.frame
presentedViewCenter = presentedViewController.view.center
} else if gesture.state == .changed {
swipeGestureChanged(gesture: gesture)
} else if gesture.state == .ended || gesture.state == .cancelled {
swipeGestureEnded()
}
}
// MARK: Helper's
func swipeGestureChanged(gesture: UIPanGestureRecognizer) {
let amount = gesture.translation(in: presentedViewController.view)
let swipeBottom: Bool = (dismissOnSwipeDirection == .default) ? presentationType != .topHalf : dismissOnSwipeDirection == .bottom
let swipeTop: Bool = (dismissOnSwipeDirection == .default) ? presentationType == .topHalf : dismissOnSwipeDirection == .top
if swipeTop && amount.y > 0 {
return
} else if swipeBottom && amount.y < 0 {
return
}
var swipeLimit: CGFloat = 100
if swipeTop {
swipeLimit = -swipeLimit
}
presentedViewController.view.center = CGPoint(x: presentedViewCenter.x,
y: presentedViewCenter.y + amount.y)
let shouldDismiss = swipeTop ? (amount.y < swipeLimit) : ( amount.y > swipeLimit)
if shouldDismiss {
presentedViewIsBeingDissmissed = true
presentedViewController.dismiss(animated: dismissAnimated, completion: nil)
}
}
func swipeGestureEnded() {
guard !presentedViewIsBeingDissmissed else {
return
}
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 1,
options: [],
animations: {
self.presentedViewController.view.frame = self.presentedViewFrame
}, completion: nil)
}
}
// MARK: - Keyboard Handling
extension PresentrController {
func keyboardWasShown(notification: Notification) {
if let keyboardFrame = notification.keyboardEndFrame() {
let presentedFrame = frameOfPresentedViewInContainerView
let translatedFrame = keyboardTranslationType.getTranslationFrame(keyboardFrame: keyboardFrame, presentedFrame: presentedFrame)
if translatedFrame != presentedFrame {
UIView.animate(withDuration: notification.keyboardAnimationDuration() ?? 0.5, animations: {
self.presentedView?.frame = translatedFrame
})
}
keyboardIsShowing = true
}
}
func keyboardWillHide (notification: Notification) {
if keyboardIsShowing {
let presentedFrame = frameOfPresentedViewInContainerView
if self.presentedView?.frame != presentedFrame {
UIView.animate(withDuration: notification.keyboardAnimationDuration() ?? 0.5, animations: {
self.presentedView?.frame = presentedFrame
})
}
keyboardIsShowing = false
}
}
}
| mit | 9b780bd37e7cd9eb97bf1023ed8440f5 | 34.574279 | 165 | 0.668973 | 5.79415 | false | false | false | false |
zjjzmw1/speedxSwift | speedxSwift/Pods/RealmSwift/RealmSwift/LinkingObjects.swift | 3 | 18502 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
/// :nodoc:
/// Internal class. Do not use directly. Used for reflection and initialization
public class LinkingObjectsBase: NSObject, NSFastEnumeration {
internal var rlmResults: RLMResults
internal let objectClassName: String
internal let propertyName: String
init(results: RLMResults, fromClassName objectClassName: String, property propertyName: String) {
self.rlmResults = results
self.objectClassName = objectClassName
self.propertyName = propertyName
}
// MARK: Fast Enumeration
public func countByEnumeratingWithState(state: UnsafeMutablePointer<NSFastEnumerationState>,
objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>,
count len: Int) -> Int {
return Int(rlmResults.countByEnumeratingWithState(state,
objects: buffer,
count: UInt(len)))
}
}
/**
LinkingObjects is an auto-updating container type that represents a collection of objects that
link to a given object.
LinkingObjects can be queried with the same predicates as `List<T>` and `Results<T>`.
LinkingObjects always reflect the current state of the Realm on the current thread,
including during write transactions on the current thread. The one exception to
this is when using `for...in` enumeration, which will always enumerate over the
linking objects when the enumeration is begun, even if some of them are deleted or
modified to no longer link to the target object during the enumeration.
LinkingObjects can only be used as a property on `Object` models. The property must
be declared as `let` and cannot be `dynamic`.
*/
public final class LinkingObjects<T: Object>: LinkingObjectsBase {
/// Element type contained in this collection.
public typealias Element = T
// MARK: Properties
/// Returns the Realm these linking objects are associated with.
public var realm: Realm? { return rlmResults.attached ? Realm(rlmResults.realm) : nil }
/// Returns the number of objects in these linking objects.
public var count: Int { return Int(rlmResults.count) }
// MARK: Initializers
public init(fromType type: T.Type, property propertyName: String) {
let className = (T.self as Object.Type).className()
super.init(results: RLMResults.emptyDetachedResults(), fromClassName: className, property: propertyName)
}
/// Returns a human-readable description of the objects contained in these linking objects.
public override var description: String {
let type = "LinkingObjects<\(rlmResults.objectClassName)>"
return gsub("RLMResults <0x[a-z0-9]+>", template: type, string: rlmResults.description) ?? type
}
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not present.
- parameter object: The object whose index is being queried.
- returns: The index of the given object, or `nil` if the object is not present.
*/
public func indexOf(object: T) -> Int? {
return notFoundToNil(rlmResults.indexOfObject(unsafeBitCast(object, RLMObject.self)))
}
/**
Returns the index of the first object matching the given predicate,
or `nil` if no objects match.
- parameter predicate: The predicate to filter the objects.
- returns: The index of the first matching object, or `nil` if no objects match.
*/
public func indexOf(predicate: NSPredicate) -> Int? {
return notFoundToNil(rlmResults.indexOfObjectWithPredicate(predicate))
}
/**
Returns the index of the first object matching the given predicate,
or `nil` if no objects match.
- parameter predicateFormat: The predicate format string which can accept variable arguments.
- returns: The index of the first matching object, or `nil` if no objects match.
*/
public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? {
return notFoundToNil(rlmResults.indexOfObjectWithPredicate(NSPredicate(format: predicateFormat,
argumentArray: args)))
}
// MARK: Object Retrieval
/**
Returns the object at the given `index`.
- parameter index: The index.
- returns: The object at the given `index`.
*/
public subscript(index: Int) -> T {
get {
throwForNegativeIndex(index)
return unsafeBitCast(rlmResults[UInt(index)], T.self)
}
}
/// Returns the first object in the collection, or `nil` if empty.
public var first: T? { return unsafeBitCast(rlmResults.firstObject(), Optional<T>.self) }
/// Returns the last object in the collection, or `nil` if empty.
public var last: T? { return unsafeBitCast(rlmResults.lastObject(), Optional<T>.self) }
// MARK: KVC
/**
Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the
collection's objects.
- parameter key: The name of the property.
- returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the
collection's objects.
*/
public override func valueForKey(key: String) -> AnyObject? {
return rlmResults.valueForKey(key)
}
/**
Returns an Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the
collection's objects.
- parameter keyPath: The key path to the property.
- returns: Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the
collection's objects.
*/
public override func valueForKeyPath(keyPath: String) -> AnyObject? {
return rlmResults.valueForKeyPath(keyPath)
}
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key.
- warning: This method can only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property.
*/
public override func setValue(value: AnyObject?, forKey key: String) {
return rlmResults.setValue(value, forKey: key)
}
// MARK: Filtering
/**
Filters the collection to the objects that match the given predicate.
- parameter predicateFormat: The predicate format string which can accept variable arguments.
- returns: Results containing objects that match the given predicate.
*/
public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T> {
return Results<T>(rlmResults.objectsWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args)))
}
/**
Filters the collection to the objects that match the given predicate.
- parameter predicate: The predicate to filter the objects.
- returns: Results containing objects that match the given predicate.
*/
public func filter(predicate: NSPredicate) -> Results<T> {
return Results<T>(rlmResults.objectsWithPredicate(predicate))
}
// MARK: Sorting
/**
Returns `Results` with elements sorted by the given property name.
- parameter property: The property name to sort by.
- parameter ascending: The direction to sort by.
- returns: `Results` with elements sorted by the given property name.
*/
public func sorted(property: String, ascending: Bool = true) -> Results<T> {
return sorted([SortDescriptor(property: property, ascending: ascending)])
}
/**
Returns `Results` with elements sorted by the given sort descriptors.
- parameter sortDescriptors: `SortDescriptor`s to sort by.
- returns: `Results` with elements sorted by the given sort descriptors.
*/
public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> {
return Results<T>(rlmResults.sortedResultsUsingDescriptors(sortDescriptors.map { $0.rlmSortDescriptorValue }))
}
// MARK: Aggregate Operations
/**
Returns the minimum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on.
- returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection
is empty.
*/
public func min<U: MinMaxType>(property: String) -> U? {
return rlmResults.minOfProperty(property) as! U?
}
/**
Returns the maximum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on.
- returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection
is empty.
*/
public func max<U: MinMaxType>(property: String) -> U? {
return rlmResults.maxOfProperty(property) as! U?
}
/**
Returns the sum of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
- returns: The sum of the given property over all objects in the collection.
*/
public func sum<U: AddableType>(property: String) -> U {
return rlmResults.sumOfProperty(property) as AnyObject as! U
}
/**
Returns the average of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate average on.
- returns: The average of the given property over all objects in the collection, or `nil` if the collection
is empty.
*/
public func average<U: AddableType>(property: String) -> U? {
return rlmResults.averageOfProperty(property) as! U?
}
// MARK: Notifications
/**
Register a block to be called each time the LinkingObjects changes.
The block will be asynchronously called with the initial set of objects, and then
called again after each write transaction which changes either any of the
objects in the collection, or which objects are in the collection.
If an error occurs the block will be called with `nil` for the linkingObjects
parameter and a non-`nil` error. Currently the only errors that can occur are
when opening the Realm on the background worker thread fails.
At the time when the block is called, the LinkingObjects object will be fully
evaluated and up-to-date, and as long as you do not perform a write transaction
on the same thread or explicitly call realm.refresh(), accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be
delivered while the run loop is blocked by other activity. When
notifications can't be delivered instantly, multiple notifications may be
coalesced into a single notification. This can include the notification
with the initial results. For example, the following code performs a write
transaction immediately after adding the notification block, so there is no
opportunity for the initial notification to be delivered first. As a
result, the initial notification will reflect the state of the Realm after
the write transaction.
let dog = realm.objects(Dog).first!
let owners = dog.owners
print("owners.count: \(owners.count)") // => 0
let token = owners.addNotificationBlock { (owners, error) in
// Only fired once for the example
print("owners.count: \(owners.count)") // will only print "owners.count: 1"
}
try! realm.write {
realm.add(Person.self, value: ["name": "Mark", dogs: [dog]])
}
// end of runloop execution context
You must retain the returned token for as long as you want updates to continue
to be sent to the block. To stop receiving updates, call stop() on the token.
- warning: This method cannot be called during a write transaction, or when
the source realm is read-only.
- parameter block: The block to be called with the evaluated linking objects.
- returns: A token which must be held for as long as you want query results to be delivered.
*/
@available(*, deprecated=1, message="Use addNotificationBlock with changes")
@warn_unused_result(message="You must hold on to the NotificationToken returned from addNotificationBlock")
public func addNotificationBlock(block: (linkingObjects: LinkingObjects<T>?, error: NSError?) -> ())
-> NotificationToken {
return rlmResults.addNotificationBlock { results, changes, error in
if results != nil {
block(linkingObjects: self, error: nil)
} else {
block(linkingObjects: nil, error: error)
}
}
}
/**
Register a block to be called each time the LinkingObjects changes.
The block will be asynchronously called with the initial set of objects, and then
called again after each write transaction which changes either any of the
objects in the collection, or which objects are in the collection.
This version of this method reports which of the objects in the collection were
added, removed, or modified in each write transaction as indices within the
collection. See the RealmCollectionChange documentation for more information on
the change information supplied and an example of how to use it to update
a UITableView.
At the time when the block is called, the LinkingObjects object will be fully
evaluated and up-to-date, and as long as you do not perform a write transaction
on the same thread or explicitly call realm.refresh(), accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be
delivered while the run loop is blocked by other activity. When
notifications can't be delivered instantly, multiple notifications may be
coalesced into a single notification. This can include the notification
with the initial set of objects. For example, the following code performs a write
transaction immediately after adding the notification block, so there is no
opportunity for the initial notification to be delivered first. As a
result, the initial notification will reflect the state of the Realm after
the write transaction.
let dog = realm.objects(Dog).first!
let owners = dog.owners
print("owners.count: \(owners.count)") // => 0
let token = owners.addNotificationBlock { (changes: RealmCollectionChange) in
switch changes {
case .Initial(let owners):
// Will print "owners.count: 1"
print("owners.count: \(owners.count)")
break
case .Update:
// Will not be hit in this example
break
case .Error:
break
}
}
try! realm.write {
realm.add(Person.self, value: ["name": "Mark", dogs: [dog]])
}
// end of runloop execution context
You must retain the returned token for as long as you want updates to continue
to be sent to the block. To stop receiving updates, call stop() on the token.
- warning: This method cannot be called during a write transaction, or when
the source realm is read-only.
- parameter block: The block to be called with the evaluated linking objects and change information.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
@warn_unused_result(message="You must hold on to the NotificationToken returned from addNotificationBlock")
public func addNotificationBlock(block: (RealmCollectionChange<LinkingObjects> -> Void)) -> NotificationToken {
return rlmResults.addNotificationBlock { results, change, error in
block(RealmCollectionChange.fromObjc(self, change: change, error: error))
}
}
}
extension LinkingObjects: RealmCollectionType {
// MARK: Sequence Support
/// Returns a `GeneratorOf<T>` that yields successive elements in the results.
public func generate() -> RLMGenerator<T> {
return RLMGenerator(collection: rlmResults)
}
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return count }
/// :nodoc:
public func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) ->
NotificationToken {
let anyCollection = AnyRealmCollection(self)
return rlmResults.addNotificationBlock { _, change, error in
block(RealmCollectionChange.fromObjc(anyCollection, change: change, error: error))
}
}
}
| mit | 28cfd74607fc3293ce6cfcbcf58568e3 | 40.484305 | 119 | 0.681278 | 5.059338 | false | false | false | false |
pgherveou/PromiseKit | Swift Sources/UIViewController+Promise.swift | 1 | 5186 | import UIKit
import MessageUI.MFMailComposeViewController
import Social.SLComposeViewController
import AssetsLibrary.ALAssetsLibrary
class MFMailComposeViewControllerProxy: NSObject, MFMailComposeViewControllerDelegate, UINavigationControllerDelegate {
override init() {
super.init()
PMKRetain(self)
}
func mailComposeController(controller:MFMailComposeViewController!, didFinishWithResult result:Int, error:NSError!) {
if error != nil {
controller.reject(error)
} else {
controller.fulfill(result)
}
PMKRelease(self)
}
}
class UIImagePickerControllerProxy: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: NSDictionary!) {
picker.fulfill(info as NSDictionary?)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController!) {
picker.fulfill(nil as NSDictionary?)
}
}
class Resolver<T> {
let fulfiller: (T) -> Void
let rejecter: (NSError) -> Void
init(_ deferred: (Promise<T>, (T)->Void, (NSError)->Void)) {
(_, self.fulfiller, self.rejecter) = deferred
}
}
private var key = "PMKSomeString"
extension UIViewController {
public func fulfill<T>(value:T) {
let resolver = objc_getAssociatedObject(self, &key) as Resolver<T>
resolver.fulfiller(value)
}
public func reject(error:NSError) {
let resolver = objc_getAssociatedObject(self, &key) as Resolver<Any>;
resolver.rejecter(error)
}
public func promiseViewController<T>(vc: UIViewController, animated: Bool = true, completion:(Void)->() = {}) -> Promise<T> {
presentViewController(vc, animated:animated, completion:completion)
let deferred = Promise<T>.defer()
objc_setAssociatedObject(vc, &key, Resolver<T>(deferred), UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return deferred.promise.finally { () -> () in
self.dismissViewControllerAnimated(animated, completion:nil)
}
}
public func promiseViewController<T>(nc: UINavigationController, animated: Bool = false, completion:(Void)->() = {}) -> Promise<T> {
let vc = nc.viewControllers[0] as UIViewController
return promiseViewController(vc, animated: animated, completion: completion)
}
public func promiseViewController(vc: MFMailComposeViewController, animated: Bool = false, completion:(Void)->() = {}) -> Promise<Int> {
vc.delegate = MFMailComposeViewControllerProxy()
return promiseViewController(vc as UIViewController, animated: animated, completion: completion)
}
public func promiseViewController(vc: UIImagePickerController, animated: Bool = false, completion:()->() = {}) -> Promise<UIImage?> {
let delegate = UIImagePickerControllerProxy()
vc.delegate = delegate
PMKRetain(delegate)
return promiseViewController(vc as UIViewController, animated: animated, completion: completion).then{
(info: NSDictionary?) -> UIImage? in
return info?.objectForKey(UIImagePickerControllerOriginalImage) as UIImage?
}.finally {
PMKRelease(delegate)
}
}
public func promiseViewController(vc: UIImagePickerController, animated: Bool = false, completion:(Void)->() = {}) -> Promise<NSData?> {
let delegate = UIImagePickerControllerProxy()
vc.delegate = delegate
PMKRetain(delegate)
return promiseViewController(vc as UIViewController, animated: animated, completion: completion).then{
(info: NSDictionary?) -> Promise<NSData?> in
if info == nil { return Promise<NSData?>(value: nil) }
let url = info![UIImagePickerControllerReferenceURL] as NSURL
return Promise { (fulfill, reject) in
ALAssetsLibrary().assetForURL(url, resultBlock:{ asset in
let N = Int(asset.defaultRepresentation().size())
let bytes = UnsafeMutablePointer<UInt8>.alloc(N)
var error: NSError?
asset.defaultRepresentation().getBytes(bytes, fromOffset:0, length:N, error:&error)
if error != nil {
reject(error!)
} else {
let data = NSData(bytesNoCopy: bytes, length: N)
fulfill(data)
}
}, failureBlock:{
reject($0)
})
}
}.finally {
PMKRelease(delegate)
}
}
public func promiseViewController(vc: SLComposeViewController, animated: Bool = false, completion:(Void)->() = {}) -> Promise<SLComposeViewControllerResult> {
return Promise { (fulfill, reject) in
vc.completionHandler = { (result: SLComposeViewControllerResult) in
fulfill(result)
self.dismissViewControllerAnimated(animated, completion: nil)
}
self.presentViewController(vc, animated: animated, completion: completion)
}
}
}
| mit | b5174d3972e207a160068192d1b1cfda | 38.587786 | 162 | 0.644234 | 5.286442 | false | false | false | false |
artyom-stv/TextInputKit | TextInputKit/TextInputKit/Code/SpecializedTextInput/PhoneNumber/PhoneNumberKitLoader.swift | 1 | 3078 | //
// PhoneNumberKitLoader.swift
// TextInputKit
//
// Created by Artem Starosvetskiy on 13/01/2017.
// Copyright © 2017 Artem Starosvetskiy. All rights reserved.
//
import Foundation
import PhoneNumberKit
/// A `PhoneNumberKitLoader` incapsulates the logic of loading a `PhoneNumberKit` in background.
final class PhoneNumberKitLoader {
// MARK: Nested Types
/// A `Task` class represents a task for loading a `PhoneNumberKit` in background.
final class Task {
/// Waits for a `PhoneNumberKit` to be loaded.
///
/// - Returns: The loaded `PhoneNumberKit`.
func wait() -> PhoneNumberKit {
workItem?.wait()
workItem = nil
return phoneNumberKit!
}
fileprivate typealias CompletionHandler = (PhoneNumberKit) -> ()
fileprivate init(completion: CompletionHandler) {
workItem = DispatchWorkItem { [weak weakSelf = self] in
if let strongSelf = weakSelf {
let phoneNumberKit = PhoneNumberKit()
strongSelf.phoneNumberKit = phoneNumberKit
strongSelf.completion?(phoneNumberKit)
strongSelf.completion = nil
}
}
}
fileprivate func schedule(on queue: DispatchQueue) {
guard let workItem = workItem else {
return
}
queue.async(execute: workItem)
}
private var workItem: DispatchWorkItem?
private var phoneNumberKit: PhoneNumberKit?
private var completion: CompletionHandler?
}
// MARK: Shared Instance.
/// Holds a shared `PhoneNumberKitLoader`.
static let shared = PhoneNumberKitLoader()
// MARK: Properties
/// Creates a `CachedPhoneNumberKit`.
var cachedPhoneNumberKit: CachedPhoneNumberKit {
return loadingMutex.fastsync {
if let phoneNumberKit = cache.object {
return CachedPhoneNumberKit(phoneNumberKit)
}
else {
let task = startLoading()
return CachedPhoneNumberKit(task)
}
}
}
// MARK: Private Initializer
private init() {
self.queue = DispatchQueue.global(qos: .utility)
self.cache = ObjectCache<PhoneNumberKit>(queue: queue)
}
// MARK: Private Stored Properties
private let loadingMutex = PThreadMutex()
private let queue: DispatchQueue
private let cache: ObjectCache<PhoneNumberKit>
private var task: Task?
private func startLoading() -> Task {
if let currentTask = task {
return currentTask
}
let currentTask = Task(completion: { [weak weakSelf = self] phoneNumberKit in
if let strongSelf = weakSelf {
strongSelf.loadingMutex.fastsync {
strongSelf.cache.object = phoneNumberKit
}
}
})
currentTask.schedule(on: queue)
task = currentTask
return currentTask
}
}
| mit | 62b7157cb0170b35c7bb4126fe01c076 | 25.299145 | 96 | 0.594735 | 5.524237 | false | false | false | false |
lucasharding/antenna | tvOS/Controllers/RecordingsTableViewCell.swift | 1 | 2430 | //
// RecordingsTableViewCell.swift
// antenna
//
// Created by Lucas Harding on 2016-05-03.
// Copyright © 2016 Lucas Harding. All rights reserved.
//
import UIKit
class RecordingsTableViewCell : UITableViewCell {
@IBOutlet var channelImageView: UIImageView?
@IBOutlet var programImageView: UIImageView?
@IBOutlet var titleLabel: UILabel?
@IBOutlet var timesLabel: UILabel?
@IBOutlet var expiresLabel: UILabel?
@IBOutlet var descriptionLabel: UILabel?
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
super.didUpdateFocus(in: context, with: coordinator)
let focused = context.nextFocusedView == self
coordinator.addCoordinatedAnimations({
self.titleLabel?.isHighlighted = focused
self.timesLabel?.isHighlighted = focused
self.descriptionLabel?.isHighlighted = focused
self.expiresLabel?.isHighlighted = focused
}, completion: nil)
}
override func prepareForReuse() {
super.prepareForReuse()
self.imageView?.image = nil
}
func updateWithProgram(_ program: TVRecording?) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let timeFormatter = DateFormatter()
timeFormatter.timeStyle = .short
if let program = program {
if let imageURL = program.imageURL {
self.programImageView?.af_setImage(withURL: imageURL)
}
self.titleLabel?.text = program.title
self.timesLabel?.text = "\(dateFormatter.string(from: program.startDate as Date)) • \(timeFormatter.string(from: program.startDate as Date)) • \(Int(program.runtime / 60)) mins"
if program.isDVRScheduled == false && program.dvrExpiresAt != nil {
self.expiresLabel?.text = "Expires: \(dateFormatter.string(from: program.dvrExpiresAt! as Date))"
}
else {
self.expiresLabel?.text = nil
}
if program.episodeTitle.characters.count > 0 {
self.descriptionLabel?.text = "\(program.episodeTitle) - \(program.description)"
}
else {
self.descriptionLabel?.text = program.description
}
}
}
}
| gpl-3.0 | 4a1fd93f42a5021e777483e6e1fcb2b6 | 34.661765 | 189 | 0.616495 | 5.226293 | false | false | false | false |
LuizZak/TaskMan | TaskMan/DateRange+JSON.swift | 1 | 1062 | //
// DateRange+JSON.swift
// TaskMan
//
// Created by Luiz Fernando Silva on 07/12/16.
// Copyright © 2016 Luiz Fernando Silva. All rights reserved.
//
import Cocoa
import SwiftyJSON
extension DateRange: JsonInitializable, JsonSerializable {
init(json: JSON) throws {
try self.startDate = json[JsonKey.startDate].tryParseDate(withFormatter: rfc3339DateTimeFormatter)
try self.endDate = json[JsonKey.endDate].tryParseDate(withFormatter: rfc3339DateTimeFormatter)
}
func serialize() -> JSON {
var dict: [JsonKey: Any] = [:]
dict[.startDate] = rfc3339StringFrom(date: startDate)
dict[.endDate] = rfc3339StringFrom(date: endDate)
return dict.mapToJSON()
}
}
extension DateRange {
/// Inner enum containing the JSON key names for the model
enum JsonKey: String, JSONSubscriptType {
case startDate = "start_date"
case endDate = "end_date"
var jsonKey: JSONKey {
return JSONKey.key(self.rawValue)
}
}
}
| mit | cc49efabb679d655c22d250bc0305dd8 | 26.205128 | 106 | 0.645617 | 4.244 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Library/Extensions/UIImage.swift | 1 | 1004 | //
// UIImage.swift
// MEGameTracker
//
// Created by Emily Ivie on 9/3/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import UIKit
extension UIImage {
/// Interface Builder can't find image files when they are created via code.
/// So, specify a class in the same package as the image file (here, AppDelegate), and IB will show the image.
public static func ibSafeImage(named name: String) -> UIImage? {
return UIImage(named: name, in: Bundle(for: AppDelegate.self), compatibleWith: nil)
}
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let cgImage = image?.cgImage {
self.init(cgImage: cgImage)
} else {
return nil
}
}
}
| mit | edce07e71dd14258032a90f92b09189b | 30.34375 | 111 | 0.717846 | 3.714815 | false | false | false | false |
AckeeCZ/ACKategories | ACKategoriesExample/Screens/MapView/MapViewModel.swift | 1 | 1112 | //
// MapViewModel.swift
// ACKategories-Example
//
// Created by Vendula Švastalová on 29/11/2019.
// Copyright © 2019 Ackee, s.r.o. All rights reserved.
//
import ACKategories
import CoreLocation
import MapKit
protocol MapViewModelingActions {
}
protocol MapViewModeling {
var annotations: [MKAnnotation] { get }
}
extension MapViewModeling where Self: MapViewModelingActions {
var actions: MapViewModelingActions { return self }
}
final class MapViewModel: Base.ViewModel, MapViewModeling, MapViewModelingActions {
private let coordinates: [CLLocationCoordinate2D] = [
CLLocationCoordinate2D(latitude: 49.997441, longitude: 14.187523),
CLLocationCoordinate2D(latitude: 50.109445, longitude: 14.357311),
CLLocationCoordinate2D(latitude: 50.075125, longitude: 14.568965)
]
lazy var annotations: [MKAnnotation] = coordinates.map {
let annotation = MKPointAnnotation()
annotation.coordinate = $0
annotation.title = "lat: \(annotation.coordinate.latitude), lon: \(annotation.coordinate.longitude)"
return annotation
}
}
| mit | c4b6bd0daa5d0b842306699c54fa1123 | 28.184211 | 108 | 0.726781 | 3.97491 | false | false | false | false |
mitchtreece/Spider | Spider/Classes/Core/Request/Headers.swift | 1 | 5044 | //
// Headers.swift
// Spider-Web
//
// Created by Mitch Treece on 11/2/19.
//
import Foundation
/// A configurable HTTP request header.
public struct Headers {
/// Representation of the various header content types.
public enum ContentType: Equatable {
/// An application/json content type.
case app_json
/// An application/javascript content type.
case app_js
/// A text/plain content type.
case text
/// An text/html content type.
case text_html
/// A text/json content type.
case text_json
/// A text/javascript content type.
case text_js
/// An image/png content type.
case image_png
/// An image/jpeg content type.
case image_jpeg
/// An custom content type.
case custom(String)
/// The content type's raw value.
public var value: String {
switch self {
case .app_json: return "application/json"
case .app_js: return "application/javascript"
case .text: return "text/plain"
case .text_html: return "text/html"
case .text_json: return "text/json"
case .text_js: return "text/javascript"
case .image_png: return "image/png"
case .image_jpeg: return "image/jpeg"
case .custom(let type): return type
}
}
}
/// The HTTP content type.
public var contentType: ContentType?
/// Array of acceptable content types supported by a request.
///
/// If none are provided, the request will accept _all_ content types.
public var acceptTypes: [ContentType]?
internal private(set) var customFields = [String: String]()
/// Initializes HTTP request headers.
/// - Parameter content: An optional header content type.
/// - Parameter accept: Optional header accept types.
/// - Parameter fields: An optional custom header fields object.
public init(content: ContentType?,
accept: [ContentType]?,
fields: [String: String]?) {
self.contentType = content
self.acceptTypes = accept
for (key, value) in fields ?? [:] {
set(value: value, forField: key)
}
}
public init() {
//
}
/// Sets the value of a given HTTP header field.
/// - Parameter value: The HTTP header value
/// - Parameter field: The HTTP header field
public mutating func set(value: String, forField field: String) {
self.customFields[field] = value
}
/// Creates a new set of headers by merging another set into the receiver.
/// - parameter headers: The set of headers to merge in.
/// - returns: A new set of headers.
public func merged(with headers: Headers) -> Headers {
let contentType = headers.contentType ?? self.contentType
let acceptTypes = headers.acceptTypes ?? self.acceptTypes
var fields = self.customFields
for (key, value) in headers.customFields {
fields[key] = value
}
return Headers(
content: contentType,
accept: acceptTypes,
fields: fields
)
}
// MARK: Private
internal mutating func jsonifyAndPrepare(for request: Request, using spider: Spider) -> [String: String] {
var dictionary = [String: String]()
// Auth
if let auth = request.authorization {
dictionary[auth.field] = auth.headerValue
}
else if let sharedAuth = spider.authorization {
dictionary[sharedAuth.field] = sharedAuth.headerValue
}
// Content type
if let multipartRequest = request as? MultipartRequest {
let content = "multipart/form-data; boundary=\(multipartRequest.boundary)"
// Kinda weird to also mutate our object & update
// the content-type here.
self.contentType = .custom(content)
dictionary["Content-Type"] = content
}
else if let content = self.contentType?.value {
dictionary["Content-Type"] = content
}
// Accept types
if let acceptTypes = self.acceptTypes {
var string: String?
acceptTypes.forEach { type in
string = (string == nil) ? type.value : "\(string!), \(type.value)"
}
dictionary["Accept"] = string
}
// Custom fields
for (key, value) in self.customFields {
dictionary[key] = value
}
// Done
return dictionary
}
}
| mit | aa24b6f6d0e7534bd0bb5c0d3a1ef1d9 | 26.714286 | 110 | 0.534893 | 5.126016 | false | false | false | false |
SpectralDragon/LightRoute | Example/Source/ViewControllers/Main/AboutViewController.swift | 1 | 2958 | //
// AboutViewController.swift
// iOS Example
//
// Created by v.a.prusakov on 23/04/2018.
// Copyright © 2018 v.a.prusakov. All rights reserved.
//
import UIKit
final class AboutViewController: UIViewController, DismissObserver {
@IBOutlet private weak var tableView: UITableView!
@IBOutlet weak var footerSocialView: UIView!
fileprivate var items: [MainModel] = .about
@IBOutlet private var twitterSocial: SocialView!
@IBOutlet private var githubSocial: SocialView!
@IBOutlet private var mediumSocial: SocialView!
override func viewDidLoad() {
super.viewDidLoad()
self.setupTableView()
self.setupSocial()
self.tableView.tableFooterView = self.footerSocialView
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Fix little bug with table cell labels
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
// MARK: - Setup
func setupSocial() {
self.twitterSocial.configure(social: .twitter)
self.githubSocial.configure(social: .github)
self.mediumSocial.configure(social: .medium)
}
func setupTableView() {
self.tableView.estimatedRowHeight = 150
self.tableView.contentInset = .init(top: 16, left: 0, bottom: 16, right: 0)
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.registerCell(MainTableViewCell.self)
}
// MARK: - DismissObserver
func presentedViewDidDismiss() {
guard let selectedIndex = self.tableView.indexPathForSelectedRow else { return }
self.tableView.deselectRow(at: selectedIndex, animated: true)
}
}
// MARK: - UITableViewDelegate
extension AboutViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indentifier = self.items[indexPath.row].transitionId
try? self.forSegue(identifier: indentifier, to: UIViewController.self).then { controller in
(controller as? DismissSender)?.dismissListner = self
return nil
}
}
}
// MARK: - UITableViewDataSource
extension AboutViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: MainTableViewCell.reuseIdentifier, for: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let item = self.items[indexPath.row]
(cell as? MainTableViewCell)?.configure(with: item)
}
}
| mit | f0f625702f10f39e9a1b066d1782ae34 | 31.855556 | 112 | 0.683125 | 4.91196 | false | false | false | false |
jhend11/Coinvert | Coinvert/QRCodeReader/SwitchCameraButton.swift | 1 | 7375 | /*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
@IBDesignable class SwitchCameraButton: UIButton {
@IBInspectable var edgeColor: UIColor = UIColor.whiteColor() {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var fillColor: UIColor = UIColor.darkGrayColor() {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var edgeHighlightedColor: UIColor = UIColor.whiteColor()
@IBInspectable var fillHighlightedColor: UIColor = UIColor.blackColor()
override func drawRect(rect: CGRect) {
let width = rect.width
let height = rect.height
let center = width / 2
let middle = height / 2
let strokeLineWidth = CGFloat(2)
// Colors
let paintColor = (self.state != .Highlighted) ? fillColor : fillHighlightedColor
let strokeColor = (self.state != .Highlighted) ? edgeColor : edgeHighlightedColor
// Camera box
let cameraWidth = width * 0.4
let cameraHeight = cameraWidth * 0.6
let cameraX = center - cameraWidth / 2
let cameraY = middle - cameraHeight / 2
let cameraRadius = cameraWidth / 80
let boxPath = UIBezierPath(roundedRect: CGRectMake(cameraX, cameraY, cameraWidth, cameraHeight), cornerRadius: cameraRadius)
// Camera lens
let outerLensSize = cameraHeight * 0.8
let outerLensX = center - outerLensSize / 2
let outerLensY = middle - outerLensSize / 2
let innerLensSize = outerLensSize * 0.7
let innerLensX = center - innerLensSize / 2
let innerLensY = middle - innerLensSize / 2
let outerLensPath = UIBezierPath(ovalInRect: CGRectMake(outerLensX, outerLensY, outerLensSize, outerLensSize))
let innerLensPath = UIBezierPath(ovalInRect: CGRectMake(innerLensX, innerLensY, innerLensSize, innerLensSize))
// Draw flash box
let flashBoxWidth = cameraWidth * 0.8
let flashBoxHeight = cameraHeight * 0.17
let flashBoxDeltaWidth = flashBoxWidth * 0.14
let flashLeftMostX = cameraX + (cameraWidth - flashBoxWidth) * 0.5
let flashBottomMostY = cameraY
let flashPath = UIBezierPath()
flashPath.moveToPoint(CGPointMake(flashLeftMostX, flashBottomMostY))
flashPath.addLineToPoint(CGPointMake(flashLeftMostX + flashBoxWidth, flashBottomMostY))
flashPath.addLineToPoint(CGPointMake(flashLeftMostX + flashBoxWidth - flashBoxDeltaWidth, flashBottomMostY - flashBoxHeight))
flashPath.addLineToPoint(CGPointMake(flashLeftMostX + flashBoxDeltaWidth, flashBottomMostY - flashBoxHeight))
flashPath.closePath()
flashPath.lineCapStyle = kCGLineCapRound
flashPath.lineJoinStyle = kCGLineJoinRound
// Arrows
let arrowHeadHeigth = cameraHeight * 0.5
let arrowHeadWidth = ((width - cameraWidth) / 2) * 0.3
let arrowTailHeigth = arrowHeadHeigth * 0.6
let arrowTailWidth = ((width - cameraWidth) / 2) * 0.7
// Draw left arrow
let arrowLeftX = center - cameraWidth * 0.2
let arrowLeftY = middle + cameraHeight * 0.45
let leftArrowPath = UIBezierPath()
leftArrowPath.moveToPoint(CGPointMake(arrowLeftX, arrowLeftY))
leftArrowPath.addLineToPoint(CGPointMake(arrowLeftX - arrowHeadWidth, arrowLeftY - arrowHeadHeigth / 2))
leftArrowPath.addLineToPoint(CGPointMake(arrowLeftX - arrowHeadWidth, arrowLeftY - arrowTailHeigth / 2))
leftArrowPath.addLineToPoint(CGPointMake(arrowLeftX - arrowHeadWidth - arrowTailWidth, arrowLeftY - arrowTailHeigth / 2))
leftArrowPath.addLineToPoint(CGPointMake(arrowLeftX - arrowHeadWidth - arrowTailWidth, arrowLeftY + arrowTailHeigth / 2))
leftArrowPath.addLineToPoint(CGPointMake(arrowLeftX - arrowHeadWidth, arrowLeftY + arrowTailHeigth / 2))
leftArrowPath.addLineToPoint(CGPointMake(arrowLeftX - arrowHeadWidth, arrowLeftY + arrowHeadHeigth / 2))
// Right arrow
let arrowRightX = center + cameraWidth * 0.2
let arrowRightY = middle + cameraHeight * 0.60
let rigthArrowPath = UIBezierPath()
rigthArrowPath.moveToPoint(CGPointMake(arrowRightX, arrowRightY))
rigthArrowPath.addLineToPoint(CGPointMake(arrowRightX + arrowHeadWidth, arrowRightY - arrowHeadHeigth / 2))
rigthArrowPath.addLineToPoint(CGPointMake(arrowRightX + arrowHeadWidth, arrowRightY - arrowTailHeigth / 2))
rigthArrowPath.addLineToPoint(CGPointMake(arrowRightX + arrowHeadWidth + arrowTailWidth, arrowRightY - arrowTailHeigth / 2))
rigthArrowPath.addLineToPoint(CGPointMake(arrowRightX + arrowHeadWidth + arrowTailWidth, arrowRightY + arrowTailHeigth / 2))
rigthArrowPath.addLineToPoint(CGPointMake(arrowRightX + arrowHeadWidth, arrowRightY + arrowTailHeigth / 2))
rigthArrowPath.addLineToPoint(CGPointMake(arrowRightX + arrowHeadWidth, arrowRightY + arrowHeadHeigth / 2))
rigthArrowPath.closePath()
// Drawing
paintColor.setFill()
rigthArrowPath.fill()
strokeColor.setStroke()
rigthArrowPath.lineWidth = strokeLineWidth
rigthArrowPath.stroke()
paintColor.setFill()
boxPath.fill()
strokeColor.setStroke()
boxPath.lineWidth = strokeLineWidth
boxPath.stroke()
strokeColor.setFill()
outerLensPath.fill()
paintColor.setFill()
innerLensPath.fill()
paintColor.setFill()
flashPath.fill()
strokeColor.setStroke()
flashPath.lineWidth = strokeLineWidth
flashPath.stroke()
leftArrowPath.closePath()
paintColor.setFill()
leftArrowPath.fill()
strokeColor.setStroke()
leftArrowPath.lineWidth = strokeLineWidth
leftArrowPath.stroke()
}
// MARK: - UIResponder Methods
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
setNeedsDisplay()
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
setNeedsDisplay()
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
setNeedsDisplay()
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
super.touchesCancelled(touches, withEvent: event)
setNeedsDisplay()
}
} | lgpl-3.0 | 6dca58b376c1202e1771035951aa4a0e | 37.217617 | 129 | 0.726237 | 4.442771 | false | false | false | false |
jigneshsheth/Datastructures | DataStructure/DataStructure/ZigzagConversion.swift | 1 | 725 | //
// ZigzagConversion.swift
// DataStructure
//
// Created by Jigs Sheth on 11/8/21.
// Copyright © 2021 jigneshsheth.com. All rights reserved.
//
import Foundation
class ZigzagConversion {
static func zigzag(_ input:String, numOfRow:Int) -> String {
var s:[String] = []
for i in 0..<numOfRow{
s.append("")
}
let charArray = Array(input)
var counter = 0
var isIncrement = true
for char in charArray {
s[counter].append(String(char))
if isIncrement && counter < numOfRow - 1 {
counter += 1
}
if !isIncrement && counter > 0{
counter -= 1
}
if counter == numOfRow - 1 || counter == 0 {
isIncrement = !isIncrement
}
}
return s.joined()
}
}
| mit | 703c1fa7ef81ec973a97e11cc0c78e70 | 15.837209 | 61 | 0.603591 | 3.12069 | false | false | false | false |
343max/WorldTime | WorldTime/MinuteChangeNotifier.swift | 1 | 1166 | // Copyright 2014-present Max von Webel. All Rights Reserved.
import Foundation
protocol MinuteChangeNotifierDelegate: class {
func minuteDidChange(notifier: MinuteChangeNotifier)
}
class MinuteChangeNotifier {
var timer: Timer!
weak var delegate: MinuteChangeNotifierDelegate?
static func nextMinute(fromDate date: Date) -> Date {
let calendar = NSCalendar.current
var components = calendar.dateComponents([.era, .year, .month, .day, .hour, .minute], from: date as Date)
components.second = 0
components.minute = components.minute! + 1
return calendar.date(from: components)!
}
deinit {
timer.invalidate()
}
init(delegate: MinuteChangeNotifierDelegate) {
let date = MinuteChangeNotifier.nextMinute(fromDate: Date())
timer = Timer(fireAt: date as Date, interval: 60.0, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
self.delegate = delegate
}
@objc func timerFired(timer: Timer) {
self.delegate?.minuteDidChange(notifier: self)
}
}
| mit | 67b48148e90ebf2bba4fe4ce02d1d371 | 32.314286 | 136 | 0.689537 | 4.350746 | false | false | false | false |
playbasis/native-sdk-ios | PlaybasisSDK/Classes/PBForm/PBLeaderBoardForm.swift | 1 | 1282 | //
// PBLeaderBoardForm.swift
// Playbook
//
// Created by Médéric Petit on 6/24/2559 BE.
// Copyright © 2559 smartsoftasia. All rights reserved.
//
import UIKit
public enum PBLeaderBoardStatus:String {
case Join = "join"
case Finish = "finish"
}
public final class PBLeaderBoardForm: PBForm {
//Required
public var questId:String!
// Optional
public var completionElementId:String?
public var playerId:String?
public var offset:Int? = 0
public var limit:Int? = 20
public var status:PBLeaderBoardStatus?
override public func params() -> [String:String] {
var params:[String:String] = [:]
params["quest_id"] = questId!
if let mCompletionElementId = self.completionElementId {
params["completion_element_id"] = mCompletionElementId
}
if let mPlayedId = self.playerId {
params["player_id"] = mPlayedId
}
if let mOffset = self.offset {
params["offset"] = String(mOffset)
}
if let mLimit = self.limit {
params["limit"] = String(mLimit)
}
if let mStatus = self.status {
params["status"] = mStatus.rawValue
}
return params
}
}
| mit | c9b945f202f26df5d64a060101e7fb23 | 23.132075 | 66 | 0.590305 | 4.073248 | false | false | false | false |
willpowell8/UIDesignKit_iOS | UIDesignKit/Classes/Extensions/UINavigationController+UIDesign.swift | 1 | 11614 | //
// UINavigationController+UIDesign.swift
// Pods
//
// Created by Will Powell on 17/12/2016.
//
//
import UIKit
private var designKey: UInt8 = 9
extension UINavigationController {
@IBInspectable
public var DesignKey: String? {
get {
return objc_getAssociatedObject(self, &designKey) as? String
}
set(newValue) {
designClear()
objc_setAssociatedObject(self, &designKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
checkForDesignUpdate()
setupNotifications();
}
}
func designClear(){
NotificationCenter.default.removeObserver(self, name: UIDesign.LOADED, object: nil);
if let designKey = DesignKey, designKey.count > 0 {
let eventHighlight = "DESIGN_HIGHLIGHT_\(designKey)"
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: eventHighlight), object: nil);
let eventText = "DESIGN_UPDATE_\(designKey)"
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: eventText), object: nil);
}
}
func setupNotifications(){
NotificationCenter.default.addObserver(self, selector: #selector(updateDesignFromNotification), name: UIDesign.LOADED, object: nil)
if let designKey = DesignKey, designKey.count > 0 {
let eventHighlight = "DESIGN_HIGHLIGHT_\(designKey)"
NotificationCenter.default.addObserver(self, selector: #selector(designHighlight), name: NSNotification.Name(rawValue:eventHighlight), object: nil)
let eventText = "DESIGN_UPDATE_\(designKey)"
NotificationCenter.default.addObserver(self, selector: #selector(updateDesignFromNotification), name: NSNotification.Name(rawValue:eventText), object: nil)
}
}
@objc private func updateDesignFromNotification() {
if Thread.isMainThread {
self.checkForDesignUpdate()
}else{
DispatchQueue.main.async(execute: {
self.checkForDesignUpdate()
})
}
}
@objc public func designHighlight() {
}
private func checkForDesignUpdate(){
if let designKey = self.DesignKey, !designKey.isEmpty {
guard let design = UIDesign.get(designKey) else {
UIDesign.createKey(designKey, type:self.getType(), properties: self.getAvailableDesignProperties())
return;
}
if UIDesign.ignoreRemote == true {
return;
}
guard let data = design["data"] as? [AnyHashable: Any], let type = design["type"] as? String else{
return
}
if Thread.isMainThread {
self.updateDesign(type:type, data: data)
}else{
DispatchQueue.main.async(execute: {
self.updateDesign(type:type, data: data)
})
}
}
}
private func getAvailableDesignProperties() -> [String:Any] {
let data = [String:Any]();
return self.getDesignProperties(data: data);
}
@available(iOS 13.0, *)
func colorForTrait(color:UIColor?, trait:UIUserInterfaceStyle)->UIColor?{
guard color != nil else {
return nil
}
let view = UIView()
view.overrideUserInterfaceStyle = trait
view.backgroundColor = color
guard let c = view.layer.backgroundColor else {
return nil
}
let outputColor = UIColor(cgColor: c)
return outputColor
}
public func getDesignProperties(data:[String:Any]) -> [String:Any]{
var dataReturn = data;
if #available(iOS 13.0, *) {
var lightValue = ["type":"COLOR"]
var darkValue = ["type":"COLOR"]
if let lightColor = colorForTrait(color: self.navigationBar.barTintColor, trait: .light){
lightValue["value"] = lightColor.toHexString()
}
if let darkColor = colorForTrait(color: self.navigationBar.barTintColor, trait: .dark){
darkValue["value"] = darkColor.toHexString()
}
dataReturn["barTintColor"] = lightValue
dataReturn["barTintColor-dark"] = darkValue
}else{
dataReturn["barTintColor"] = ["type":"COLOR", "value":self.navigationBar.barTintColor?.toHexString()]
}
if #available(iOS 13.0, *) {
var lightValue = ["type":"COLOR"]
var darkValue = ["type":"COLOR"]
if let lightColor = colorForTrait(color: self.navigationBar.tintColor, trait: .light){
lightValue["value"] = lightColor.toHexString()
}
if let darkColor = colorForTrait(color: self.navigationBar.tintColor, trait: .dark){
darkValue["value"] = darkColor.toHexString()
}
dataReturn["barTintColor"] = lightValue
dataReturn["barTintColor-dark"] = darkValue
}else{
dataReturn["tintColor"] = ["type":"COLOR", "value":self.navigationBar.tintColor.toHexString()]
}
if #available(iOS 13.0, *) {
dataReturn["navigationTitleFontColor"] = ["type":"COLOR"]
dataReturn["navigationTitleFontColor-dark"] = ["type":"COLOR"]
}else{
dataReturn["navigationTitleFontColor"] = ["type":"COLOR"]
}
dataReturn["navigationTitleFont"] = ["type":"FONT"];
return dataReturn;
}
public func getType() -> String{
return "VIEW";
}
public func applyData(data:[AnyHashable:Any], property:String, targetType:UIDesignType, apply:@escaping (_ value: Any) -> Void){
if data[property] != nil {
let element = data[property] as! [AnyHashable: Any];
guard let elementTypeString = element["type"] as? String, let elementType = UIDesignType(rawValue:elementTypeString) else {
return;
}
if element["universal"] != nil && elementType == targetType {
var propertyForDeviceType:String = "universal";
if element[UIDesign.deviceType] != nil {
propertyForDeviceType = UIDesign.deviceType
}
switch(targetType){
case .color:
guard let value = element[propertyForDeviceType] as? String
else{
return;
}
if #available(iOS 13.0, *) {
if let darkDictionary = data["\(property)-dark"] as? [AnyHashable: Any], let darkValue = darkDictionary[propertyForDeviceType] as? String {
let adaptiveColor = UIColor { (traits) -> UIColor in
// Return one of two colors depending on light or dark mode
return traits.userInterfaceStyle == .dark ?
UIColor(fromHexString:darkValue) :
UIColor(fromHexString:value)
}
apply(adaptiveColor)
break
}
}
let color = UIColor(fromHexString:value)
apply(color)
break;
case .int:
guard let value = element[propertyForDeviceType] as? Int
else{
return;
}
apply(value);
break;
case .url:
guard let value = element[propertyForDeviceType] as? String else {
print("URL VALUE NOT STRING");
return;
}
if value != "<null>" {
guard let url = URL(string:value) else{
return;
}
apply(url);
}
break;
case .font:
guard let value = element[propertyForDeviceType] as? String else {
print("Font VALUE NOT STRING");
return;
}
let parts = value.components(separatedBy: "|")
if ( parts.count > 1 ) {
var size = CGFloat(9.0)
if parts.count > 2, let n = Float(parts[2]) {
size = CGFloat(n)
}
let descriptor = UIFontDescriptor(name: parts[0], size: size)
let font = UIFont(descriptor: descriptor, size: size);
apply(font);
}
break;
default:
break;
}
}else{
//print("Value is not configured correctly \(elementType)");
}
}else{
// NEED TO ADD PROPERTY
let properties = self.getAvailableDesignProperties()
if let propertyValue = properties[property], let designKey = self.DesignKey, !designKey.isEmpty {
UIDesign.addPropertyToKey(designKey, property: property, attribute: propertyValue)
}
}
if #available(iOS 13.0, *) {
if targetType == .color {
checkData(data: data, property: "\(property)-dark")
}
}
}
// used to check new components
public func checkData(data:[AnyHashable:Any], property:String){
if data[property] == nil {
let properties = self.getAvailableDesignProperties()
if let attribute = properties[property] {
UIDesign.addPropertyToKey(self.DesignKey!, property: property, attribute: attribute)
}
}
}
public func updateDesign(type:String, data:[AnyHashable: Any]) {
// OVERRIDE TO GO HERE FOR INDIVIDUAL CLASSES
self.applyData(data: data, property: "barTintColor", targetType: .color, apply: { (value) in
if let v = value as? UIColor {
self.navigationBar.barTintColor = v
}
})
self.applyData(data: data, property: "tintColor", targetType: .color, apply: { (value) in
if let v = value as? UIColor {
self.navigationBar.tintColor = v
}
})
self.applyData(data: data, property: "navigationTitleFontColor", targetType: .color, apply: { (value) in
if let v = value as? UIColor {
if self.navigationBar.titleTextAttributes == nil {
self.navigationBar.titleTextAttributes = [NSAttributedString.Key:Any]()
}
self.navigationBar.titleTextAttributes?[NSAttributedString.Key.foregroundColor] = v
}
})
self.applyData(data: data, property: "navigationTitleFont", targetType: .font, apply: { (value) in
if let v = value as? UIFont {
if self.navigationBar.titleTextAttributes == nil {
self.navigationBar.titleTextAttributes = [NSAttributedString.Key:Any]()
}
self.navigationBar.titleTextAttributes?[NSAttributedString.Key.font] = v
}
})
}
}
| mit | 69939666848fb71f7ee7ebc7351a6620 | 39.894366 | 167 | 0.530653 | 5.255204 | false | false | false | false |
siberianisaev/XcassetsCreator | XcassetsCreator/OpenPanel.swift | 1 | 1945 | //
// OpenPanel.swift
// XcassetsCreator
//
// Created by Andrey Isaev on 26.04.15.
// Copyright (c) 2015 Andrey Isaev. All rights reserved.
//
import Foundation
import Cocoa
class OpenPanel: NSObject {
class func open(_ onFinish: @escaping (([String]?) -> ())) {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.allowsMultipleSelection = true
panel.begin { (result) -> Void in
if result.rawValue == NSFileHandlingPanelOKButton {
var selected = [String]()
let fm = FileManager.default
for URL in panel.urls {
let path = URL.path
var isDirectory: ObjCBool = false
if fm.fileExists(atPath: path, isDirectory: &isDirectory) && isDirectory.boolValue {
selected.append(path)
selected += self.recursiveGetDirectoriesFromDirectory(path)
}
}
onFinish(selected)
}
}
}
class func recursiveGetDirectoriesFromDirectory(_ directoryPath: String) -> [String] {
var results = [String]()
let fm = FileManager.default
do {
let fileNames = try fm.contentsOfDirectory(atPath: directoryPath)
for fileName in fileNames {
let path = (directoryPath as NSString).appendingPathComponent(fileName)
var isDirectory: ObjCBool = false
if fm.fileExists(atPath: path, isDirectory: &isDirectory) {
if isDirectory.boolValue {
results.append(path)
results += recursiveGetDirectoriesFromDirectory(path)
}
}
}
} catch {
print(error)
}
return results
}
}
| mit | d08caf49df9989b211d38f1605432ec0 | 32.534483 | 104 | 0.533162 | 5.541311 | false | false | false | false |
benlangmuir/swift | test/Sema/dynamic_self_implicit_conversions.swift | 3 | 3112 | // RUN: %target-swift-frontend -typecheck -dump-ast %s | %FileCheck %s
// FIXME: Make this a SILGen test instead.
// Even though redundant conversions are eventually optimized away, test from
// the get-go that we build these implicit conversions only when necessary.
protocol P {}
class A {
required init() {}
func method() -> Self { self }
var property: Self { self }
subscript() -> Self { self }
static func staticMethod() -> Self { .init() }
static var staticProperty: Self { .init() }
static subscript() -> Self { .init() }
}
class B: A {
func test() -> Self {
// CHECK: covariant_return_conversion_expr implicit type='Self' location={{.*}}.swift:[[@LINE+1]]
_ = super.method()
// CHECK: covariant_function_conversion_expr implicit type='() -> Self' location={{.*}}.swift:[[@LINE+1]]
_ = super.method
// CHECK: covariant_return_conversion_expr implicit type='Self' location={{.*}}.swift:[[@LINE+1]]
_ = super.property
// CHECK: covariant_return_conversion_expr implicit type='Self' location={{.*}}.swift:[[@LINE+1]]
_ = super[]
return super.property
}
static func testStatic() -> Self {
// CHECK: covariant_return_conversion_expr implicit type='Self' location={{.*}}.swift:[[@LINE+1]]
_ = super.staticMethod()
// CHECK: covariant_function_conversion_expr implicit type='() -> Self' location={{.*}}.swift:[[@LINE+1]]
_ = super.staticMethod
// CHECK-NOT: function_conversion_expr {{.*}} location={{.*}}.swift:[[@LINE+3]]
// CHECK-NOT: covariant_function_conversion_expr {{.*}} location={{.*}}.swift:[[@LINE+2]]
// CHECK: covariant_return_conversion_expr implicit type='Self' location={{.*}}.swift:[[@LINE+1]]
_ = self.method
// CHECK: covariant_function_conversion_expr implicit type='() -> Self' location={{.*}}.swift:[[@LINE+1]]
_ = self.init
// CHECK: covariant_return_conversion_expr implicit type='Self' location={{.*}}.swift:[[@LINE+1]]
_ = self.init()
// CHECK: covariant_return_conversion_expr implicit type='Self' location={{.*}}.swift:[[@LINE+1]]
_ = super.staticProperty
// CHECK: covariant_return_conversion_expr implicit type='Self' location={{.*}}.swift:[[@LINE+1]]
_ = super[]
return super.staticProperty
}
}
func testOnExistential(arg: P & A) {
// FIXME: This could be a single conversion.
// CHECK: function_conversion_expr implicit type='() -> A & P' location={{.*}}.swift:[[@LINE+2]]
// CHECK-NEXT: covariant_function_conversion_expr implicit type='() -> A & P' location={{.*}}.swift:[[@LINE+1]]
_ = arg.method
}
class Generic<T> {}
extension Generic where T == Never {
func method() -> Self { self }
var property: Self { self }
subscript() -> Self { self }
func test() {
// CHECK-NOT: conversion_expr {{.*}} location={{.*}}.swift:{{[[@LINE+1]]|[[@LINE+2]]|[[@LINE+3]]|[[@LINE+4]]}}
_ = Generic().method()
_ = Generic().method
_ = Generic().property
_ = Generic()[]
}
}
final class Final {
static func useSelf(_ body: (Self) -> ()) {}
}
func testNoErasure(_ body: (Final) -> ()) {
return Final.useSelf(body)
}
| apache-2.0 | 3e2922f40db1db6a0fa9b4a33062f526 | 36.493976 | 114 | 0.620501 | 3.813725 | false | true | false | false |
satoshin21/Anima | Sources/AnimaNode.swift | 1 | 15099 | //
// AnimaNode.swift
// Pods
//
// Created by Satoshi Nagasaka on 2017/03/12.
//
//
import UIKit
internal enum NodeType {
case single(AnimaType)
case group([AnimaType])
case wait(TimeInterval)
case anchor(AnimaAnchorPoint)
}
internal struct AnimaNode {
let nodeType: NodeType
let options: [AnimaOption]
init(nodeType: NodeType, options: [AnimaOption] = []) {
self.nodeType = nodeType
self.options = options
}
func addAnimation(to layer: CALayer, animationDidStop: @escaping AnimationDidStop) {
switch nodeType {
case .single(let animationType):
if let animation = instantiateAnimaAnimation(animationType, layer: layer, animationDidStop: animationDidStop) {
layer.add(animation, forKey: "\(Date.timeIntervalSinceReferenceDate)")
}
case .group(let animations):
let animations = animations.compactMap({ (animaType) -> CAAnimation? in
let animation = instantiateAnimaAnimation(animaType, layer: layer, animationDidStop: {_ in })
animation?.delegate = nil
return animation
})
let group = AnimaAnimationGroup(options: options)
group.didStop = { (finished) in
animationDidStop(true)
}
if let groupDuration = options.first(where: {$0 == .duration(.nan)}), case let .duration(duration) = groupDuration {
animations.forEach({$0.duration = duration})
group.duration = duration
} else if let duration = animations.max(by: { $0.duration > $1.duration } )?.duration {
group.duration = duration
}
group.animations = animations
layer.add(group, forKey: nil)
case .anchor(let anchorPoint):
layer.position += layer.diffPoint(for: anchorPoint)
layer.anchorPoint = anchorPoint.anchorPoint
animationDidStop(true)
case .wait(let timeInterval):
let deadline: DispatchTime = .now() + timeInterval
DispatchQueue(label: "jp.hatenadiary.satoshin21.AnimaNode").asyncAfter(deadline: deadline, execute: {
DispatchQueue.main.async {
animationDidStop(true)
}
})
}
}
func instantiateAnimaAnimation(_ animationType: AnimaType, layer: CALayer, animationDidStop: @escaping AnimationDidStop) -> CAAnimation? {
switch animationType {
case .moveByX(let x):
return createTranslationAnimation(move: CGPoint(x: x, y: 0), layer: layer, animationDidStop: animationDidStop)
case .moveByY(let y):
return createTranslationAnimation(move: CGPoint(x: 0, y: y), layer: layer, animationDidStop: animationDidStop)
case .moveByXY(let x, let y):
return createTranslationAnimation(move: CGPoint(x: x, y: y), layer: layer, animationDidStop: animationDidStop)
case .moveTo(let x, let y):
let target = CGPoint(x: x, y: y)
let diffPoint = target - layer.position
let currentX: CGFloat = layer.currentValue(keyPath: "transform.translation.x")
let currentY: CGFloat = layer.currentValue(keyPath: "transform.translation.y")
let currentTranslation = CGPoint(x: currentX, y: currentY)
let lastPoint = diffPoint - currentTranslation
return createTranslationAnimation(move: lastPoint, layer: layer, animationDidStop: animationDidStop)
case .scaleByX(let x):
return createScaleAnimation(scale: x, layer: layer, animationDidStop: animationDidStop, scaleType: .x)
case .scaleByY(let y):
return createScaleAnimation(scale: y, layer: layer, animationDidStop: animationDidStop, scaleType: .y)
case .scaleBy(let scale):
return createScaleAnimation(scale: scale, layer: layer, animationDidStop: animationDidStop, scaleType: .default)
case .moveAnchor(let anchorPoint):
return createAnimation(keyPath: #keyPath(CALayer.anchorPoint),
from: layer.anchorPoint,
to: anchorPoint.anchorPoint,
layer: layer,
animationDidStop: animationDidStop)
case .backgroundColor(let color):
return createAnimation(keyPath: #keyPath(CALayer.backgroundColor),
from: layer.backgroundColor,
to: color.cgColor,
layer: layer,
animationDidStop: animationDidStop)
case .rotateByXRadian(let radian):
return createRotateAnimation(radian: radian, layer: layer, animationDidStop: animationDidStop, rotateType: .x)
case .rotateByXDegree(let degree):
return createRotateAnimation(radian: degree.degreesToRadians, layer: layer, animationDidStop: animationDidStop, rotateType: .x)
case .rotateByYRadian(let radian):
return createRotateAnimation(radian: radian, layer: layer, animationDidStop: animationDidStop, rotateType: .y)
case .rotateByYDegree(let degree):
return createRotateAnimation(radian: degree.degreesToRadians, layer: layer, animationDidStop: animationDidStop, rotateType: .y)
case .rotateByZRadian(let radian):
return createRotateAnimation(radian: radian, layer: layer, animationDidStop: animationDidStop, rotateType: .z)
case .rotateByZDegree(let degree):
return createRotateAnimation(radian: degree.degreesToRadians, layer: layer, animationDidStop: animationDidStop, rotateType: .z)
case .opacity(let opacity):
return createAnimation(keyPath: #keyPath(CALayer.opacity),
from: layer.opacity,
to: opacity,
layer: layer,
animationDidStop: animationDidStop)
case .borderColor(let color):
return createAnimation(keyPath: #keyPath(CALayer.borderColor),
from: layer.borderColor,
to: color.cgColor,
layer: layer,
animationDidStop: animationDidStop)
case .borderWidth(let width):
return createAnimation(keyPath: #keyPath(CALayer.borderWidth),
from: layer.borderWidth,
to: width,
layer: layer,
animationDidStop: animationDidStop)
case .cornerRadius(let cornerRadius):
return createAnimation(keyPath: #keyPath(CALayer.cornerRadius),
from: layer.cornerRadius,
to: cornerRadius,
layer: layer,
animationDidStop: animationDidStop)
case .masksToBounds(let masksToBounds):
return createAnimation(keyPath: #keyPath(CALayer.masksToBounds),
from: layer.masksToBounds,
to: masksToBounds,
layer: layer,
animationDidStop: animationDidStop)
case .moveAnchorPointZ(let anchorPointZ):
return createAnimation(keyPath: #keyPath(CALayer.anchorPointZ),
from: layer.anchorPointZ,
to: anchorPointZ,
layer: layer,
animationDidStop: animationDidStop)
case .hidden(let isHidden):
return createAnimation(keyPath: #keyPath(CALayer.isHidden),
from: layer.isHidden,
to: isHidden,
layer: layer,
animationDidStop: animationDidStop)
case .zPosition(let zPosition):
return createAnimation(keyPath: #keyPath(CALayer.zPosition),
from: layer.zPosition,
to: zPosition,
layer: layer,
animationDidStop: animationDidStop)
case .shadowColor(let shadowColor):
return createAnimation(keyPath: #keyPath(CALayer.shadowColor),
from: layer.shadowColor,
to: shadowColor.cgColor,
layer: layer,
animationDidStop: animationDidStop)
case .shadowOpacity(let shadowOpacity):
return createAnimation(keyPath: #keyPath(CALayer.shadowOpacity),
from: layer.shadowOpacity,
to: shadowOpacity,
layer: layer,
animationDidStop: animationDidStop)
case .shadowRadius(let shadowRadius):
return createAnimation(keyPath: #keyPath(CALayer.shadowRadius),
from: layer.shadowRadius,
to: shadowRadius,
layer: layer,
animationDidStop: animationDidStop)
case .shadowPath(let shadowPath):
return createAnimation(keyPath: #keyPath(CALayer.shadowPath),
from: layer.shadowPath,
to: shadowPath,
layer: layer,
animationDidStop: animationDidStop)
case .original(let keyPath, let from, let to):
return createAnimation(keyPath: keyPath,
from: from,
to: to,
layer: layer,
animationDidStop: animationDidStop)
case .movePath(let path, let keyTimes):
let futurePosition: CGPoint = {
if options.contains(.autoreverse) {
return path.firstPoint ?? layer.position
} else {
return path.currentPoint
}
}()
let animation = AnimaKeyframeAnimation(keyPath: #keyPath(CALayer.position), options: options)
animation.didStop = animationDidStop
animation.keyTimes = keyTimes.map({NSNumber(value: $0)})
animation.path = path
layer.position = futurePosition
return animation
}
}
func createTranslationAnimation(move: CGPoint, layer: CALayer, animationDidStop: @escaping AnimationDidStop) -> CAAnimation? {
let keyPath = "transform.translation"
let currentTranslation: CGPoint = {
if let current = layer.value(forKeyPath: keyPath) as? CGSize {
return CGPoint(x: current.width, y: current.height)
} else {
layer.setValue(CGPoint.zero, forKeyPath: keyPath)
return .zero
}
}()
let to = move + currentTranslation
return createAnimation(keyPath: keyPath, from: currentTranslation, to: to, layer: layer, animationDidStop: animationDidStop)
}
func createMoveAnimation(position: CGPoint, layer: CALayer, animationDidStop: @escaping AnimationDidStop) -> CAAnimation? {
return createAnimation(keyPath: #keyPath(CALayer.position),
from: layer.position,
to: position,
layer: layer,
animationDidStop: animationDidStop)
}
func createRotateAnimation(radian: CGFloat, layer: CALayer, animationDidStop: @escaping AnimationDidStop, rotateType: RotateType) -> CAAnimation? {
let currentRotate: CGFloat = {
if let current = layer.value(forKeyPath: rotateType.keyPath) as? CGFloat {
return current
} else {
layer.setValue(CGFloat(0), forKeyPath: rotateType.keyPath)
return 0
}
}()
let toValue = currentRotate + radian
return createAnimation(keyPath: rotateType.keyPath,
from: currentRotate,
to: toValue,
layer: layer,
animationDidStop: animationDidStop)
}
func createScaleAnimation(scale: CGFloat, layer: CALayer, animationDidStop: @escaping AnimationDidStop, scaleType: Scaletype) -> CAAnimation? {
let currentScale: CGFloat = {
if let current = layer.value(forKeyPath: scaleType.keyPath) as? CGFloat {
return current
} else {
layer.setValue(CGFloat(1), forKeyPath: scaleType.keyPath)
return 1
}
}()
let toValue = currentScale + scale
return createAnimation(keyPath: scaleType.keyPath,
from: currentScale,
to: toValue,
layer: layer,
animationDidStop: animationDidStop)
}
func createAnimation<T>(keyPath: String, from: T?, to: T, layer: CALayer, animationDidStop: @escaping AnimationDidStop) -> CAAnimation {
let defaultAnimation = DefaultAnimation(keyPath: keyPath, animationValue: to, options: options)
let futureProperty = defaultAnimation.futureProperty(currentProperty: from)
let anim = defaultAnimation.instantiateAnimation(currentProperty: from, didStop: animationDidStop)
layer.setValue(futureProperty, forKeyPath: keyPath)
return anim
}
}
| mit | 3f91da0c86a4e289d73cc26995beb9f8 | 42.638728 | 151 | 0.518909 | 6.293872 | false | false | false | false |
bitjammer/swift | test/SILGen/c_function_pointers.swift | 1 | 2367 | // RUN: %target-swift-frontend -emit-silgen -verify %s | %FileCheck %s
func values(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(c) (Int) -> Int {
return arg
}
// CHECK-LABEL: sil hidden @_T019c_function_pointers6valuesS2iXCS2iXCF
// CHECK: bb0(%0 : $@convention(c) (Int) -> Int):
// CHECK: return %0 : $@convention(c) (Int) -> Int
@discardableResult
func calls(_ arg: @convention(c) (Int) -> Int, _ x: Int) -> Int {
return arg(x)
}
// CHECK-LABEL: sil hidden @_T019c_function_pointers5callsS3iXC_SitF
// CHECK: bb0(%0 : $@convention(c) (Int) -> Int, %1 : $Int):
// CHECK: [[RESULT:%.*]] = apply %0(%1)
// CHECK: return [[RESULT]]
@discardableResult
func calls_no_args(_ arg: @convention(c) () -> Int) -> Int {
return arg()
}
func global(_ x: Int) -> Int { return x }
func no_args() -> Int { return 42 }
// CHECK-LABEL: sil hidden @_T019c_function_pointers0B19_to_swift_functionsySiF
func pointers_to_swift_functions(_ x: Int) {
// CHECK: bb0([[X:%.*]] : $Int):
func local(_ y: Int) -> Int { return y }
// CHECK: [[GLOBAL_C:%.*]] = function_ref @_T019c_function_pointers6globalS2iFTo
// CHECK: apply {{.*}}([[GLOBAL_C]], [[X]])
calls(global, x)
// CHECK: [[LOCAL_C:%.*]] = function_ref @_T019c_function_pointers0B19_to_swift_functionsySiF5localL_S2iFTo
// CHECK: apply {{.*}}([[LOCAL_C]], [[X]])
calls(local, x)
// CHECK: [[CLOSURE_C:%.*]] = function_ref @_T019c_function_pointers0B19_to_swift_functionsySiFS2icfU_To
// CHECK: apply {{.*}}([[CLOSURE_C]], [[X]])
calls({ $0 + 1 }, x)
calls_no_args(no_args)
// CHECK: [[NO_ARGS_C:%.*]] = function_ref @_T019c_function_pointers7no_argsSiyFTo
// CHECK: apply {{.*}}([[NO_ARGS_C]])
}
func unsupported(_ a: Any) -> Int { return 0 }
func pointers_to_bad_swift_functions(_ x: Int) {
calls(unsupported, x) // expected-error{{C function pointer signature '(Any) -> Int' is not compatible with expected type '@convention(c) (Int) -> Int'}}
}
// CHECK-LABEL: sil shared @_T019c_function_pointers22StructWithInitializersV3fn1yyXCvfiyycfU_ : $@convention(thin) () -> () {
// CHECK-LABEL: sil shared [thunk] @_T019c_function_pointers22StructWithInitializersV3fn1yyXCvfiyycfU_To : $@convention(c) () -> () {
struct StructWithInitializers {
let fn1: @convention(c) () -> () = {}
init(a: ()) {}
init(b: ()) {}
}
| apache-2.0 | 5618a98afe105aaa36096b51077e823c | 35.415385 | 155 | 0.61597 | 3.015287 | false | false | false | false |
AngeloStavrow/Rewatch | Rewatch/UI/Helpers/Stylesheet.swift | 1 | 2912 | //
// Stylesheet.swift
// Rewatch
//
// Created by Romain Pouclet on 2015-10-22.
// Copyright © 2015 Perfectly-Cooked. All rights reserved.
//
import UIKit
class Stylesheet: NSObject {
// Colors
static let navigationBarTextColor = UIColor(rgba: "#222222")
static let navigationBarTintColor = UIColor.whiteColor()
static let commonBackgroundColor = UIColor(rgba: "#222222")
static let appBackgroundColor = UIColor.blackColor()
static let showBackgroundColor = UIColor(rgba: "#F74D40")
static let episodeNumberTextColor = UIColor(rgba: "#222222")
static let seasonNumberTextColor = UIColor(rgba: "#222222")
static let episodePictureBackgroundImageColor = UIColor(rgba: "#222222")
static let buttonBorderColor = UIColor(rgba: "#979797")
static let explainationTextColor = UIColor(rgba: "#F74E40")
static let statusTextColor = UIColor.whiteColor()
static let creditsTitleColor = UIColor(rgba: "#F74D40")
static let creditsValueColor = UIColor.whiteColor()
static let arrowColor = UIColor(rgba: "#F74D40")
// Fonts
static let titleFont = UIFont(name: "Roboto-Bold", size: 16)!
static let textFont = UIFont(name: "Roboto-Thin", size: 18)!
static let showNameTextFont = UIFont(name: "Roboto-Light", size: 21)!
static let episodeTitleTextFont = UIFont(name: "Roboto-Bold", size: 26)!
static let episodeNumberFont = UIFont(name: "Roboto-Thin", size: 66)!
static let seasonNumbertextFont = UIFont(name: "Roboto-Thin", size: 66)!
static let buttonFont = UIFont(name: "Roboto-Bold", size: 16)!
static let explainationFont = UIFont(name: "Roboto-Light", size: 15)!
static let statusFont = UIFont(name: "Roboto", size: 15)!
static let creditsTitleFont = UIFont(name: "Roboto-Thin", size: 12)!
static let creditsValueFont = UIFont(name: "Roboto-Thin", size: 17)!
func apply() {
UINavigationBar.appearance().translucent = false
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: Stylesheet.navigationBarTextColor, NSFontAttributeName: Stylesheet.titleFont]
UINavigationBar.appearance().barTintColor = Stylesheet.navigationBarTintColor
UINavigationBar.appearance().tintColor = Stylesheet.navigationBarTintColor
UINavigationBar.appearance().backgroundColor = Stylesheet.navigationBarTintColor
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarPosition: .Any, barMetrics: .Default)
UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: Stylesheet.navigationBarTextColor, NSFontAttributeName: Stylesheet.titleFont], forState: .Normal)
}
}
extension UIFont {
class func robotoWithSize(size: CGFloat) -> UIFont {
return UIFont(name: "Roboto", size: size)!
}
}
| mit | 5ce2b97de46ff7ee733e62d4f7bde1f2 | 43.784615 | 190 | 0.721058 | 4.702746 | false | false | false | false |
michaelborgmann/handshake | Handshake/LoginViewController.swift | 1 | 4067 | //
// LoginViewController.swift
// Handshake
//
// Created by Michael Borgmann on 29/06/15.
// Copyright (c) 2015 Michael Borgmann. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: "LoginViewController", bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
emailField.delegate = self
passwordField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if emailField.isFirstResponder() {
passwordField.becomeFirstResponder()
} else if passwordField.isFirstResponder() {
passwordField.resignFirstResponder()
}
return true
}
@IBAction func login(sender: AnyObject) {
let email = emailField.text
let password = passwordField.text
if email.isEmpty || password.isEmpty {
alertMessage(title: "Handshake", message: "The email or password you entered was incorrect. Please try again.")
return
}
// FIXME: for offline debuggin and development only
let offline = true
if offline {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
// Send user data to server side
let url = NSURL(string: "http://webapi.domain.com/includes/login.php")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let postString = "email=\(email)&password=\(password)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
if let parseJSON = json {
var resultValue = parseJSON["status"] as? String
println("result: \(resultValue)")
if (resultValue == "Success") {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize();
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
task.resume()
}
}
func alertMessage(title: String? = nil, message: String) {
var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okayAction = UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(okayAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
| gpl-2.0 | 9b93d824ecbfa4e2e95ac64abaef9e86 | 34.365217 | 130 | 0.58151 | 5.911337 | false | false | false | false |
t-ae/ImageTrimmer | ImageTrimmer/ViewControllers/TrimViewController.swift | 1 | 1368 | import Foundation
import Cocoa
import RxSwift
import RxCocoa
import Swim
class TrimViewController: NSViewController {
private(set) var image: Image<RGBA, UInt8>!
private(set) var x: BehaviorRelay<Int>!
private(set) var y: BehaviorRelay<Int>!
private(set) var width: Int!
private(set) var height: Int!
private(set) var positiveDirectory: String!
private(set) var negativeDirectory: String!
private(set) var positiveFileNumber: BehaviorRelay<Int>!
private(set) var negativeFileNumber: BehaviorRelay<Int>!
override func viewDidDisappear() {
NSApplication.shared.stopModal()
}
func bind(image: Image<RGBA, UInt8>!,
x: BehaviorRelay<Int>,
y: BehaviorRelay<Int>,
width: Int,
height: Int,
positiveDirectory: String,
negativeDirectory: String,
positiveFileNumber: BehaviorRelay<Int>,
negativeFileNumber: BehaviorRelay<Int>) {
self.image = image
self.x = x
self.y = y
self.width = width
self.height = height
self.positiveDirectory = positiveDirectory
self.negativeDirectory = negativeDirectory
self.positiveFileNumber = positiveFileNumber
self.negativeFileNumber = negativeFileNumber
}
}
| mit | 939c06171ece58bd6f156787f8d8d1c3 | 28.106383 | 60 | 0.630848 | 4.920863 | false | false | false | false |
steelwheels/KiwiControls | Source/Controls/KCTableCellView.swift | 1 | 4692 | /**
* @file KCTableCellView.swift
* @brief Define KCTableCellView class
* @par Copyright
* Copyright (C) 2021 Steel Wheels Project
*/
import CoconutData
import Foundation
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
public protocol KCTableCellDelegate {
#if os(OSX)
func tableCellView(shouldEndEditing view: KCTableCellView, columnTitle title: String, rowIndex ridx: Int, value val: CNValue)
#endif
}
#if os(OSX)
public class KCTableCellView: NSTableCellView, NSTextFieldDelegate
{
private var mDelegate: KCTableCellDelegate? = nil
private var mTitle = ""
private var mRowIndex = -1
private var mIsInitialized = false
public func setup(title tstr: String, row ridx: Int, delegate dlg: KCTableCellDelegate){
mTitle = tstr
mRowIndex = ridx
mDelegate = dlg
guard !mIsInitialized else {
return // already initialized
}
if let field = super.textField {
field.delegate = self
}
mIsInitialized = true
}
public override var objectValue: Any? {
get {
return super.objectValue
}
set(newval){
if let nval = newval as? CNValue {
updateValue(value: nval)
}
super.objectValue = newval
}
}
private func updateValue(value val: CNValue){
if let field = super.textField {
field.stringValue = val.description
field.sizeToFit()
} else {
let newfield = NSTextField(string: val.description)
super.textField = newfield
}
}
private func updateImageValue(value val: CNImage){
if let imgview = super.imageView {
imgview.image = val
} else {
let newimage = NSImageView()
newimage.image = val
super.imageView = newimage
}
}
public var firstResponderView: KCViewBase? { get {
if let field = self.textField {
return field
} else if let imgview = self.imageView {
return imgview
} else {
return nil
}
}}
public var isEditable: Bool {
get {
if let field = self.textField {
return field.isEditable
} else if let _ = self.imageView {
return false
} else {
return false
}
}
set(newval){
if let field = self.textField {
field.isEditable = newval
} else if let _ = self.imageView {
// do nothing
} else {
// do nothing
}
}
}
public var isEnabled: Bool {
get {
if let field = self.textField {
return field.isEnabled
} else if let img = self.imageView {
return img.isEnabled
} else {
return false
}
}
set(newval){
if let field = self.textField {
field.isEnabled = newval
if newval {
field.textColor = NSColor.controlTextColor
} else {
field.textColor = NSColor.disabledControlTextColor
}
} else if let img = self.imageView {
img.isEnabled = newval
} else {
// do nothing
}
}
}
public override var intrinsicContentSize: NSSize {
get {
if let field = self.textField {
return self.intrinsicContentSize(ofTextField: field)
} else if let img = self.imageView {
return img.intrinsicContentSize
} else {
return super.intrinsicContentSize
}
}
}
private func intrinsicContentSize(ofTextField field: NSTextField) -> CGSize {
let DefaultLength: Int = 4
let curnum = field.stringValue.count
let newnum = max(curnum, DefaultLength)
let fitsize = field.fittingSize
let newwidth: CGFloat
if let font = field.font {
let attr = [NSAttributedString.Key.font: font]
let str: String = " "
let fsize = str.size(withAttributes: attr)
newwidth = max(fitsize.width, fsize.width * CGFloat(newnum))
} else {
newwidth = fitsize.width
}
field.preferredMaxLayoutWidth = newwidth
return CGSize(width: newwidth, height: fitsize.height)
}
public override var fittingSize: CGSize {
get {
if let field = self.textField {
return field.fittingSize
} else if let img = self.imageView {
return img.fittingSize
} else {
return super.fittingSize
}
}
}
public override func setFrameSize(_ newsize: CGSize) {
let fitsize = self.fittingSize
if fitsize.width <= newsize.width && fitsize.height <= newsize.height {
self.setFrameSizeBody(size: newsize)
} else {
self.setFrameSizeBody(size: fitsize)
}
}
private func setFrameSizeBody(size newsize: CGSize){
super.setFrameSize(newsize)
if let field = self.textField {
field.setFrameSize(newsize)
} else if let img = self.imageView {
img.setFrameSize(newsize)
}
}
/* NSTextFieldDelegate */
public func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
if let dlg = mDelegate {
let val: CNValue = .stringValue(fieldEditor.string)
dlg.tableCellView(shouldEndEditing: self, columnTitle: mTitle, rowIndex: mRowIndex, value: val)
}
return true
}
}
#endif // os(OSX)
| lgpl-2.1 | e939e8da1a3687c739203ba17d5dd6b5 | 21.666667 | 126 | 0.685848 | 3.353824 | false | false | false | false |
JesusAntonioGil/MemeMe2.0 | MemeMe2/Helpers/ActivityHelper/ActivityHelper.swift | 1 | 1817 | //
// ActivityHelper.swift
// MemeMe2
//
// Created by Jesus Antonio Gil on 24/3/16.
// Copyright © 2016 Jesus Antonio Gil. All rights reserved.
//
import UIKit
import QuartzCore
class ActivityHelper: NSObject {
//Inject
var storageHelperProtocol: StorageHelperProtocol!
var viewController: UIViewController!
//MARK: PUBLIC
func shareImage(meme: Meme) {
let shareItems = [meme.memeImage]
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivityTypePrint, UIActivityTypePostToWeibo, UIActivityTypeCopyToPasteboard, UIActivityTypeAddToReadingList, UIActivityTypePostToVimeo]
activityViewController.completionWithItemsHandler = {
(activity, success, items, error) in
if(success == true && error == nil) {
self.saveMeme(meme)
}
}
viewController.presentViewController(activityViewController, animated: true, completion: nil)
}
func getImageFromView(view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let img: UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
//MARK: PRIVATE
func saveMeme(meme: Meme) {
let memeObject = MemeObject(topText: meme.topText, bottomText: meme.bottomText, image: meme.image, memeImage: meme.memeImage)
var memeArray = storageHelperProtocol.memes
memeArray.append(memeObject)
storageHelperProtocol.memes = memeArray
}
}
| mit | fcb3c0fe95c33ae27e123abbe99fccab | 32.018182 | 194 | 0.690529 | 5.404762 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKitRunner OSX/CesiumViewController.swift | 1 | 3443 | //
// ViewController.swift
// CesiumKitRunner OSX
//
// Created by Ryan Walklin on 1/08/2015.
// Copyright © 2015 Test Toast. All rights reserved.
//
import Cocoa
import MetalKit
import CesiumKit
class CesiumViewController: NSViewController {
fileprivate var _cesiumKitController: CesiumKitController! = nil
@IBOutlet var _metalView: MTKView!
override func viewDidLoad() {
super.viewDidLoad()
view.layer!.contentsScale = NSScreen.main()?.backingScaleFactor ?? 1.0
_cesiumKitController = CesiumKitController(view: _metalView)
_metalView.delegate = _cesiumKitController
_cesiumKitController.startRendering()
}
override func viewWillAppear() {
_metalView.window?.acceptsMouseMovedEvents = true
}
override func mouseDown(with event: NSEvent) {
let locationInWindow = event.locationInWindow
let localPoint = _metalView.convert(locationInWindow, from: nil)
let viewHeight = Double(_metalView.bounds.height)
let position = Cartesian2(x: Double(localPoint.x), y: viewHeight - Double(localPoint.y))
let modifier: KeyboardEventModifier?
if event.modifierFlags.contains(.control) {
modifier = .ctrl
} else if event.modifierFlags.contains(.option) {
modifier = .alt
} else if event.modifierFlags.contains(.shift) {
modifier = .shift
} else {
modifier = nil
}
_cesiumKitController.handleMouseDown(.left, position: position, modifier: modifier)
}
override func mouseDragged(with event: NSEvent) {
let locationInWindow = event.locationInWindow
let localPoint = _metalView.convert(locationInWindow, from: nil)
let viewHeight = Double(_metalView.bounds.height)
let position = Cartesian2(x: Double(localPoint.x), y: viewHeight - Double(localPoint.y))
let modifier: KeyboardEventModifier?
if event.modifierFlags.contains(.control) {
modifier = .ctrl
} else if event.modifierFlags.contains(.option) {
modifier = .alt
} else if event.modifierFlags.contains(.shift) {
modifier = .shift
} else {
modifier = nil
}
_cesiumKitController.handleMouseMove(.left, position: position, modifier: modifier)
}
override func mouseMoved(with event: NSEvent) {
}
override func mouseUp(with event: NSEvent) {
let locationInWindow = event.locationInWindow
let localPoint = _metalView.convert(locationInWindow, from: nil)
let viewHeight = Double(_metalView.bounds.height)
let position = Cartesian2(x: Double(localPoint.x), y: viewHeight - Double(localPoint.y))
let modifier: KeyboardEventModifier?
if event.modifierFlags.contains(.control) {
modifier = .ctrl
} else if event.modifierFlags.contains(.option) {
modifier = .alt
} else if event.modifierFlags.contains(.shift) {
modifier = .shift
} else {
modifier = nil
}
_cesiumKitController.handleMouseUp(.left, position: position, modifier: modifier)
}
override func scrollWheel(with event: NSEvent) {
_cesiumKitController.handleWheel(Double(event.deltaX), deltaY: Double(event.deltaY))
}
}
| apache-2.0 | 2481353c9386f1edc7164c026b306aff | 33.42 | 96 | 0.636839 | 4.734525 | false | false | false | false |
Kalvar/swift-KRBeaconFinder | KRBeaconFinder/Classes/KRBeaconFinder/KRBeaconOne.swift | 1 | 8855 | //
// KRBeaconOne.swift
// KRBeaconFinder
//
// Created by Kalvar on 2014/6/22.
// Copyright (c) 2014年 Kalvar. All rights reserved.
//
import CoreLocation
import CoreBluetooth
@objc protocol KRBeaconOneDelegate : NSObjectProtocol
{
@optional func krBeaconOneDidDetermineState(beaconFinder : KRBeaconOne, state : CLRegionState, region : CLRegion);
}
class KRBeaconOne : KRBeaconFinder, CLLocationManagerDelegate
{
var oneDelegate : KRBeaconOneDelegate? = nil;
var uuid : String!;
var identifier : String!;
var major : UInt16?;
var minor : UInt16?;
var beaconRegion : CLBeaconRegion? = nil
{
didSet
{
//同步設定 beaconPeripheral 要廣播的 beaconRegion
if beaconPeripheral != nil
{
super.beaconPeripheral!.beaconRegion = beaconRegion;
}
}
};
var notifyOnDisplay : Bool!
{
didSet
{
if beaconRegion != nil
{
beaconRegion!.notifyEntryStateOnDisplay = notifyOnDisplay;
}
}
};
var notifyOnEntry : Bool!
{
didSet
{
if beaconRegion != nil
{
beaconRegion!.notifyOnEntry = notifyOnEntry;
}
}
};
var notifyOnExit : Bool!
{
didSet
{
if beaconRegion != nil
{
beaconRegion!.notifyOnExit = notifyOnExit;
}
}
};
var notifyMode : KRBeaconNotifyModes
{
set
{
//KRBeaconNotifyModes.Default
//...
}
get
{
/*
* @ 演算法則
* - 1. 先將 KRBeaconNotifyModes 以 2 進制模式編排 :
*
* //0 0 0
* .Deny = 0, //0
* //1 0 0
* .OnlyDisplay, //1
* //0 1 0
* .OnlyEntry, //2
* //1 1 0
* .DisplayAndEntry, //3
* //0 0 1
* .OnlyExit, //4
* //1 0 1
* .DisplayAndExit, //5
* //0 1 1
* .EntryAndExit, //6
* //1 1 1
* .Default //7
*
* - 2. 再將 _notifyOnDisplay, _notifyOnEntry, _notifyOnExit 依照順序放入陣列。
*
* - 3. 依陣列位置給 2^0, 2^1, 2^2 值。
* - 因為代入的判斷參數只有 true / false 2 種狀態,故以 2 為基底。
* - 如代入的判斷參數有 0, 1, 2 這 3 種狀態,就要以 3 為基底,其它以此類推。
*
* - 4. 列舉陣列值,只要為 true 就累加起來。
*
* - 5. 最後依照累加的總值對應 KRBeaconNotifyModes 的位置即可。
*
*/
var _styles : Bool[] = [notifyOnDisplay, notifyOnEntry, notifyOnExit];
//如代入的參數為 2 種判斷狀態,就以 2 為基底,如為 3 種判斷狀態,就代 3,其餘以此類推。
let _binaryCode : Int = 2;
var _times : Int = 0;
var _sum : Int = 0;
for _everyStyle : Bool in _styles
{
if true == _everyStyle
{
//sumOf( 2^0, 2^1 ... )
_sum += Int( pow(Double(_binaryCode), Double(_times)) );
}
++_times;
}
//從 Int 轉換成 enum 相對應位置的值
return KRBeaconNotifyModes.fromRaw(_sum)!;
}
};
/*
* #pragma --mark Private Methods
*/
func _createBeaconRegion()
{
//Has value is return.
if let _someBeacon = beaconRegion
{
return;
}
//proximityUUID 指的是該 Apple Certificated Beacon ID,而不是 BLE 掃出來的 DeviceUUID
let proximityUUID : NSUUID = NSUUID(UUIDString : uuid);
if( major > 0 && minor > 0 )
{
beaconRegion = CLBeaconRegion(proximityUUID: proximityUUID, major: major!, minor: minor!, identifier: identifier);
}
else
{
if( major > 0 )
{
beaconRegion = CLBeaconRegion(proximityUUID: proximityUUID, major: major!, identifier: identifier!);
}
else
{
beaconRegion = CLBeaconRegion(proximityUUID: proximityUUID, identifier: identifier!);
}
}
if beaconRegion? != nil
{
beaconRegion!.notifyEntryStateOnDisplay = notifyOnDisplay;
beaconRegion!.notifyOnEntry = notifyOnEntry;
beaconRegion!.notifyOnExit = notifyOnExit;
super.addRegion( beaconRegion! );
}
}
/*
* #pragma --mark Public Methods
*/
//override extended singleton method.
override class var sharedFinder : KRBeaconOne
{
struct Singleton
{
static let instance : KRBeaconOne = KRBeaconOne();
}
return Singleton.instance;
}
//init does not override
init()
{
//如果沒有 ? 問號的變數,就一定要在這裡作初始化的動作
super.init();
/*
//Extends and Overrides all of works
super.test();
self.test();
test();
*/
uuid = nil;
identifier = nil;
major = 0;
minor = 0;
notifyOnDisplay = true;
notifyOnEntry = true;
notifyOnExit = true;
oneDelegate = nil;
//GCG still Works
//dispatch_async(dispatch_get_main_queue(), {});
super.locationManager.delegate = self;
}
/*
* #pragma --mark Override Add Region Methods
*/
func addRegionWithUuid(beaconUuid : String, beaconIdentifier : String, beaconMajor : UInt16, beaconMinor : UInt16)
{
uuid = beaconUuid;
identifier = beaconIdentifier;
major = beaconMajor;
minor = beaconMinor;
beaconRegion = nil;
_createBeaconRegion();
}
/*
* #pragma --mark Override Ranging Methods
*/
/*
* @ 開始範圍搜索
*/
override func ranging(founder : FoundBeaconsHandler?)
{
_createBeaconRegion();
super.ranging( founder );
}
override func ranging()
{
_createBeaconRegion();
ranging();
}
override func stopRanging()
{
super.stopRanging();
}
/*
* #pragma --mark Override Monitoring Methods
*/
override func monitoring(handler : DisplayRegionHandler?)
{
_createBeaconRegion();
super.monitoring( handler );
}
override func monitoring()
{
_createBeaconRegion();
super.monitoring();
}
override func stopMonitoring()
{
super.stopMonitoring();
}
override func awakeDisplay(completion : DisplayRegionHandler?)
{
super.displayRegionHandler = completion;
monitoring();
}
override func awakeDisplay()
{
awakeDisplay( super.displayRegionHandler );
}
override func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
if !CLLocationManager.locationServicesEnabled()
{
return;
}
if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Authorized
{
return;
}
}
override func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: AnyObject[]!, inRegion region: CLBeaconRegion!)
{
println("beacons 2 \(beacons)");
self.foundBeacons = beacons;
//All of works.
//if self.foundBeaconsHandler? != nil
//if self.foundBeaconsHandler
foundBeaconsHandler?(foundBeacons : foundBeacons, beaconRegion : region);
}
override func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!)
{
enterRegionHandler?(manager : manager, region : region);
}
override func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!)
{
exitRegionHandler?(manager : manager, region : region);
}
override func locationManager(manager: CLLocationManager!, didDetermineState state: CLRegionState, forRegion region: CLRegion!)
{
oneDelegate?.krBeaconOneDidDetermineState?(self, state : state, region : region);
displayRegionHandler?(manager : manager, region : region, state : state);
}
}
| mit | 3fd6cf7a5438b46273b4881b65d311c5 | 25.264798 | 135 | 0.519037 | 4.402611 | false | false | false | false |
VivaReal/Compose | Compose/Classes/Extensions/Foundation/Array+Add.swift | 1 | 4624 | //
// Array+Add.swift
// Compose
//
// Created by Bruno Bilescky on 04/10/16.
// Copyright © 2016 VivaReal. All rights reserved.
//
import Foundation
/// Conditional append methods added to Array
public extension Array {
/// Check if the condition is true, generate the item and insert it
///
/// - parameter condition: condition to test
/// - parameter item: a closure to generate the item to insert
public mutating func add(if condition:@autoclosure ()-> Bool, item:(()-> Element)) {
guard condition() else { return }
let concreteItem = item()
self.append(concreteItem)
}
/// Check if the condition is not nil and unwrap it, passing the value to the closure to generate the item
///
/// - parameter condition: a closure that returns an optional
/// - parameter item: the closure that will use the unwrapped value to generate the item
public mutating func add<T>(ifLet condition:@autoclosure ()-> T?, item:((T)-> Element)) {
guard let value = condition() else { return }
let concreteItem = item(value)
self.append(concreteItem)
}
/// Check if the condition is not nil and unwrap it, passing the value to the closure to generate the item. If the value is nill use the else block to generate an item
///
/// - parameter condition: a closure that returns an optional
/// - parameter item: the closure that will use the unwrapped value to generate the item
/// - parameter elseItem: a closure that receives no value and generate an item to add to the collection
public mutating func add<T>(ifLet condition:@autoclosure ()-> T?, item:((T)-> Element), elseItem:(()-> Element)) {
let concreteItem: Element
if let value = condition() {
concreteItem = item(value)
}
else {
concreteItem = elseItem()
}
self.append(concreteItem)
}
/// Add many items from the closure to the array
///
/// - parameter items: the closure that will generate the items
public mutating func add(many items:(()-> [Element])) {
let concreteItems = items()
self.append(contentsOf: concreteItems)
}
/// check if the condition is true and than invokes the closure to generate and add the items
///
/// - parameter condition: condition to check
/// - parameter items: the closure that will generate the items
public mutating func add(manyIf condition:@autoclosure ()-> Bool, items:(()-> [Element])) {
guard condition() else { return }
let concreteItems = items()
self.append(contentsOf: concreteItems)
}
/// Check if the condition is not nil and unwrap it, passing the value to the closure to generate the items
///
/// - parameter condition: a closure that returns an optional
/// - parameter items: the closure that will use the unwrapped value to generate the items
public mutating func add<T>(manyIfLet condition:@autoclosure ()-> T?, items:((T)-> [Element])) {
guard let value = condition() else { return }
let concreteItems = items(value)
self.append(contentsOf: concreteItems)
}
/// check if a condition is true and generates the according item using the right closure
///
/// - parameter condition: the closure to check
/// - parameter itemTrue: the closure to generate the item if the condition is true
/// - parameter itemFalse: the closure to generate the item if the condition is false
public mutating func add(ifTrue condition:@autoclosure ()-> Bool, itemTrue:(()-> Element), itemFalse:(()-> Element)) {
let concreteItem: Element
if condition() {
concreteItem = itemTrue()
}
else {
concreteItem = itemFalse()
}
self.append(concreteItem)
}
/// check if a condition is true and generates the according items using the right closure
///
/// - parameter condition: the closure to check
/// - parameter itemsTrue: the closure to generate the items if the condition is true
/// - parameter itemsFalse: the closure to generate the items if the condition is false
public mutating func add(manyIfTrue condition:@autoclosure ()-> Bool, itemsTrue:(()-> [Element]), itemsFalse:(()-> [Element])) {
let concreteItems: [Element]
if condition() {
concreteItems = itemsTrue()
}
else {
concreteItems = itemsFalse()
}
self.append(contentsOf: concreteItems)
}
}
| mit | 030b2727562e3356e7b283d035156fe1 | 41.027273 | 171 | 0.637249 | 4.790674 | false | false | false | false |
renzifeng/ZFZhiHuDaily | ZFZhiHuDaily/Drawer/View/ZFLeftHomeCell.swift | 1 | 795 | //
// ZFHomeCell.swift
// ZFZhiHuDaily
//
// Created by 任子丰 on 16/1/6.
// Copyright © 2016年 任子丰. All rights reserved.
//
import UIKit
class ZFLeftHomeCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
backgroundColor = UIColor(patternImage: UIImage(named: "bg")!)
let selectView = UIView()
selectView.backgroundColor = UIColor.blackColor()
selectedBackgroundView = selectView
titleLabel.highlightedTextColor = UIColor.whiteColor()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 | 4af1e215b92225b2253c344393454156 | 25 | 70 | 0.673077 | 4.588235 | false | false | false | false |
JoeLago/MHGDB-iOS | Pods/GRDB.swift/GRDB/QueryInterface/SQLExpressible.swift | 2 | 3757 | // MARK: - SQLExpressible
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The protocol for all types that can be turned into an SQL expression.
///
/// It is adopted by protocols like DatabaseValueConvertible, and types
/// like Column.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// :nodoc:
public protocol SQLExpressible {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an SQLExpression
var sqlExpression: SQLExpression { get }
}
// MARK: - SQLSpecificExpressible
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLSpecificExpressible is a protocol for all database-specific types that can
/// be turned into an SQL expression. Types whose existence is not purely
/// dedicated to the database should adopt the SQLExpressible protocol instead.
///
/// For example, Column is a type that only exists to help you build requests,
/// and it adopts SQLSpecificExpressible.
///
/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
///
/// :nodoc:
public protocol SQLSpecificExpressible : SQLExpressible {
// SQLExpressible can be adopted by Swift standard types, and user
// types, through the DatabaseValueConvertible protocol which inherits
// from SQLExpressible.
//
// For example, Int adopts SQLExpressible through
// DatabaseValueConvertible.
//
// SQLSpecificExpressible, on the other side, is not adopted by any
// Swift standard type or any user type. It is only adopted by GRDB types,
// such as Column and SQLExpression.
//
// This separation lets us define functions and operators that do not
// spill out. The three declarations below have no chance overloading a
// Swift-defined operator, or a user-defined operator:
//
// - ==(SQLExpressible, SQLSpecificExpressible)
// - ==(SQLSpecificExpressible, SQLExpressible)
// - ==(SQLSpecificExpressible, SQLSpecificExpressible)
}
// MARK: - SQLExpressible & SQLOrderingTerm
extension SQLExpressible where Self: SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public var reversed: SQLOrderingTerm {
return SQLOrdering.desc(sqlExpression)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.expressionSQL(&arguments)
}
}
// MARK: - SQLExpressible & SQLSelectable
extension SQLExpressible where Self: SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.expressionSQL(&arguments)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.expressionSQL(&arguments)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func count(distinct: Bool) -> SQLCount? {
return sqlExpression.count(distinct: distinct)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func columnCount(_ db: Database) throws -> Int {
return 1
}
}
| mit | 24c117d70b1cb904d75337790461cdf7 | 34.780952 | 93 | 0.686984 | 4.565006 | false | false | false | false |
sroebert/JSONCoding | Sources/JSONDecoder.swift | 1 | 19726 | //
// JSONDecoder.swift
// JSONCoding
//
// Created by Steven Roebert on 04/05/17.
// Copyright © 2017 Steven Roebert. All rights reserved.
//
import Foundation
public final class JSONDecoder {
// MARK: - Properties
public let parent: JSONDecoder?
public let jsonObject: Any?
public let rootPath: JSONPath
public let decodingOptions: Dictionary<String, Any>
// MARK: - Initialize
public init(jsonObject: Any?, rootPath: JSONPath = nil, parent: JSONDecoder? = nil, options: Dictionary<String, Any> = [:]) {
self.rootPath = rootPath
self.parent = parent
self.jsonObject = jsonObject
self.decodingOptions = options
}
public convenience init(data: Data, rootPath: JSONPath = nil, options: Dictionary<String, Any> = [:]) throws {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data)
self.init(jsonObject: jsonObject, rootPath: rootPath, options: options)
}
catch {
throw JSONDecodingError.invalidJSON
}
}
public convenience init(string: String, rootPath: JSONPath = nil, options: Dictionary<String, Any> = [:]) throws {
guard let data = string.data(using: .utf8) else {
throw JSONDecodingError.invalidJSON
}
try self.init(data: data, rootPath: rootPath, options: options)
}
// MARK: - Core Decode Functions
public func decodeJSONObject<T: JSONValue>(_ jsonObject: Any, path: JSONPath) throws -> T {
if jsonObject is NSNull {
throw JSONDecodingError.missingData(path)
}
let value = jsonObject as? T
guard value != nil else {
throw JSONDecodingError.invalidDataType(path, T.self, jsonObject)
}
return value!
}
public func decodeJSONObject<T: JSONValue>(_ jsonObject: Any, path: JSONPath) throws -> T? {
if jsonObject is NSNull {
return nil
}
let value: T = try decodeJSONObject(jsonObject, path: path)
return value
}
public func decodeJSONObject<T: JSONDecodable>(_ jsonObject: Any, path: JSONPath) throws -> T {
if jsonObject is NSNull {
throw JSONDecodingError.missingData(path)
}
let pathOffset = rootPath.count
if pathOffset >= path.count {
return try T(decoder: self)
}
else {
var parent = self
var subPath = rootPath + path[pathOffset]
var subJsonObject = try self.jsonObject(for: JSONPath(element: path[pathOffset]))
for i in pathOffset+1..<path.count {
parent = JSONDecoder(jsonObject: subJsonObject, rootPath: subPath, parent: parent, options: decodingOptions)
subPath = subPath + path[i]
subJsonObject = try parent.jsonObject(for: JSONPath(element: path[i]))
}
let decoder = JSONDecoder(jsonObject: subJsonObject, rootPath: subPath, parent: parent, options: decodingOptions)
return try T(decoder: decoder)
}
}
public func decodeJSONObject<T: JSONDecodable>(_ jsonObject: Any, path: JSONPath) throws -> T? {
if jsonObject is NSNull {
return nil
}
let value: T = try decodeJSONObject(jsonObject, path: path)
return value
}
public func decodeJSONObject<T: RawRepresentable, U: JSONValue>(_ jsonObject: Any, path: JSONPath) throws -> T where T.RawValue == U {
let rawValue: U = try decodeJSONObject(jsonObject, path: path)
guard let value = T(rawValue: rawValue) else {
guard let fallbackRepresentable = T.self as? JSONFallbackRepresentable.Type,
let fallback = fallbackRepresentable.init(fallbackFromJSONObject: jsonObject) as? T else {
throw JSONDecodingError.invalidRawValue(path, T.self, rawValue)
}
return fallback
}
return value
}
public func decodeJSONObject<T: RawRepresentable, U: JSONValue>(_ jsonObject: Any, path: JSONPath) throws -> T? where T.RawValue == U {
if jsonObject is NSNull {
return nil
}
let value: T = try decodeJSONObject(jsonObject, path: path)
return value
}
// MARK: - Utils
public func jsonObject(for path: JSONPath) throws -> Any? {
guard !path.isEmpty else {
return self.jsonObject
}
var jsonObject = self.jsonObject
for (index, element) in path.enumerated() {
guard jsonObject != nil else {
return nil
}
switch element.pathElementType {
case .index(let arrayIndex):
guard let array = jsonObject as? NSArray else {
throw JSONDecodingError.invalidDataType(rootPath + path[0...index], NSArray.self, jsonObject!)
}
guard arrayIndex >= 0 && arrayIndex < array.count else {
return nil
}
jsonObject = array[arrayIndex]
case .key(let key):
guard let dictionary = jsonObject as? NSDictionary else {
throw JSONDecodingError.invalidDataType(rootPath + path[0...index], NSDictionary.self, jsonObject!)
}
jsonObject = dictionary[key]
}
}
return jsonObject
}
public func decoder(at path: JSONPath = nil) throws -> JSONDecoder {
let jsonObject = try self.jsonObject(for: path)
return JSONDecoder(jsonObject: jsonObject, rootPath: rootPath + path, parent: self, options: decodingOptions)
}
// MARK: - Decode
public func decode<T>(_ path: JSONPath = nil, decoder: (Any, JSONPath) throws -> T) throws -> T {
guard let jsonObject = try jsonObject(for: path) else {
throw JSONDecodingError.missingData(rootPath + path)
}
return try decoder(jsonObject, rootPath + path)
}
public func decode<T>(_ path: JSONPath = nil, decoder: (Any, JSONPath) throws -> T?) throws -> T? {
guard let jsonObject = try jsonObject(for: path) else {
return nil
}
return try decoder(jsonObject, rootPath + path)
}
public func decode<T, U: JSONValue>(_ path: JSONPath = nil, decoder: (U, JSONPath) throws -> T) throws -> T {
let value: U = try decode(path, decoder: decodeJSONObject)
return try decoder(value, rootPath + path)
}
public func decode<T, U: JSONValue>(_ path: JSONPath = nil, decoder: (U, JSONPath) throws -> T?) throws -> T? {
let value: U? = try decode(path, decoder: decodeJSONObject)
guard value != nil else {
return nil
}
return try decoder(value!, rootPath + path)
}
// MARK: - Array / Dictionary Decoders
private func decodeArray<T>(_ array: NSArray, path: JSONPath, decoder: @escaping (Any, JSONPath) throws -> T) throws -> [T] {
return try array.enumerated().map { (index, arrayObject) in
return try decoder(arrayObject, path + index)
}
}
public func decoderForArrayWithDecoder<T>(_ decoder: @escaping (Any, JSONPath) throws -> T) -> (Any, JSONPath) throws -> [T] {
return { (jsonObject, path) in
let array: NSArray = try self.decodeJSONObject(jsonObject, path: path)
return try self.decodeArray(array, path: path, decoder: decoder)
}
}
public func decoderForArrayWithDecoder<T>(_ decoder: @escaping (Any, JSONPath) throws -> T) -> (Any, JSONPath) throws -> [T]? {
return { (jsonObject, path) in
let array: NSArray? = try self.decodeJSONObject(jsonObject, path: path)
guard array != nil else {
return nil
}
return try self.decodeArray(array!, path: path, decoder: decoder)
}
}
private func decodeDictionary<T>(_ dictionary: NSDictionary, path: JSONPath, decoder: (Any, JSONPath) throws -> T) throws -> [String:T] {
return try dictionary.mapKeysAndValues { key, jsonObject in
let stringKey = key as! String
let value: T = try decoder(jsonObject, path + stringKey)
return (stringKey, value)
}
}
public func decoderForDictionaryWithDecoder<T>(_ decoder: @escaping (Any, JSONPath) throws -> T) -> (Any, JSONPath) throws -> [String:T] {
return { (jsonObject, path) in
let dictionary: NSDictionary = try self.decodeJSONObject(jsonObject, path: path)
return try self.decodeDictionary(dictionary, path: path, decoder: decoder)
}
}
public func decoderForDictionaryWithDecoder<T>(_ decoder: @escaping (Any, JSONPath) throws -> T) -> (Any, JSONPath) throws -> [String:T]? {
return { (jsonObject, path) in
let dictionary: NSDictionary? = try self.decodeJSONObject(jsonObject, path: path)
guard dictionary != nil else {
return nil
}
return try self.decodeDictionary(dictionary!, path: path, decoder: decoder)
}
}
// MARK: - Decode Values
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> T {
return try decode(path, decoder: decodeJSONObject)
}
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> T? {
return try decode(path, decoder: decodeJSONObject)
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> T {
return try decode(path, decoder: decodeJSONObject)
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> T? {
return try decode(path, decoder: decodeJSONObject)
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> T where T.RawValue == U {
return try decode(path, decoder: decodeJSONObject)
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> T? where T.RawValue == U {
return try decode(path, decoder: decodeJSONObject)
}
// MARK: - Array
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [T] {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [T]? {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [T] {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [T]? {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [T] where T.RawValue == U {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [T]? where T.RawValue == U {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
// MARK: - Array of Optionals
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [T?] {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [T?]? {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [T?] {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [T?]? {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [T?] where T.RawValue == U {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [T?]? where T.RawValue == U {
return try decode(path, decoder: decoderForArrayWithDecoder(decodeJSONObject))
}
// MARK: - Dictionary
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [String:T] {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [String:T]? {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [String:T] {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [String:T]? {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [String:T] where T.RawValue == U {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [String:T]? where T.RawValue == U {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
// MARK: - Dictionary of Optionals
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [String:T?] {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [String:T?]? {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [String:T?] {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [String:T?]? {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [String:T?] where T.RawValue == U {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [String:T?]? where T.RawValue == U {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decodeJSONObject))
}
// MARK: - Array of Dictionaries
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [[String:T]] {
return try decode(path, decoder: decoderForArrayWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [[String:T]]? {
return try decode(path, decoder: decoderForArrayWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [[String:T]] {
return try decode(path, decoder: decoderForArrayWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [[String:T]]? {
return try decode(path, decoder: decoderForArrayWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [[String:T]] where T.RawValue == U {
return try decode(path, decoder: decoderForArrayWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [[String:T]]? where T.RawValue == U {
return try decode(path, decoder: decoderForArrayWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
// MARK: - Dictionary of Dictionaries
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [String:[String:T]] {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [String:[String:T]]? {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [String:[String:T]] {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [String:[String:T]]? {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [String:[String:T]] where T.RawValue == U {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [String:[String:T]]? where T.RawValue == U {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForDictionaryWithDecoder(decodeJSONObject)))
}
// MARK: - Dictionary of Arrays
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [String:[T]] {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForArrayWithDecoder(decodeJSONObject)))
}
public func decode<T: JSONValue>(_ path: JSONPath = nil) throws -> [String:[T]]? {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForArrayWithDecoder(decodeJSONObject)))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [String:[T]] {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForArrayWithDecoder(decodeJSONObject)))
}
public func decode<T: JSONDecodable>(_ path: JSONPath = nil) throws -> [String:[T]]? {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForArrayWithDecoder(decodeJSONObject)))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [String:[T]] where T.RawValue == U {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForArrayWithDecoder(decodeJSONObject)))
}
public func decode<T: RawRepresentable, U: JSONValue>(_ path: JSONPath = nil) throws -> [String:[T]]? where T.RawValue == U {
return try decode(path, decoder: decoderForDictionaryWithDecoder(decoderForArrayWithDecoder(decodeJSONObject)))
}
}
| mit | bcbc859136da576832007fef25785541 | 42.256579 | 143 | 0.63564 | 4.679715 | false | false | false | false |
danielfr3/recipez | recipez-app/ViewController.swift | 1 | 1812 | //
// ViewController.swift
// recipez-app
//
// Created by Daniel Freire on 30/05/16.
// Copyright © 2016 Daniel Freire. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var recipes = [Recipe]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.delegate = self
tableView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
fetchAndSetResults()
tableView.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("RecipeCell") as? RecipeCell {
let recipe = recipes[indexPath.row]
cell.configureCell(recipe)
return cell
} else {
return RecipeCell()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}
func fetchAndSetResults() {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Recipe")
do {
let results = try context.executeFetchRequest(fetchRequest)
self.recipes = results as! [Recipe]
} catch let err as NSError {
print(err.debugDescription)
}
}
}
| gpl-3.0 | 0272a2eaade41948c52fdf5d00718c86 | 26.029851 | 109 | 0.625621 | 5.422156 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.