repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
huonw/swift | benchmark/single-source/ArraySubscript.swift | 7 | 1346 | //===--- ArraySubscript.swift ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks the performance of modifying an array element.
import TestsUtils
public let ArraySubscript = BenchmarkInfo(
name: "ArraySubscript",
runFunction: run_ArraySubscript,
tags: [.validation, .api, .Array])
@inline(never)
public func run_ArraySubscript(_ N: Int) {
SRand()
let numArrays = 200*N
let numArrayElements = 100
func bound(_ x: Int) -> Int { return min(x, numArrayElements-1) }
var arrays = [[Int]](repeating: [], count: numArrays)
for i in 0..<numArrays {
for _ in 0..<numArrayElements {
arrays[i].append(Int(truncatingIfNeeded: Random()))
}
}
// Do a max up the diagonal.
for i in 1..<numArrays {
arrays[i][bound(i)] =
max(arrays[i-1][bound(i-1)], arrays[i][bound(i)])
}
CheckResults(arrays[0][0] <= arrays[numArrays-1][bound(numArrays-1)])
}
| apache-2.0 | f79f0d22e8abcc9b19b2bf8442127f72 | 30.302326 | 80 | 0.615899 | 3.947214 | false | false | false | false |
LiveHappier/Charts | Source/Charts/Charts/BarCharRoundedView.swift | 1 | 6763 | //
// BarChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
/// Chart that draws bars.
open class BarChartRoundedView: BarLineChartViewBase, BarChartDataProvider
{
/// if set to true, all values are drawn above their bars, instead of below their top
fileprivate var _drawValueAboveBarEnabled = true
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
fileprivate var _drawBarShadowEnabled = false
internal override func initialize()
{
super.initialize()
renderer = BarChartRoundedRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler)
self.highlighter = BarHighlighter(chart: self)
self.xAxis.spaceMin = 0.5
self.xAxis.spaceMax = 0.5
}
internal override func calcMinMax()
{
guard let data = self.data as? BarChartData
else { return }
if fitBars
{
_xAxis.calculate(
min: data.xMin - data.barWidth / 2.0,
max: data.xMax + data.barWidth / 2.0)
}
else
{
_xAxis.calculate(min: data.xMin, max: data.xMax)
}
// calculate axis range (min / max) according to provided data
_leftAxis.calculate(
min: data.getYMin(axis: .left),
max: data.getYMax(axis: .left))
_rightAxis.calculate(
min: data.getYMin(axis: .right),
max: data.getYMax(axis: .right))
}
/// - returns: The Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart.
open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight?
{
if _data === nil
{
Swift.print("Can't select by touch. No data set.")
return nil
}
guard let h = self.highlighter?.getHighlight(x: pt.x, y: pt.y)
else { return nil }
if !isHighlightFullBarEnabled { return h }
// For isHighlightFullBarEnabled, remove stackIndex
return Highlight(
x: h.x, y: h.y,
xPx: h.xPx, yPx: h.yPx,
dataIndex: h.dataIndex,
dataSetIndex: h.dataSetIndex,
stackIndex: -1,
axis: h.axis)
}
/// - returns: The bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data.
open func getBarBounds(entry e: BarChartDataEntry) -> CGRect
{
guard let
data = _data as? BarChartData,
let set = data.getDataSetForEntry(e) as? IBarChartDataSet
else { return CGRect.null }
let y = e.y
let x = e.x
let barWidth = data.barWidth
let left = x - barWidth / 2.0
let right = x + barWidth / 2.0
let top = y >= 0.0 ? y : 0.0
let bottom = y <= 0.0 ? y : 0.0
var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top)
getTransformer(forAxis: set.axisDependency).rectValueToPixel(&bounds)
return bounds
}
/// Groups all BarDataSet objects this data object holds together by modifying the x-value of their entries.
/// Previously set x-values of entries will be overwritten. Leaves space between bars and groups as specified by the parameters.
/// Calls `notifyDataSetChanged()` afterwards.
///
/// - parameter fromX: the starting point on the x-axis where the grouping should begin
/// - parameter groupSpace: the space between groups of bars in values (not pixels) e.g. 0.8f for bar width 1f
/// - parameter barSpace: the space between individual bars in values (not pixels) e.g. 0.1f for bar width 1f
open func groupBars(fromX: Double, groupSpace: Double, barSpace: Double)
{
guard let barData = self.barData
else
{
Swift.print("You need to set data for the chart before grouping bars.", terminator: "\n")
return
}
barData.groupBars(fromX: fromX, groupSpace: groupSpace, barSpace: barSpace)
notifyDataSetChanged()
}
/// Highlights the value at the given x-value in the given DataSet. Provide -1 as the dataSetIndex to undo all highlighting.
/// - parameter x:
/// - parameter dataSetIndex:
/// - parameter stackIndex: the index inside the stack - only relevant for stacked entries
open func highlightValue(x: Double, dataSetIndex: Int, stackIndex: Int)
{
highlightValue(Highlight(x: x, dataSetIndex: dataSetIndex, stackIndex: stackIndex))
}
// MARK: Accessors
/// if set to true, all values are drawn above their bars, instead of below their top
open var drawValueAboveBarEnabled: Bool
{
get { return _drawValueAboveBarEnabled }
set
{
_drawValueAboveBarEnabled = newValue
setNeedsDisplay()
}
}
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
open var drawBarShadowEnabled: Bool
{
get { return _drawBarShadowEnabled }
set
{
_drawBarShadowEnabled = newValue
setNeedsDisplay()
}
}
/// Adds half of the bar width to each side of the x-axis range in order to allow the bars of the barchart to be fully displayed.
/// **default**: false
open var fitBars = false
/// Set this to `true` to make the highlight operation full-bar oriented, `false` to make it highlight single values (relevant only for stacked).
/// If enabled, highlighting operations will highlight the whole bar, even if only a single stack entry was tapped.
open var highlightFullBarEnabled: Bool = false
/// - returns: `true` the highlight is be full-bar oriented, `false` ifsingle-value
open var isHighlightFullBarEnabled: Bool { return highlightFullBarEnabled }
// MARK: - BarChartDataProbider
open var barData: BarChartData? { return _data as? BarChartData }
/// - returns: `true` if drawing values above bars is enabled, `false` ifnot
open var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled }
/// - returns: `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot
open var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled }
}
| apache-2.0 | 6600a6ab88a61baece0291cca6d1e6bf | 35.956284 | 149 | 0.620435 | 4.78966 | false | false | false | false |
FromF/AirRecipe | AirRecipe WatchKit Extension/GlanceController.swift | 1 | 1455 | //
// GlanceController.swift
// AirRecipe WatchKit Extension
//
// Created by Fuji on 2015/05/27.
// Copyright (c) 2015年 FromF. All rights reserved.
//
import WatchKit
import Foundation
class GlanceController: WKInterfaceController {
//Keys
let CatalogSlectImageName:String = "SlectImageName"
//UI
@IBOutlet weak var imageView: WKInterfaceImage!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
WKInterfaceController.openParentApplication(["getinfo": ""],
reply: {replyInfo, error in
//self.propertyDictionary.removeAll(keepCapacity: false)
var relyInfokeys = Array(replyInfo.keys)
for relyInfokey in relyInfokeys {
if relyInfokey == self.CatalogSlectImageName {
let imagename:String = replyInfo["\(relyInfokey)"] as! String + "_Watch.jpg"
self.imageView.setImage(UIImage(named: imagename))
}
}
})
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| mit | 7aa393b5b12b03d310b2ebb562ae5b5d | 28.653061 | 100 | 0.612526 | 4.993127 | false | false | false | false |
Nocookieleft/Jump-r-Drop | Tower/Tower/GameOverScene.swift | 1 | 3128 | //
// GameOverScene.swift
// Tower
//
// Created by Evil Cookie on 09/06/15.
// Copyright (c) 2015 Evil Cookie. All rights reserved.
//
import Foundation
import SpriteKit
class GameOverScene : SKScene {
let GOMessage = SKLabelNode(fontNamed: "Noteworthy")
let NGButton = SKLabelNode(fontNamed: "Muli")
var hasWon = false
override func didMoveToView(view: SKView) {
// setup scene
backgroundColor = kColorLightBlue
if hasWon
{
GOMessage.text = "You Won!"
}else
{
GOMessage.text = "You Lost"
}
GOMessage.fontColor = kColorDeepDarkBlue
GOMessage.position = CGPoint(x: view.center.x, y: (view.frame.height * 0.6))
addChild(GOMessage)
// show a menu like the pause-menu
let menuNode = SKShapeNode(rectOfSize: CGSizeMake(view.frame.width/2, view.frame.height*0.5))
menuNode.position = view.center
menuNode.fillColor = kColorDarkBlue
addChild(menuNode)
// make a button shape to indicate that the user can click here
let buttonNode = SKShapeNode(rectOfSize: CGSizeMake(menuNode.frame.width * 0.9, 60))
buttonNode.position = CGPointMake(view.center.x, (menuNode.frame.height * 0.8))
buttonNode.fillColor = kColorDarkBlue
buttonNode.name = "newGameButton"
addChild(buttonNode)
// show a "New Game" label node
NGButton.name = "NewGame"
NGButton.fontColor = kColorDeepDarkBlue
NGButton.fontSize = (GOMessage.fontSize * 0.8)
NGButton.text = "New Game"
NGButton.position = CGPointMake(menuNode.position.x, (buttonNode.position.y - 6))
addChild(NGButton)
}
// restart the game by going to the gamescene
func restartGame(){
if let newScene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
let newView = self.view! as SKView
newScene.size = CGSizeMake(view!.bounds.size.width, view!.bounds.size.height)
/* Set the scale mode to scale to fit the window */
newScene.scaleMode = .AspectFill
newView.presentScene(newScene)
}else
{
println("Failed to Restart Game")
}
}
// restart the game if the user touches New Game node
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// check for each touch if any menu nodes are touched by checking location
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let touchedNode = nodeAtPoint(location)
if let nodeName = touchedNode.name {
if (nodeName == "NewGame" || nodeName == "newGameButton")
{
restartGame()
}else
{
println("Failed to Start a New Game")
}
}
}
}
} | gpl-3.0 | dd086490524db16e662c1dfb9e122bc5 | 30.29 | 101 | 0.571292 | 4.634074 | false | false | false | false |
SteveClement/iOS-Open-GPX-Tracker | OpenGpxTracker/AppDelegate.swift | 1 | 6112 |
//
// AppDelegate.swift
// OpenGpxTracker
//
// Created by merlos on 13/09/14.
// Copyright (c) 2014 TransitBox. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "uk.co.plymouthsoftware.core_data" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("DATAMODELNAME", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PROJECTNAME.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() 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.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() 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
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| gpl-3.0 | e5f6b8f4fcb2eac895e468b405175774 | 53.088496 | 290 | 0.718586 | 5.848804 | false | false | false | false |
sungkipyung/CodeSample | SimpleCameraApp/SimpleCameraApp/CameraViewController.swift | 1 | 3309 | //
// CameraViewController.swift
// SimpleCameraApp
//
// Created by 성기평 on 2016. 4. 5..
// Copyright © 2016년 hothead. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
class CameraViewController: UIViewController {
@IBOutlet weak var cameraPreview: CameraPreview!
@IBOutlet weak var cameraToggleButton: UIButton!
@IBOutlet weak var cameraFlashButton: UIButton!
@IBOutlet weak var cameraShotButton: UIButton!
var camera:Camera = Camera.init()
override func loadView() {
super.loadView()
let avLayer = cameraPreview.layer as? AVCaptureVideoPreviewLayer
avLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
cameraToggleButton.layer.cornerRadius = cameraToggleButton.frame.width / 2
cameraToggleButton.layer.masksToBounds = true
cameraToggleButton.layer.borderColor = cameraPreview.tintColor.cgColor
cameraToggleButton.layer.borderWidth = 1
cameraFlashButton.layer.cornerRadius = cameraFlashButton.frame.width / 2
cameraFlashButton.layer.masksToBounds = true
cameraFlashButton.layer.borderColor = cameraPreview.tintColor.cgColor
cameraFlashButton.layer.borderWidth = 1
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
camera.setupWithPreview(cameraPreview) { (result:CameraManualSetupResult) -> (Void) in
}
camera.turnOn({ (result:CameraManualSetupResult) -> (Void) in
})
}
override func viewWillDisappear(_ animated: Bool) {
camera.turnOff { () -> (Void) in
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var prefersStatusBarHidden : Bool {
return true
}
/*
// 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.
}
*/
@IBAction func onTouchBackButton(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil);
}
@IBAction func onTouchShotButton(_ sender: UIButton) {
self.camera.takePicture({ (imageData:Data?) -> (Void) in
if (imageData == nil) {
return
}
let capturedImage:UIImage = UIImage.init(data:imageData!)!
// TODO: Save Image
}, withPreview: self.cameraPreview)
}
@IBAction func onTouchDownControl(_ sender: UIControl) {
}
@IBAction func onTouchUpControl(_ sender: UIControl) {
}
@IBAction func onTouchCameraToggleButton(_ sender: UIControl) {
cameraShotButton.isEnabled = false
cameraToggleButton.isEnabled = false
self.camera.toggleCamera { (error) -> (Void) in
self.cameraShotButton.isEnabled = true
self.cameraToggleButton.isEnabled = true
}
}
}
| apache-2.0 | d8ddffca9aa89aa29ec6696f56e09efb | 32 | 106 | 0.650606 | 5.084746 | false | false | false | false |
Yalantis/PullToMakeSoup | PullToMakeSoup/PullToMakeSoup/CAKeyframeAnimation+Extensions.swift | 1 | 2320 | //
// Created by Anastasiya Gorban on 4/20/15.
// Copyright (c) 2015 Yalantis. All rights reserved.
//
// Licensed under the MIT license: http://opensource.org/licenses/MIT
// Latest version can be found at https://github.com/Yalantis/PullToMakeSoup
//
import CoreGraphics
enum AnimationType: String {
case Rotation = "transform.rotation.z"
case Opacity = "opacity"
case TranslationX = "transform.translation.x"
case TranslationY = "transform.translation.y"
}
enum TimingFunction {
case linear, easeIn, easeOut, easeInEaseOut
}
func mediaTimingFunction(_ function: TimingFunction) -> CAMediaTimingFunction {
switch function {
case .linear: return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
case .easeIn: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
case .easeOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
case .easeInEaseOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
}
extension CAKeyframeAnimation {
class func animationWith(
_ type: AnimationType,
values:[Double],
keyTimes:[Double],
duration: Double,
beginTime: Double) -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: type.rawValue)
animation.values = values
animation.keyTimes = keyTimes as [NSNumber]?
animation.duration = duration
animation.beginTime = beginTime
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
return animation
}
class func animationPosition(_ path: CGPath, duration: Double, timingFunction: TimingFunction, beginTime: Double) -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = path
animation.duration = duration
animation.beginTime = beginTime
animation.timingFunction = mediaTimingFunction(timingFunction)
return animation
}
}
extension UIView {
func addAnimation(_ animation: CAKeyframeAnimation) {
layer.add(animation, forKey: description + animation.keyPath!)
layer.speed = 0
}
func removeAllAnimations() {
layer.removeAllAnimations()
}
}
| mit | d4018b07dd854d01f8a4d9884b3ab1f3 | 32.623188 | 142 | 0.702586 | 5.321101 | false | false | false | false |
LearningSwift2/LearningApps | IntermediateTableView/SimpleTableView/MovieCell.swift | 1 | 717 | //
// MovieCell.swift
//
//
// Created by Phil Wright on 12/4/15.
// Copyright © 2015 Touchopia, LLC. All rights reserved.
//
import UIKit
class MovieCell: UITableViewCell {
var movie : Movie?
@IBOutlet weak var titleLabel: UILabel!
func configureCell(movie: Movie) {
// save the movie
self.movie = movie
if let title = movie.title {
self.titleLabel.text = title
}
if let path = self.movie?.posterPath {
guard let url = NSURL(string: path) else {
print("Not a valid url")
return
}
self.imageView?.loadImageFromURL(url)
}
}
}
| apache-2.0 | f22d25843f7699c2c9a1b3ef42bb5b61 | 20.058824 | 57 | 0.52514 | 4.475 | false | false | false | false |
honghaoz/Swift-Google-Maps-API | Example/Example/ViewController.swift | 1 | 2778 | //
// ViewController.swift
// Example
//
// Created by Honghao Zhang on 2016-02-12.
// Copyright © 2016 Honghao Zhang. All rights reserved.
//
import UIKit
import GoogleMaps
import GoogleMapsDirections
import GooglePlacesAPI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Google Maps Directions
GoogleMapsDirections.provide(apiKey: "AIzaSyDftpY3fi6x_TL4rntL8pgZb-A8mf6D0Ss")
let origin = GoogleMapsDirections.Place.stringDescription(address: "Davis Center, Waterloo, Canada")
let destination = GoogleMapsDirections.Place.stringDescription(address: "Conestoga Mall, Waterloo, Canada")
// You can also use coordinates or placeID for a place
// let origin = Place.Coordinate(coordinate: LocationCoordinate2D(latitude: 43.4697354, longitude: -80.5397377))
// let origin = Place.PlaceID(id: "ChIJb9sw59k0K4gRZZlYrnOomfc")
GoogleMapsDirections.direction(fromOrigin: origin, toDestination: destination) { (response, error) -> Void in
// Check Status Code
guard response?.status == GoogleMapsDirections.StatusCode.ok else {
// Status Code is Not OK
debugPrint(response?.errorMessage ?? "")
return
}
// Use .result or .geocodedWaypoints to access response details
// response will have same structure as what Google Maps Directions API returns
debugPrint("it has \(response?.routes.count ?? 0) routes")
}
// Google Places
GooglePlaces.provide(apiKey: "AIzaSyDftpY3fi6x_TL4rntL8pgZb-A8mf6D0Ss")
GooglePlaces.placeAutocomplete(forInput: "Pub") { (response, error) -> Void in
// Check Status Code
guard response?.status == GooglePlaces.StatusCode.ok else {
// Status Code is Not OK
debugPrint(response?.errorMessage ?? "")
return
}
// Use .predictions to access response details
debugPrint("first matched result: \(response?.predictions.first?.description ?? "nil")")
}
GooglePlaces.placeDetails(forPlaceID: "ChIJb9sw59k0K4gRZZlYrnOomfc") { (response, error) -> Void in
// Check Status Code
guard response?.status == GooglePlaces.StatusCode.ok else {
// Status Code is Not OK
debugPrint(response?.errorMessage ?? "")
return
}
// Use .result to access response details
debugPrint("the formated address is: \(response?.result?.formattedAddress ?? "nil")")
}
}
}
| mit | b3e601fbb16f0de7d02e68c9f13ed4a9 | 38.671429 | 120 | 0.612171 | 4.690878 | false | false | false | false |
zoulinzhya/GLTools | GLTools/Classes/ActionSheetViewController.swift | 1 | 6957 | //
// ActionSheetViewController.swift
// GLTDemo
//
// Created by zoulin on 2017/10/27.
// Copyright © 2017年 zoulin. All rights reserved.
//
import UIKit
class ActionSheetViewController: UIViewController {
var delegate: GActionSheetDelegate?
var bgAlpha:CGFloat = 0.35
fileprivate var actionSheetButtons:[ActionSheetButton] = [ActionSheetButton]()
fileprivate var datasource:[[ActionSheetButton]] = [[ActionSheetButton]]()
fileprivate let screenWidth = UIScreen.main.bounds.size.width
fileprivate let screenHeight = UIScreen.main.bounds.size.height
fileprivate var overlayView: UIView!
fileprivate let headerHeight: CGFloat = 5
fileprivate lazy var tableView:UITableView = {
let table = UITableView(frame: .zero, style: .plain)
table.showsVerticalScrollIndicator = false
table.showsHorizontalScrollIndicator = false
table.isScrollEnabled = false
table.register(ActionSheetTableCell.self, forCellReuseIdentifier: ActionSheetTableCell.identifier)
table.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
table.tableFooterView = UIView()
return table
}()
init(buttonList:[ActionSheetButton]) {
super.init(nibName: nil, bundle: nil)
self.providesPresentationContextTransitionStyle = true
self.definesPresentationContext = true
self.modalPresentationStyle = .custom
self.actionSheetButtons = buttonList
self.configDatasource()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.configViews()
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.updateContentViewFrame()
}
fileprivate func configViews() {
overlayView = UIView(frame: self.view.bounds)
overlayView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:bgAlpha)
overlayView.alpha = 0
self.view.addSubview(overlayView)
let tap = UITapGestureRecognizer(target: self, action: #selector(overlayViewTapHandler))
overlayView.addGestureRecognizer(tap)
var frame = self.view.frame
frame.origin.y = self.screenHeight
self.tableView.frame = frame
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
}
fileprivate func updateContentViewFrame() {
var height: CGFloat = 0
height = CGFloat(actionSheetButtons.count) * 44
if self.datasource.count > 1 {
height += headerHeight
}
let frame = CGRect(x: 0, y: screenHeight - height, width: screenWidth, height: height)
UIView.animate(withDuration: 0.2) {
self.tableView.frame = frame
self.overlayView.alpha = 1.0
}
}
@objc fileprivate func overlayViewTapHandler() {
UIView.animate(withDuration: 0.25, animations: {
var frame = self.tableView.frame
frame.origin.y = self.view.bounds.size.height
self.tableView.frame = frame
self.overlayView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:0)
}) { _ in
self.dismiss(animated: false, completion: nil)
}
}
fileprivate func configDatasource() {
if self.actionSheetButtons.count > 0 {
var actonButtons:[ActionSheetButton] = [ActionSheetButton]()
var cancelButton:[ActionSheetButton] = [ActionSheetButton]()
for (_, actionButton) in actionSheetButtons.enumerated() {
if (actionButton.btnType == .actionSheetBtn_cancel) {
cancelButton.append(actionButton)
} else {
actonButtons.append(actionButton)
}
}
self.datasource.append(actonButtons)
self.datasource.append(cancelButton)
}
}
@objc fileprivate func deviceOrientationDidChange() {
let height = self.tableView.bounds.size.height
let width = self.view.bounds.size.width
let y = self.view.bounds.size.height - height
let frame = CGRect(x: 0, y: y, width: width, height: height)
UIView.animate(withDuration: 0.2) {
self.overlayView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2));
self.tableView.frame = frame
self.overlayView.frame = self.view.bounds
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ActionSheetViewController : UITableViewDelegate, UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return self.datasource.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.datasource[section].count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let actionButton:ActionSheetButton = self.datasource[indexPath.section][indexPath.row]
let cell:ActionSheetTableCell = tableView.dequeueReusableCell(withIdentifier: ActionSheetTableCell.identifier, for: indexPath) as! ActionSheetTableCell
cell.updateActionSheetButton(button: actionButton)
return cell
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return self.datasource.count == 2 && section == 1 ? headerHeight : 0.0
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let reuseIdentifier = "sectionheader"
var header = tableView.dequeueReusableHeaderFooterView(withIdentifier: reuseIdentifier)
if (header == nil) {
header = UITableViewHeaderFooterView(reuseIdentifier: reuseIdentifier)
header?.contentView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.6)
}
return header
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let selectActionButton:ActionSheetButton = self.datasource[indexPath.section][indexPath.row]
self.overlayViewTapHandler()
self.delegate?.actionSheet(self, clickedButton: selectActionButton)
}
}
| mit | 14ab30671977dbd98016faf1c54f4c39 | 37.849162 | 170 | 0.661777 | 5.15493 | false | false | false | false |
HenvyLuk/BabyGuard | BabyGuard/CVCalendar/CVCalendarMenuView.swift | 1 | 4565 | //
// CVCalendarMenuView.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/26/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
public typealias WeekdaySymbolType = CVWeekdaySymbolType
public final class CVCalendarMenuView: UIView {
public var symbols = [String]()
public var symbolViews: [UILabel]?
public var firstWeekday: Weekday? = .Sunday
public var dayOfWeekTextColor: UIColor? = .darkGrayColor()
public var dayofWeekBackgroundColor: UIColor? = .clearColor()
public var dayOfWeekTextUppercase: Bool? = true
public var dayOfWeekFont: UIFont? = UIFont(name: "Avenir", size: 10)
public var weekdaySymbolType: WeekdaySymbolType? = .Short
@IBOutlet public weak var menuViewDelegate: AnyObject? {
set {
if let delegate = newValue as? MenuViewDelegate {
self.delegate = delegate
}
}
get {
return delegate as? AnyObject
}
}
public weak var delegate: MenuViewDelegate? {
didSet {
setupAppearance()
setupWeekdaySymbols()
createDaySymbols()
}
}
public init() {
super.init(frame: CGRect.zero)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func setupAppearance() {
if let delegate = delegate {
firstWeekday~>delegate.firstWeekday?()
dayOfWeekTextColor~>delegate.dayOfWeekTextColor?()
dayofWeekBackgroundColor~>delegate.dayOfWeekBackGroundColor?()
dayOfWeekTextUppercase~>delegate.dayOfWeekTextUppercase?()
dayOfWeekFont~>delegate.dayOfWeekFont?()
weekdaySymbolType~>delegate.weekdaySymbolType?()
}
}
public func setupWeekdaySymbols() {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.components([NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: NSDate())
calendar.firstWeekday = firstWeekday!.rawValue
symbols = calendar.weekdaySymbols
}
public func createDaySymbols() {
// Change symbols with their places if needed.
let dateFormatter = NSDateFormatter()
var weekdays: NSArray
switch weekdaySymbolType! {
case .Normal:
weekdays = dateFormatter.weekdaySymbols as NSArray
case .Short:
weekdays = dateFormatter.shortWeekdaySymbols as NSArray
case .VeryShort:
weekdays = dateFormatter.veryShortWeekdaySymbols as NSArray
}
let firstWeekdayIndex = firstWeekday!.rawValue - 1
if firstWeekdayIndex > 0 {
let copy = weekdays
weekdays = weekdays.subarrayWithRange(
NSRange(location: firstWeekdayIndex, length: 7 - firstWeekdayIndex))
weekdays = weekdays.arrayByAddingObjectsFromArray(
copy.subarrayWithRange(NSRange(location: 0, length: firstWeekdayIndex)))
}
self.symbols = weekdays as! [String]
// Add symbols.
self.symbolViews = [UILabel]()
let space = 0 as CGFloat
let width = self.frame.width / 7 - space
let height = self.frame.height
var x: CGFloat = 0
let y: CGFloat = 0
for i in 0..<7 {
x = CGFloat(i) * width + space
let symbol = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
symbol.textAlignment = .Center
symbol.text = self.symbols[i]
if dayOfWeekTextUppercase! {
symbol.text = (self.symbols[i]).uppercaseString
}
symbol.font = dayOfWeekFont
symbol.textColor = dayOfWeekTextColor
symbol.backgroundColor = dayofWeekBackgroundColor
self.symbolViews?.append(symbol)
self.addSubview(symbol)
}
}
public func commitMenuViewUpdate() {
if let _ = delegate {
let space = 0 as CGFloat
let width = self.frame.width / 7 - space
let height = self.frame.height
var x: CGFloat = 0
let y: CGFloat = 0
for i in 0..<self.symbolViews!.count {
x = CGFloat(i) * width + space
let frame = CGRect(x: x, y: y, width: width, height: height)
let symbol = self.symbolViews![i]
symbol.frame = frame
}
}
}
}
| apache-2.0 | 4bfc8c86e4c3096b4bd134b4b080c18d | 30.267123 | 91 | 0.603943 | 4.929806 | false | false | false | false |
kesun421/firefox-ios | Client/Frontend/Settings/Clearables.swift | 1 | 5265 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
import Deferred
import SDWebImage
import CoreSpotlight
private let log = Logger.browserLogger
// Removed Clearables as part of Bug 1226654, but keeping the string around.
private let removedSavedLoginsLabel = NSLocalizedString("Saved Logins", tableName: "ClearPrivateData", comment: "Settings item for clearing passwords and login data")
// A base protocol for something that can be cleared.
protocol Clearable {
func clear() -> Success
var label: String { get }
}
class ClearableError: MaybeErrorType {
fileprivate let msg: String
init(msg: String) {
self.msg = msg
}
var description: String { return msg }
}
// Clears our browsing history, including favicons and thumbnails.
class HistoryClearable: Clearable {
let profile: Profile
init(profile: Profile) {
self.profile = profile
}
var label: String {
return NSLocalizedString("Browsing History", tableName: "ClearPrivateData", comment: "Settings item for clearing browsing history")
}
func clear() -> Success {
return profile.history.clearHistory().bindQueue(.main) { success in
SDImageCache.shared().clearDisk()
SDImageCache.shared().clearMemory()
self.profile.recentlyClosedTabs.clearTabs()
CSSearchableIndex.default().deleteAllSearchableItems()
NotificationCenter.default.post(name: NotificationPrivateDataClearedHistory, object: nil)
log.debug("HistoryClearable succeeded: \(success).")
return Deferred(value: success)
}
}
}
struct ClearableErrorType: MaybeErrorType {
let err: Error
init(err: Error) {
self.err = err
}
var description: String {
return "Couldn't clear: \(err)."
}
}
// Clear the web cache. Note, this has to close all open tabs in order to ensure the data
// cached in them isn't flushed to disk.
class CacheClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Cache", tableName: "ClearPrivateData", comment: "Settings item for clearing the cache")
}
func clear() -> Success {
let dataTypes = Set([WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
WKWebsiteDataStore.default().removeData(ofTypes: dataTypes, modifiedSince: Date.distantPast, completionHandler: {})
log.debug("CacheClearable succeeded.")
return succeed()
}
}
private func deleteLibraryFolderContents(_ folder: String) throws {
let manager = FileManager.default
let library = manager.urls(for: FileManager.SearchPathDirectory.libraryDirectory, in: .userDomainMask)[0]
let dir = library.appendingPathComponent(folder)
let contents = try manager.contentsOfDirectory(atPath: dir.path)
for content in contents {
do {
try manager.removeItem(at: dir.appendingPathComponent(content))
} catch where ((error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError)?.code == Int(EPERM) {
// "Not permitted". We ignore this.
log.debug("Couldn't delete some library contents.")
}
}
}
private func deleteLibraryFolder(_ folder: String) throws {
let manager = FileManager.default
let library = manager.urls(for: FileManager.SearchPathDirectory.libraryDirectory, in: .userDomainMask)[0]
let dir = library.appendingPathComponent(folder)
try manager.removeItem(at: dir)
}
// Removes all app cache storage.
class SiteDataClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Offline Website Data", tableName: "ClearPrivateData", comment: "Settings item for clearing website data")
}
func clear() -> Success {
let dataTypes = Set([WKWebsiteDataTypeOfflineWebApplicationCache])
WKWebsiteDataStore.default().removeData(ofTypes: dataTypes, modifiedSince: Date.distantPast, completionHandler: {})
log.debug("SiteDataClearable succeeded.")
return succeed()
}
}
// Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB.
class CookiesClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Cookies", tableName: "ClearPrivateData", comment: "Settings item for clearing cookies")
}
func clear() -> Success {
let dataTypes = Set([WKWebsiteDataTypeCookies, WKWebsiteDataTypeLocalStorage, WKWebsiteDataTypeSessionStorage, WKWebsiteDataTypeWebSQLDatabases, WKWebsiteDataTypeIndexedDBDatabases])
WKWebsiteDataStore.default().removeData(ofTypes: dataTypes, modifiedSince: Date.distantPast, completionHandler: {})
log.debug("CookiesClearable succeeded.")
return succeed()
}
}
| mpl-2.0 | 6da5dfda5c45aae307ed2257cd813870 | 34.33557 | 190 | 0.703704 | 4.995256 | false | false | false | false |
OatmealCode/Oatmeal | Example/Pods/Carlos/Carlos/NSUserDefaultsCacheLevel.swift | 2 | 5019 | import Foundation
import PiedPiper
/**
Default name for the persistent domain used by the NSUserDefaultsCacheLevel
Keep in mind that using this domain for multiple cache levels at the same time could lead to undesired results!
For example, if one of the cache levels get cleared, also the other will be affected unless they save something before leaving the app.
The behavior is not 100% certain and this possibility is discouraged.
*/
private let DefaultUserDefaultsDomainName = "CarlosPersistentDomain"
/// This class is a NSUserDefaults cache level. It has a configurable domain name so that multiple levels can be included in the same sandboxed app.
public class NSUserDefaultsCacheLevel<K: StringConvertible, T: NSCoding>: CacheLevel {
/// The key type of the cache, should be convertible to String values
public typealias KeyType = K
/// The output type of the cache, should conform to NSCoding
public typealias OutputType = T
private let domainName: String
private let lock: ReadWriteLock
private let userDefaults: NSUserDefaults
private var internalDomain: [String: NSData]? = nil
private var safeInternalDomain: [String: NSData] {
if let internalDomain = internalDomain {
return internalDomain
} else {
let fetchedDomain = (userDefaults.persistentDomainForName(domainName) as? [String: NSData]) ?? [:]
internalDomain = fetchedDomain
return fetchedDomain
}
}
/**
Creates a new instance of this NSUserDefaults-based cache level.
- parameter name: The name to use for the persistent domain on NSUserDefaults. Should be unique in your sandboxed app
*/
public init(name: String = DefaultUserDefaultsDomainName) {
self.domainName = name
lock = PThreadReadWriteLock()
userDefaults = NSUserDefaults.standardUserDefaults()
internalDomain = safeInternalDomain
}
/**
Sets a new value for the given key
- parameter value: The value to set for the given key
- parameter key: The key you want to set
This method will convert the value to NSData by using NSCoding and save the data on the persistent domain.
A soft-cache is used to avoid hitting the persistent domain everytime you are going to fetch values from this cache. The operation is thread-safe
*/
public func set(value: OutputType, forKey key: KeyType) {
var softCache = safeInternalDomain
Logger.log("Setting a value for the key \(key.toString()) on the user defaults cache \(self)")
lock.withWriteLock {
softCache[key.toString()] = NSKeyedArchiver.archivedDataWithRootObject(value)
internalDomain = softCache
userDefaults.setPersistentDomain(softCache, forName: domainName)
}
}
/**
Fetches a value on the persistent domain for the given key
- parameter key: The key you want to fetch
- returns: The result of this fetch on the cache
A soft-cache is used to avoid hitting the persistent domain everytime. This operation is thread-safe
*/
public func get(key: KeyType) -> Future<OutputType> {
let result = Promise<OutputType>()
if let cachedValue = lock.withReadLock({ safeInternalDomain[key.toString()] }) {
if let unencodedObject = NSKeyedUnarchiver.su_unarchiveObjectWithData(cachedValue) as? T {
Logger.log("Fetched \(key.toString()) on user defaults level (domain \(domainName)")
result.succeed(unencodedObject)
} else {
Logger.log("Failed fetching \(key.toString()) on the user defaults cache (domain \(domainName), corrupted data")
result.fail(FetchError.InvalidCachedData)
}
} else {
Logger.log("Failed fetching \(key.toString()) on the user defaults cache (domain \(domainName), no data")
result.fail(FetchError.ValueNotInCache)
}
return result.future
}
/**
Completely clears the contents of this cache
Please keep in mind that if the same name is used for multiple cache levels, the contents of these caches will also be cleared, at least from a persistence point of view.
The soft caches of the other levels will still contain consistent values, though, so setting a value on one of these levels will result in the whole previous content of the cache to be persisted on NSUserDefaults, even this may or may not be the desired behavior.
The conclusion is that you should only use the same name for multiple cache levels if you are aware of the consequences. In general the behavior may not be the expected one.
The operation is thread-safe
*/
public func clear() {
lock.withWriteLock {
userDefaults.removePersistentDomainForName(domainName)
internalDomain = [:]
}
}
/**
Clears the contents of the soft cache for this cache level.
Fetching or setting a value after this call is safe, since the content will be pre-fetched from the disk immediately before.
The operation is thread-safe
*/
public func onMemoryWarning() {
lock.withWriteLock {
internalDomain = nil
}
}
} | mit | 40ab18e681a4782518826e5262d09b77 | 39.16 | 265 | 0.72903 | 4.853965 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/PaymentSheet/Views/AfterpayPriceBreakdownView.swift | 1 | 7818 | //
// AfterpayPriceBreakdownView.swift
// StripePaymentSheet
//
// Created by Jaime Park on 6/9/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
import UIKit
import SafariServices
@_spi(STP) import StripeUICore
@_spi(STP) import StripePayments
@_spi(STP) import StripePaymentsUI
/// For internal SDK use only
@objc(STP_Internal_AfterpayPriceBreakdownView)
class AfterpayPriceBreakdownView: UIView {
private let afterPayClearPayLabel = UILabel()
private let theme: ElementsUITheme
private lazy var afterpayMarkImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.image = PaymentSheetImageLibrary.afterpayLogo(locale: locale)
imageView.tintColor = theme.colors.parentBackground.contrastingColor
return imageView
}()
private lazy var afterpayMarkImage: UIImage = {
return PaymentSheetImageLibrary.afterpayLogo(locale: locale)
}()
private lazy var infoImage: UIImage = {
return PaymentSheetImageLibrary.safeImageNamed("afterpay_icon_info@3x")
}()
private lazy var infoURL: URL? = {
let language = locale.languageCode?.lowercased() ?? "en"
let region = locale.regionCode?.uppercased() ?? "US"
let localeCode = "\(language)_\(region)"
return URL(string: "https://static.afterpay.com/modal/\(localeCode).html")
}()
static func numberOfInstallments(currency: String) -> Int {
return currency.uppercased() == "EUR" ? 3 : 4
}
let locale: Locale
init(amount: Int, currency: String, locale: Locale = Locale.autoupdatingCurrent, theme: ElementsUITheme = .default) {
self.locale = locale
self.theme = theme
super.init(frame: .zero)
let numInstallments = Self.numberOfInstallments(currency: currency)
let installmentAmount = amount / numInstallments
let installmentAmountDisplayString = String.localizedAmountDisplayString(for: installmentAmount, currency: currency)
afterPayClearPayLabel.attributedText = generateAfterPayClearPayString(numInstallments: numInstallments,
installmentAmountString: installmentAmountDisplayString)
afterPayClearPayLabel.numberOfLines = 0
afterPayClearPayLabel.translatesAutoresizingMaskIntoConstraints = false
afterPayClearPayLabel.isUserInteractionEnabled = true
addSubview(afterPayClearPayLabel)
NSLayoutConstraint.activate([
afterPayClearPayLabel.leadingAnchor.constraint(
equalTo: leadingAnchor),
afterPayClearPayLabel.topAnchor.constraint(
equalTo: topAnchor),
afterPayClearPayLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
afterPayClearPayLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
])
afterPayClearPayLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapInfoButton)))
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
}
private func generateAfterPayClearPayString(numInstallments: Int, installmentAmountString: String) -> NSMutableAttributedString {
let amountStringAttributes = [
NSAttributedString.Key.font: theme.fonts.subheadlineBold,
.foregroundColor: theme.colors.bodyText
]
let stringAttributes = [
NSAttributedString.Key.font: theme.fonts.subheadline,
.foregroundColor: theme.colors.bodyText
]
let template = STPLocalizedString("Pay in <num_installments/> interest-free payments of <installment_price/> with <img/>",
"Pay in templated string for afterpay/clearpay")
let resultingString = NSMutableAttributedString()
resultingString.append(NSAttributedString(string: ""))
guard let numInstallmentsRange = template.range(of: "<num_installments/>"),
let installmentPrice = template.range(of: "<installment_price/>"),
let img = template.range(of: "<img/>") else {
return resultingString
}
var numInstallmentsAppended = false
var installmentPriceAppended = false
var imgAppended = false
for (indexOffset, currCharacter) in template.enumerated() {
let currIndex = template.index(template.startIndex, offsetBy: indexOffset)
if numInstallmentsRange.contains(currIndex) {
if numInstallmentsAppended {
continue
}
numInstallmentsAppended = true
resultingString.append(NSAttributedString(string: "\(numInstallments)",
attributes: stringAttributes))
} else if installmentPrice.contains(currIndex) {
if installmentPriceAppended {
continue
}
installmentPriceAppended = true
resultingString.append(NSAttributedString(string: installmentAmountString,
attributes: amountStringAttributes))
} else if img.contains(currIndex) {
if imgAppended {
continue
}
imgAppended = true
let titleFont = stringAttributes[NSAttributedString.Key.font] as! UIFont
let clearPay = attributedStringOfImageWithoutLink(uiImage: afterpayMarkImage, font: titleFont)
let infoButton = attributedStringOfImageWithoutLink(uiImage: infoImage, font: titleFont)
resultingString.append(clearPay)
resultingString.append(NSAttributedString(string: "\u{00A0}\u{00A0}", attributes: stringAttributes))
resultingString.append(infoButton)
} else {
resultingString.append(NSAttributedString(string: String(currCharacter),
attributes: stringAttributes))
}
}
return resultingString
}
private func attributedStringOfImageWithoutLink(uiImage: UIImage, font: UIFont) -> NSAttributedString {
let imageAttachment = NSTextAttachment()
imageAttachment.bounds = boundsOfImage(font: font, uiImage: uiImage)
imageAttachment.image = uiImage
return NSAttributedString(attachment: imageAttachment)
}
// https://stackoverflow.com/questions/26105803/center-nstextattachment-image-next-to-single-line-uilabel
private func boundsOfImage(font: UIFont, uiImage: UIImage) -> CGRect {
return CGRect(x: 0,
y: (font.capHeight - uiImage.size.height).rounded() / 2,
width: uiImage.size.width,
height: uiImage.size.height)
}
@objc
private func didTapInfoButton() {
if let url = infoURL {
let safariController = SFSafariViewController(url: url)
safariController.modalPresentationStyle = .overCurrentContext
parentViewController?.present(safariController, animated: true)
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
afterpayMarkImageView.tintColor = theme.colors.parentBackground.contrastingColor
}
}
private extension UIResponder {
var parentViewController: UIViewController? {
return next as? UIViewController ?? next?.parentViewController
}
}
| mit | 30d6c853c91a615cf4e799c103371b48 | 43.414773 | 134 | 0.651145 | 5.398481 | false | false | false | false |
dtweston/Tribute | Example/TributeExample-OSX/AppDelegate.swift | 1 | 1696 | //
// AppDelegate.swift
// TributeExample-OSX
//
// Created by Dave Weston on 5/16/15.
// Copyright (c) 2015 Dave Weston. All rights reserved.
//
import Cocoa
import Tribute
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet var textView: NSTextView!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
self.textView.editable = false
// self.textView.delegate = self
let parser = Parser()
let emojiLookup = ["ok": GithubEmoji(name: "ok", url: NSURL(string: "https://assets-cdn.github.com/images/icons/emoji/unicode/1f44d.png?v5")!)]
let githubPlainTextHandler = GithubPlainTextHandler(emojiLookup: emojiLookup)
let renderer = AttributedStringRenderer(plainTextHandler: githubPlainTextHandler)
if let url = NSBundle.mainBundle().URLForResource("AFNetworking-README", withExtension: "md") {
if let data = NSData(contentsOfURL: url) {
if let str = String(data: data, encoding: NSUTF8StringEncoding) {
parser.parseMarkdown(str, renderer: renderer)
}
}
}
self.textView.textContainer?.replaceLayoutManager(MarkdownLayoutManager())
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue()) { () -> Void in
self.textView.textStorage?.setAttributedString(renderer.finalString)
}
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| mit | f3a0db7c957cb9497e1abee2edfd6d75 | 33.612245 | 151 | 0.668632 | 4.63388 | false | false | false | false |
exsortis/PnutKit | Sources/PnutKit/Models/LoginResponse.swift | 1 | 866 | import Foundation
public struct LoginResponse {
public let accessToken : String
public let token : Token
public let userId : String
public let username : String
}
extension LoginResponse : Serializable {
public init?(from json : JSONDictionary) {
guard
let accessToken = json["access_token"] as? String,
let t = json["token"] as? [String : Any],
let token = Token(from: t),
let userId = json["user_id"] as? String,
let username = json["username"] as? String
else { return nil }
self.accessToken = accessToken
self.token = token
self.userId = userId
self.username = username
}
public func toDictionary() -> JSONDictionary {
let dict : JSONDictionary = [
:
]
return dict
}
}
| mit | 1b006b0114877c80a350c8f892ea2de4 | 22.405405 | 62 | 0.570439 | 4.837989 | false | false | false | false |
jemmons/SessionArtist | Sources/SessionArtist/Params.swift | 1 | 2462 | import Foundation
public enum Params {
case form([URLQueryItem]), json(ValidJSONObject)
public init(_ form: [URLQueryItem]) {
self = .form(form)
}
public init(_ json: ValidJSONObject) {
self = .json(json)
}
public func makeQuery() -> [URLQueryItem] {
switch self {
case .form(let qs):
return qs
case .json(let j):
return Helper.makeQuery(from: j)
}
}
public func makeData() -> Data {
switch self {
case .form(let qs):
var comp = URLComponents()
comp.queryItems = qs
guard let query = comp.query else {
preconditionFailure("“queryItems” somehow wasn’t set.")
}
return Data(query.utf8)
case .json(let j):
guard let jsonData = try? JSONSerialization.data(withJSONObject: j.value, options: []) else {
preconditionFailure("ValidJSONObject wasn’t valid.")
}
return jsonData
}
}
public var contentType: [HTTPHeaderField: String] {
switch self {
case .form:
return [.contentType: "application/x-www-form-urlencoded"]
case .json:
return [.contentType: "application/json"]
}
}
}
private enum Helper {
static func makeQuery(from json: ValidJSONObject) -> [URLQueryItem] {
// Assume it won't throw becasue we're enforcing JSONObject type.
// swiftlint:disable:next force_try
return try! makeQuery(from: json.value, prefix: nil)
}
/**
Generalized version to allow for recursion.
- throws: `notJSONObject` if not called (initially) on a JSONObject.
*/
private static func makeQuery(from jsonValue: Any, prefix: String? = nil) throws -> [URLQueryItem] {
var items: [URLQueryItem] = []
switch jsonValue {
case let object as JSONObject:
try object.forEach { key, value in
let nextPrefix = prefix?.appending("[\(key)]") ?? key
items.append(contentsOf: try makeQuery(from: value, prefix: nextPrefix))
}
case let array as JSONArray:
guard let somePrefix = prefix else {
throw Error.notJSONObject
}
try array.forEach { element in
items.append(contentsOf: try makeQuery(from: element, prefix: somePrefix + "[]"))
}
default:
guard let somePrefix = prefix else {
throw Error.notJSONObject
}
items.append(URLQueryItem(name: somePrefix, value: String(describing: jsonValue)))
}
return items
}
}
| mit | df8ff6480102596a33590467bdd64b06 | 24.040816 | 102 | 0.624287 | 4.29021 | false | false | false | false |
1457792186/JWSwift | 熊猫TV2/Pods/Kingfisher/Sources/Kingfisher.swift | 115 | 2226 | //
// Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 16/9/14.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import ImageIO
#if os(macOS)
import AppKit
public typealias Image = NSImage
public typealias Color = NSColor
public typealias ImageView = NSImageView
typealias Button = NSButton
#else
import UIKit
public typealias Image = UIImage
public typealias Color = UIColor
#if !os(watchOS)
public typealias ImageView = UIImageView
typealias Button = UIButton
#endif
#endif
public final class Kingfisher<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
/**
A type that has Kingfisher extensions.
*/
public protocol KingfisherCompatible {
associatedtype CompatibleType
var kf: CompatibleType { get }
}
public extension KingfisherCompatible {
public var kf: Kingfisher<Self> {
get { return Kingfisher(self) }
}
}
extension Image: KingfisherCompatible { }
#if !os(watchOS)
extension ImageView: KingfisherCompatible { }
extension Button: KingfisherCompatible { }
#endif
| apache-2.0 | 9249060ba0423c156c2e792aa427bbd8 | 30.352113 | 81 | 0.727314 | 4.425447 | false | false | false | false |
kmikiy/SpotMenu | SpotMenu/StatusBar/StatusItemBuilder.swift | 1 | 2320 | //
// StatusItemBuilder.swift
// SpotMenu
//
// Created by Miklós Kristyán on 2017. 05. 01..
// Copyright © 2017. KM. All rights reserved.
//
import Foundation
final class StatusItemBuilder {
// MARK: - Properties
private var title = ""
private var artist = ""
private var albumName = ""
private var playingIcon = ""
private var isPlaying: Bool = false
private var hideWhenPaused = false
// MARK: - Lifecycle method
init(title: String?, artist: String?, albumName: String?, isPlaying: Bool) {
if let v = title {
self.title = v
}
if let v = artist {
self.artist = v
}
if let v = albumName {
self.albumName = v
}
self.isPlaying = isPlaying
}
// MARK: - Methods
func hideWhenPaused(v: Bool) -> StatusItemBuilder {
hideWhenPaused = v
return self
}
func showTitle(v: Bool) -> StatusItemBuilder {
if !v {
title = ""
return self
}
if !isPlaying && hideWhenPaused {
title = ""
return self
}
return self
}
func showArtist(v: Bool) -> StatusItemBuilder {
if !v {
artist = ""
return self
}
if !isPlaying && hideWhenPaused {
artist = ""
return self
}
return self
}
func showAlbumName(v: Bool) -> StatusItemBuilder {
if !v {
albumName = ""
return self
}
if !isPlaying && hideWhenPaused {
albumName = ""
return self
}
return self
}
func showPlayingIcon(v: Bool) -> StatusItemBuilder {
if !v {
playingIcon = ""
return self
}
if isPlaying {
playingIcon = "♫ "
} else {
playingIcon = ""
}
return self
}
func getString() -> String {
if artist.count != 0 && title.count != 0 && albumName.count != 0 {
return "\(playingIcon)\(artist) - \(title) - \(albumName)"
} else if artist.count != 0 && title.count != 0 {
return "\(playingIcon)\(artist) - \(title)"
}
return "\(playingIcon)\(artist)\(title)"
}
}
| mit | 53736eb1b59056ada8d6959825ddeca7 | 21.920792 | 80 | 0.493305 | 4.575099 | false | false | false | false |
zwaldowski/ParksAndRecreation | Latest/Combinatorial Parsers.playground/Contents.swift | 1 | 5828 | // Inspired by:
// - http://khanlou.com/2019/12/regex-vs-combinatorial-parsing/
// - https://github.com/pointfreeco/episode-code-samples/blob/master/0064-parser-combinators-pt3/ParserCombinators.playground/Contents.swift
let int = Parsers.PrefixWhile { $0.isNumber }
.map { Swift.Int($0) }
int.match("42")
int.match("42.0")
let double = Parsers.PrefixWhile { $0.isNumber || $0 == "." }
.map { Swift.Double($0) }
double.match("42")
double.match("42.0")
let zeroOrMoreSpaces = Parsers.PrefixWhile { $0 == " " }
zeroOrMoreSpaces.match(" Hello, world!")
zeroOrMoreSpaces.match("Hello, world!")
let oneOrMoreSpaces = zeroOrMoreSpaces.filter { !$0.isEmpty }
oneOrMoreSpaces.match(" Hello, world!")
oneOrMoreSpaces.match("Hello, world!")
// MARK: -
extension Coordinate: Parseable {
static let northSouth = Parsers.First()
.map {
$0 == "N" ? 1.0
: $0 == "S" ? -1.0
: nil
}
static let latitude = double
.zip(Parsers.Literal("°"), oneOrMoreSpaces, northSouth)
.map { degrees, _, _, sign in degrees * sign }
static let eastWest = Parsers.First()
.map {
$0 == "E" ? 1.0
: $0 == "W" ? -1.0
: nil
}
static let longitude = double
.zip(Parsers.Literal("°"), oneOrMoreSpaces, eastWest)
.map { degrees, _, _, sign in
degrees * sign
}
public static let parser = latitude
.zip(Parsers.Literal(","), oneOrMoreSpaces, longitude)
.map { latitude, _, _, longitude in
Coordinate(latitude: latitude, longitude: longitude)
}
}
Coordinate(parsing: "40.446° N, 79.982° W")
// MARK: -
extension Currency: Parseable {
public static let parser = Parsers.OneOf3(
Parsers.Literal("€").map(Currency.eur),
Parsers.Literal("£").map(Currency.gbp),
Parsers.Literal("$").map(Currency.usd)
)
}
Currency(parsing: "€")
// MARK: -
extension Money: Parseable {
static let gainParser = Currency.parser
.zip(double)
.map(Money.init)
static let lossParser = gainParser
.surrounded(by: Parsers.Literal("("), Parsers.Literal(")"))
.map { (_, money, _) in money.negated }
public static let parser = gainParser.or(lossParser)
var negated: Money {
Money(currency: currency, value: -value)
}
}
Money.gainParser.match("€42")
Money.gainParser.match("£42")
Money.gainParser.match("$42")
// MARK: -
Money.gainParser
.zeroOrMore(separatedBy: Parsers.Literal(","))
.match("€42,£42,$42,")
let commaOrNewline = Parsers.First()
.filter { $0 == "," || $0 == "\n" }
Money.gainParser
.zeroOrMore(separatedBy: commaOrNewline)
.match("""
€42,£42,$42
€42,£42,$42
€42,£42,$42,฿10
""")
Money.lossParser.match("($19.00)")
Money(parsing: "£19.00")
Money(parsing: "(£19.00)")
// MARK: -
extension Location: Parseable {
public static let parser = Parsers.OneOf3(
Parsers.Literal("New York City").map(Location.nyc),
Parsers.Literal("Berlin").map(Location.berlin),
Parsers.Literal("London").map(Location.london))
}
extension Race: Parseable {
static let pathParser = Coordinate.parser.zeroOrMore(separatedBy: "\n")
public static let parser = Location.parser
.zip(Parsers.Literal(","), oneOrMoreSpaces, Money.parser, Parsers.Literal("\n"), pathParser)
.map { location, _, _, entranceFee, _, path in
Race(location: location, entranceFee: entranceFee, path: path)
}
static let arrayParser = parser.zeroOrMore(separatedBy: "\n---\n")
}
let upcomingRaces = Race.arrayParser
.match("""
New York City, $300
40.60248° N, 74.06433° W
40.61807° N, 74.02966° W
40.64953° N, 74.00929° W
40.67884° N, 73.98198° W
40.69894° N, 73.95701° W
40.72791° N, 73.95314° W
40.74882° N, 73.94221° W
40.75740° N, 73.95309° W
40.76149° N, 73.96142° W
40.77111° N, 73.95362° W
40.80260° N, 73.93061° W
40.80409° N, 73.92893° W
40.81432° N, 73.93292° W
40.80325° N, 73.94472° W
40.77392° N, 73.96917° W
40.77293° N, 73.97671° W
---
Berlin, €100
13.36015° N, 52.51516° E
13.33999° N, 52.51381° E
13.32539° N, 52.51797° E
13.33696° N, 52.52507° E
13.36454° N, 52.52278° E
13.38152° N, 52.52295° E
13.40072° N, 52.52969° E
13.42555° N, 52.51508° E
13.41858° N, 52.49862° E
13.40929° N, 52.48882° E
13.37968° N, 52.49247° E
13.34898° N, 52.48942° E
13.34103° N, 52.47626° E
13.32851° N, 52.47122° E
13.30852° N, 52.46797° E
13.28742° N, 52.47214° E
13.29091° N, 52.48270° E
13.31084° N, 52.49275° E
13.32052° N, 52.50190° E
13.34577° N, 52.50134° E
13.36903° N, 52.50701° E
13.39155° N, 52.51046° E
13.37256° N, 52.51598° E
---
London, £500
51.48205° N, 0.04283° E
51.47439° N, 0.02170° E
51.47618° N, 0.02199° E
51.49295° N, 0.05658° E
51.47542° N, 0.03019° E
51.47537° N, 0.03015° E
51.47435° N, 0.03733° E
51.47954° N, 0.04866° E
51.48604° N, 0.06293° E
51.49314° N, 0.06104° E
51.49248° N, 0.04740° E
51.48888° N, 0.03564° E
51.48655° N, 0.01830° E
51.48085° N, 0.02223° W
51.49210° N, 0.04510° W
51.49324° N, 0.04699° W
51.50959° N, 0.05491° W
51.50961° N, 0.05390° W
51.49950° N, 0.01356° W
51.50898° N, 0.02341° W
51.51069° N, 0.04225° W
51.51056° N, 0.04353° W
51.50946° N, 0.07810° W
51.51121° N, 0.09786° W
51.50964° N, 0.11870° W
51.50273° N, 0.13850° W
51.50095° N, 0.12411° W
""")
| mit | 8b62dd13573a17f03bed957eeeb12d77 | 24.75 | 140 | 0.582877 | 2.807235 | false | false | false | false |
felixjendrusch/ValueTransformer | ValueTransformerTests/ReversibleValueTransformerSpecs.swift | 1 | 9100 | // Copyright (c) 2015 Felix Jendrusch. All rights reserved.
import Quick
import Nimble
import Result
import ValueTransformer
struct ReversibleValueTransformers {
static let string = combine(ValueTransformers.string, ValueTransformers.int)
}
class ReversibleValueTransformerSpecs: QuickSpec {
override func spec() {
describe("A (combined) ReversibleValueTransformer") {
let valueTransformer = ReversibleValueTransformers.string
it("should transform a value") {
let result = valueTransformer.transform("1")
expect(result.value).to(equal(1))
}
it("should fail if its value transformation fails") {
let result = valueTransformer.transform("1.5")
expect(result.value).to(beNil())
}
it("should reverse transform a value") {
let result = valueTransformer.reverseTransform(2)
expect(result.value).to(equal("2"))
}
it("should fail if its reverse value transformation fails") {
let result = flip(valueTransformer).reverseTransform("2.5")
expect(result.value).to(beNil())
}
}
describe("A flipped ReversibleValueTransformer") {
let valueTransformer = flip(ReversibleValueTransformers.string)
it("should transform a value") {
let result = valueTransformer.transform(3)
expect(result.value).to(equal("3"))
}
it("should fail if its value transformation fails") {
let result = flip(valueTransformer).transform("3.5")
expect(result.value).to(beNil())
}
it("should reverse transform a value") {
let result = valueTransformer.reverseTransform("4")
expect(result.value).to(equal(4))
}
it("should fail if its reverse value transformation fails") {
let result = valueTransformer.reverseTransform("4.5")
expect(result.value).to(beNil())
}
}
describe("Composed reversible value transformes") {
let valueTransformer = ReversibleValueTransformers.string >>> flip(ReversibleValueTransformers.string)
it("should transform a value") {
let result = valueTransformer.transform("3")
expect(result.value).to(equal("3"))
}
it("should fail if any of its value transformation fails") {
let result = valueTransformer.transform("3.5")
expect(result.value).to(beNil())
}
it("should reverse transform a value") {
let result = valueTransformer.reverseTransform("4")
expect(result.value).to(equal("4"))
}
it("should fail if its reverse value transformation fails") {
let result = valueTransformer.reverseTransform("4.5")
expect(result.value).to(beNil())
}
}
describe("Lifted reversible value transformers") {
context("with optional value") {
let valueTransformer: ReversibleValueTransformer<String?, Int, NSError> = lift(ReversibleValueTransformers.string, defaultTransformedValue: 0)
context("if given some value") {
it("should transform a value") {
let result = valueTransformer.transform("5")
expect(result.value).to(equal(5))
}
it("should fail if its value transformation fails") {
let result = valueTransformer.transform("5.5")
expect(result.value).to(beNil())
}
}
context("if not given some value") {
it("should transform to the default transformed value") {
let result = valueTransformer.transform(nil)
expect(result.value).to(equal(0))
}
}
it("should reverse transform a value") {
let result = valueTransformer.reverseTransform(6)
expect(result.value!).to(equal("6"))
}
it("should fail if its reverse value transformation fails") {
let result = flip(valueTransformer).reverseTransform("6.5")
expect(result.value).to(beNil())
}
}
context("with optional transformed value") {
let valueTransformer: ReversibleValueTransformer<String, Int?, NSError> = lift(ReversibleValueTransformers.string, defaultReverseTransformedValue: "zero")
it("should transform a value") {
let result = valueTransformer.transform("7")
expect(result.value!).to(equal(7))
}
it("should fail if its value transformation fails") {
let result = valueTransformer.transform("7.5")
expect(result.value).to(beNil())
}
context("if given some transformed value") {
it("should reverse transform a value") {
let result = valueTransformer.reverseTransform(8)
expect(result.value).to(equal("8"))
}
it("should fail if its value transformation fails") {
let result = flip(valueTransformer).reverseTransform("8.5")
expect(result.value).to(beNil())
}
}
context("if not given some transformed value") {
it("should transform to the default value") {
let result = valueTransformer.reverseTransform(nil)
expect(result.value).to(equal("zero"))
}
}
}
context("with optional value and transformed value") {
let valueTransformer: ReversibleValueTransformer<String?, Int?, NSError> = lift(ReversibleValueTransformers.string)
context("if given some value") {
it("should transform a value") {
let result = valueTransformer.transform("9")
expect(result.value!).to(equal(9))
}
it("should fail if its value transformation fails") {
let result = valueTransformer.transform("9.5")
expect(result.value).to(beNil())
}
}
context("if not given some value") {
it("should transform to nil") {
let result = valueTransformer.transform(nil)
expect(result.value!).to(beNil())
}
}
context("if given some transformed value") {
it("should reverse transform a value") {
let result = valueTransformer.reverseTransform(10)
expect(result.value!).to(equal("10"))
}
it("should fail if its value transformation fails") {
let result = flip(valueTransformer).reverseTransform("10.5")
expect(result.value).to(beNil())
}
}
context("if not given some transformed value") {
it("should transform to nil") {
let result = valueTransformer.reverseTransform(nil)
expect(result.value!).to(beNil())
}
}
}
context("with array value and transformed value") {
let valueTransformer: ReversibleValueTransformer<[String], [Int], NSError> = lift(ReversibleValueTransformers.string)
it("should transform a value") {
let result = valueTransformer.transform([ "11", "12" ])
expect(result.value).to(equal([ 11, 12 ]))
}
it("should fail if any of its value transformation fails") {
let result = valueTransformer.transform([ "11", "12.5" ])
expect(result.value).to(beNil())
}
it("should reverse transform a value") {
let result = valueTransformer.reverseTransform([ 13, 14 ])
expect(result.value).to(equal([ "13", "14" ]))
}
it("should fail if its reverse value transformation fails") {
let result = flip(valueTransformer).reverseTransform([ "13", "14.5" ])
expect(result.value).to(beNil())
}
}
}
}
}
| mit | e45d8b37af04d4d12dcbec7cf568df86 | 34.968379 | 170 | 0.511758 | 5.48854 | false | false | false | false |
53ningen/todo | TODO/DB/Realm/Objects/IssueObject.swift | 1 | 2726 | import Foundation
import RealmSwift
/// RealmのIssueテーブルスキーマを規定するRecordObject
class IssueObject: Object {
dynamic var id: String = ""
dynamic var title: String = ""
dynamic var desc: String = ""
dynamic var state: String = ""
let labels: List<LabelObject> = List<LabelObject>() //=> LabelObject と many-to-many のリレーション
dynamic var milestone: MilestoneObject? = nil //=> MilestoneObject と one-to-many のリレーション
dynamic var locked: Bool = false
dynamic var createdAt: RealmDate = 0
dynamic var updatedAt: RealmDate = 0
let closedAt: RealmOptional<RealmDate> = RealmOptional<RealmDate>.init()
static func of(_ id: String, info: IssueInfo) -> IssueObject {
let obj = IssueObject()
obj.id = id
obj.title = info.title
obj.desc = info.desc
obj.state = info.state.rawValue
let realm = try! Realm()
let labelObjs = info.labels.flatMap { realm.object(ofType: LabelObject.self, forPrimaryKey: $0.id.value as AnyObject) }
obj.labels.append(objectsIn: labelObjs)
info.milestone.forEach { obj.milestone = realm.object(ofType: MilestoneObject.self, forPrimaryKey: $0.id.value as AnyObject) }
obj.locked = info.locked
obj.createdAt = info.createdAt
obj.updatedAt = info.updatedAt
obj.closedAt.value = info.state.closedAt
return obj
}
override static func primaryKey() -> String? {
return "id"
}
override static func indexedProperties() -> [String] {
return ["id", "title"]
}
func close(_ at: RealmDate) {
self.state = IssueState.closed(closedAt: at).rawValue
self.closedAt.value = at
self.updatedAt = at
}
func open() {
self.state = IssueState.open.rawValue
self.closedAt.value = nil
self.updatedAt = Int64(Foundation.Date().timeIntervalSince1970)
}
func update(_ info: IssueInfo) {
title = info.title
desc = info.desc
state = info.state.rawValue
let realm = try! Realm()
let labelObjs = info.labels.flatMap { realm.object(ofType: LabelObject.self, forPrimaryKey: $0.id.value as AnyObject) }
labels.removeAll()
labels.append(objectsIn: labelObjs)
if let milestoneId = info.milestone?.id.value {
self.milestone = realm.object(ofType: MilestoneObject.self, forPrimaryKey: milestoneId as AnyObject)
} else {
self.milestone = nil
}
locked = info.locked
createdAt = info.createdAt
updatedAt = info.updatedAt
closedAt.value = info.state.closedAt
}
}
| mit | 766492ac125ec0d4a0e2b208cdd3e2fc | 35.027027 | 134 | 0.632783 | 4.114198 | false | false | false | false |
Quick/Quick | Sources/Quick/Callsite.swift | 21 | 1605 | import Foundation
#if canImport(Darwin)
// swiftlint:disable type_name
@objcMembers
public class _CallsiteBase: NSObject {}
#else
public class _CallsiteBase: NSObject {}
// swiftlint:enable type_name
#endif
// Ideally we would always use `StaticString` as the type for tracking the file name
// in which an example is defined, for consistency with `assert` etc. from the
// stdlib, and because recent versions of the XCTest overlay require `StaticString`
// when calling `XCTFail`. Under the Objective-C runtime (i.e. building on macOS), we
// have to use `String` instead because StaticString can't be generated from Objective-C
#if SWIFT_PACKAGE
public typealias FileString = StaticString
#else
public typealias FileString = String
#endif
/**
An object encapsulating the file and line number at which
a particular example is defined.
*/
final public class Callsite: _CallsiteBase {
/**
The absolute path of the file in which an example is defined.
*/
public let file: FileString
/**
The line number on which an example is defined.
*/
public let line: UInt
internal init(file: FileString, line: UInt) {
self.file = file
self.line = line
}
}
extension Callsite {
/**
Returns a boolean indicating whether two Callsite objects are equal.
If two callsites are in the same file and on the same line, they must be equal.
*/
@nonobjc public static func == (lhs: Callsite, rhs: Callsite) -> Bool {
return String(describing: lhs.file) == String(describing: rhs.file) && lhs.line == rhs.line
}
}
| apache-2.0 | fe4aaf43012170d2de980f3e9c5d778c | 29.865385 | 99 | 0.700312 | 4.268617 | false | false | false | false |
finder39/Swimgur | SWNetworking/jsonDictionaryHelpers.swift | 1 | 2591 | //
// jsonDictionaryHelpers.swift
// iCracked
//
// Created by Joe Neuman on 10/30/14.
// Copyright (c) 2014. All rights reserved.
//
import Foundation
func getBool(object:AnyObject?) -> Bool? {
if let temp = object as? Bool {
return temp
} else if let temp = object as? NSNumber {
return temp.boolValue
} else if let temp = object as? Int {
return Bool(temp)
} else if let temp = object as? String {
return (temp as NSString).boolValue
} else {
return nil
}
}
// TODO: Currently using getDateFormatter() from Constants singleton. This should be seperated out. Possibly added to ICNetworking singleton?
// Reason for this is because NSDateFormatter is expensive to alloc
/*func getDate(object:AnyObject?) -> NSDate? {
if let tempObject = getString(object) {
return ICNetworking.getDateFormatter().dateFromString(tempObject)
} else {
return nil
}
}*/
func getDictionary(object:AnyObject?) -> Dictionary<String, AnyObject>? {
return object as AnyObject? as? Dictionary<String, AnyObject>
}
func getString(object:AnyObject?) -> String? {
if let temp: AnyObject = object as AnyObject? {
if let temp2 = temp as? String {
return temp2
} else if let temp2 = temp as? Float {
// check if it is actually an int
if temp2 == Float(Int(temp2)) {
return String(Int(temp2))
} else {
return "\(temp2)"
}
} else if let temp2 = temp as? Int {
return String(temp2)
} else {
return nil
}
} else {
return nil
}
}
func getDouble(object:AnyObject?) -> Double? {
if let temp: AnyObject = object as AnyObject? {
if let temp2 = temp as? Double {
return temp2
} else if let temp2 = temp as? Int {
return Double(temp2)
} else if let temp2 = temp as? String {
return (temp2 as NSString).doubleValue
} else if let temp2 = temp as? NSNumber {
// NSNumber behaves strangely, 123.456 will become 123.456001281738
return Double(temp2)
}else {
return nil
}
} else {
return nil
}
}
func getFloat(object:AnyObject?) -> Float? {
if let temp: AnyObject = object as AnyObject? {
if let temp2 = temp as? Float {
return temp2
} else if let temp2 = temp as? Int {
return Float(temp2)
} else if let temp2 = temp as? String {
return (temp2 as NSString).floatValue
} else {
return nil
}
} else {
return nil
}
}
func getArray(object:AnyObject?) -> [AnyObject]? {
if let temp: [AnyObject] = object as [AnyObject]? {
return temp
} else {
return nil
}
} | mit | 27eb74e650dc13b169ea199f611f440a | 24.663366 | 141 | 0.635662 | 3.793558 | false | false | false | false |
TellMeAMovieTeam/TellMeAMovie_iOSApp | TellMeAMovie/TellMeAMovie/Settings.swift | 1 | 5622 | //
// Settings.swift
// TellMeAMovie
//
// Created by Илья on 26.11.16.
// Copyright © 2016 IlyaGutnikov. All rights reserved.
//
import Foundation
import TMDBSwift
/// Структура, которая хранит в себе все основыне данные о настройках
public class Settings : NSObject, NSCoding {
var selectedGenre : Genre
var minYear : Int = 0
var maxYear : Int = 0
var minRating : Float = 0.0
var maxRating : Float = 0.0
public init(selectedGenre : Genre, minYear : Int, maxYear : Int, minRating : Float, maxRating : Float) {
self.selectedGenre = selectedGenre
self.minYear = minYear
self.maxYear = maxYear
self.minRating = minRating
self.maxRating = maxRating
}
public override init() {
self.selectedGenre = Genre.init()
self.minYear = 0
self.maxYear = 0
self.minRating = 0.0
self.maxRating = 0.0
}
required convenience public init(coder aDecoder: NSCoder) {
let genreId = aDecoder.decodeInteger(forKey: "TellMeAMovie_Settings_Genre_id")
let genreName = aDecoder.decodeObject(forKey: "TellMeAMovie_Settings_Genre_name") as! String
let genre = Genre(genreName: genreName, genreId: genreId)
let minYear = aDecoder.decodeInteger(forKey: "TellMeAMovie_Settings_minYear")
let maxYear = aDecoder.decodeInteger(forKey: "TellMeAMovie_Settings_maxYear")
let minRating = aDecoder.decodeFloat(forKey: "TellMeAMovie_Settings_minRating")
let maxRating = aDecoder.decodeFloat(forKey: "TellMeAMovie_Settings_maxRating")
self.init(selectedGenre : genre, minYear : minYear, maxYear : maxYear, minRating : minRating, maxRating : maxRating)
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.selectedGenre.genreId, forKey: "TellMeAMovie_Settings_Genre_id")
aCoder.encode(self.selectedGenre.genreName, forKey: "TellMeAMovie_Settings_Genre_name")
aCoder.encode(self.minYear, forKey: "TellMeAMovie_Settings_minYear")
aCoder.encode(self.maxYear, forKey: "TellMeAMovie_Settings_maxYear")
aCoder.encode(self.minRating, forKey: "TellMeAMovie_Settings_minRating")
aCoder.encode(self.maxRating, forKey: "TellMeAMovie_Settings_maxRating")
}
/// Сохраняет настройки в UD
public func saveSettingsToUserDef() {
let settings : Settings = Settings.init(selectedGenre: self.selectedGenre, minYear: self.minYear, maxYear: self.maxYear, minRating: self.minRating, maxRating: self.maxRating)
/*
print("saveSettingsToUserDef settings.selectedGenre.genreName \(settings.selectedGenre.genreName)")
print("saveSettingsToUserDef settings.selectedCountry \(settings.selectedCountry)")
print("saveSettingsToUserDef settings.minRating \(settings.minRating)")
print("saveSettingsToUserDef settings.maxRating \(settings.maxRating)")
print("saveSettingsToUserDef settings.minYear \(settings.minYear)")
print("saveSettingsToUserDef settings.maxYear \(settings.maxYear)")
*/
let data = NSKeyedArchiver.archivedData(withRootObject: settings)
let defaults = UserDefaults.standard
defaults.set(data, forKey:"TellMeAMovie_Settings" )
}
/// Получает и выставляет информацию из UD
public func getSettingsFromUserDef() {
if let decoded = UserDefaults.standard.object(forKey: "TellMeAMovie_Settings") as! Data? {
let decodedSettings = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! Settings
/*
print("getSettingsFromUserDef settings.selectedGenre.genreName \(decodedSettings.selectedGenre.genreName)")
print("getSettingsFromUserDef settings.selectedCountry \(decodedSettings.selectedCountry)")
print("getSettingsFromUserDef settings.minRating \(decodedSettings.minRating)")
print("getSettingsFromUserDef settings.maxRating \(decodedSettings.maxRating)")
print("getSettingsFromUserDef settings.minYear \(decodedSettings.minYear)")
print("getSettingsFromUserDef settings.maxYear \(decodedSettings.maxYear)")
*/
self.selectedGenre = decodedSettings.selectedGenre
self.minYear = decodedSettings.minYear
self.maxYear = decodedSettings.maxYear
self.minRating = decodedSettings.minRating
self.maxRating = decodedSettings.maxRating
} else {
self.selectedGenre = Genre.init(genreName: "боевик", genreId: Int(MovieGenres.Action.rawValue)!)
self.minYear = 1950
self.maxYear = getCurrentYear()
self.minRating = 0
self.maxRating = 10
}
}
}
public func saveCurrentSelectedMovieIndex(selectedMovieIndex : Int) {
UserDefaults.standard.set(selectedMovieIndex, forKey: "TellMeAMovie_selectedMovieIndex")
}
public func getCurrentSelectedMovieIndex() -> Int {
if let selectedMovieIndex : Int = UserDefaults.standard.integer(forKey: "TellMeAMovie_selectedMovieIndex") {
return selectedMovieIndex
} else {
return -1
}
}
public func removeCurrentSelectedMovieIndex() {
UserDefaults.standard.removeObject(forKey: "TellMeAMovie_selectedMovieIndex")
}
| apache-2.0 | 8edafd5d1ed220cfafca6667cae8be5c | 38.328571 | 182 | 0.666546 | 4.311668 | false | false | false | false |
rnfiqley/Test | ViewController.swift | 1 | 5685 |
import UIKit
import Alamofire
import AlamofireXmlToObjects
import EVReflection
import XMLDictionary
class cmmMsgHeaderCls : EVObject{
var requestMsgId : String?
var responseMsgId : String?
var responseTime : String?
var successYN : String?
var returnCode : String?
var errMsg : String?
var totalCount : String?
var countPerPage : String?
var totalPage : String?
var currentPage : String?
}
class NewAddressListResponse : EVObject{
var cmmMsgHeader : cmmMsgHeaderCls = cmmMsgHeaderCls()
var newAddressListAreaCd: [NewAddressListAreaCdCls] = [NewAddressListAreaCdCls]()
}
class NewAddressListSingleResponse : EVObject{
var cmmMsgHeader : cmmMsgHeaderCls = cmmMsgHeaderCls()
var newAddressListAreaCd: NewAddressListAreaCdCls = NewAddressListAreaCdCls()
}
class NewAddressListAreaCdCls : EVObject{
var zipNo : String?
var lnmAdres : String?
var rnAdres : String?
}
/////
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var searchField: UITextField! // 텍스트 입력받는 부분.
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var tableView: UITableView!
var ResultHeader: cmmMsgHeaderCls!
var ResultArray: [NewAddressListAreaCdCls] = [NewAddressListAreaCdCls]() // 주소 결과 저장위해
var segment : String = "dong"
var segueIndexRow : Int? //내가 받아온 검색해서 나온 결과들을 클릭을 해서 맵을 찾아야 되는데, 몇번째 테이블뷰인지를 인덱스값에 저장하는거
override func viewDidLoad() {
super.viewDidLoad()
//EVReflection.setBundleIdentifier(NewAddressListAreaCdCls)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ResultArray.count //테이블뷰 전체에 몇개의 요소가 들어가는지 결정하려고 씀
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //각셀에 들어갈 내용을 결정하는 함수.
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("AddressCell",forIndexPath: indexPath)
let zipNo = ResultArray[indexPath.row].zipNo
let lnmAdres = ResultArray[indexPath.row].lnmAdres // 도로명주소
let rnAdres = ResultArray[indexPath.row].rnAdres // 지번주소
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.textLabel?.text = "우편번호 : " + zipNo! + "\n지번주소 : " + lnmAdres! + "\n도로명 주소 : " + rnAdres!
return cell
}
@IBAction func indexChanged(sender: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex
{
case 0:
segment = "dong";
case 1:
segment = "road";
case 2:
segment = "post";
default:
break;
}
}
@IBAction func onSearchbuttonClick(sender: UIButton) { //검색버튼 눌렀을때 호출
let paras : [String:String] = //
[
"serviceKey": "ex0TP/ZK4NEE1l6dFzEuRW3kIOemE+ENUaP7XQGsYWHSjB8AMIk5PxnJmBSoBOyTCxMipm8KW6f0MyHTtzJbYA==",//서비스키 디코드한것.
"searchSe": segment, //
"srchwrd": searchField.text!, //검색하고싶은 단어 넣는 곳.
]
let URL = "http://openapi.epost.go.kr/postal/retrieveNewAdressAreaCdService/retrieveNewAdressAreaCdService/getNewAddressListAreaCd" //쿼리 보내기 전까지의 유알엘
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {//세그가 불리기 전에 먼저 함수 호출을 한다 . 세그는 넘어가는 동작. 뷰가 넘어가는 ㅈ동작
let destinationVC = segue.destinationViewController as! MapViewController //가는 곳의 클래스를 받아온거
destinationVC.AddressData = ResultArray[segueIndexRow!].lnmAdres
}
@IBAction func unwindToVC(segue: UIStoryboardSegue) {
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
segueIndexRow = indexPath.row
self.performSegueWithIdentifier("playerSegue", sender: self)
}
func singleRequest(url: String, param: [String:String]){
Alamofire.request(.GET, url, parameters:param).responseObject { (response: Result<NewAddressListSingleResponse,NSError>)in
if let result = response.value {
self.ResultArray.append(result.newAddressListAreaCd)
self.tableView.reloadData() //갱신
} else {
print("Error")
}
}
}
func multipleRequest(url: String, param: [String:String]){
Alamofire.request(.GET, url, parameters:param).responseObject { (response: Result<NewAddressListResponse,NSError>)in
if let result = response.value {
for newAddressResult in result.newAddressListAreaCd //for 문 돌면서 append에 넣었다
{
self.ResultArray.append(newAddressResult)
}
self.tableView.reloadData() //갱신
} else {
print("Error")
}
}
}
}
| mit | 62520cf98387dffabf639f21f438cf55 | 26.39267 | 157 | 0.619002 | 3.785094 | false | false | false | false |
alblue/swift | stdlib/public/core/Unicode.swift | 2 | 35071 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Conversions between different Unicode encodings. Note that UTF-16 and
// UTF-32 decoding are *not* currently resilient to erroneous data.
/// The result of one Unicode decoding step.
///
/// Each `UnicodeDecodingResult` instance can represent a Unicode scalar value,
/// an indication that no more Unicode scalars are available, or an indication
/// of a decoding error.
@_frozen
public enum UnicodeDecodingResult : Equatable {
/// A decoded Unicode scalar value.
case scalarValue(Unicode.Scalar)
/// An indication that no more Unicode scalars are available in the input.
case emptyInput
/// An indication of a decoding error.
case error
@inlinable // FIXME(sil-serialize-all)
public static func == (
lhs: UnicodeDecodingResult,
rhs: UnicodeDecodingResult
) -> Bool {
switch (lhs, rhs) {
case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)):
return lhsScalar == rhsScalar
case (.emptyInput, .emptyInput):
return true
case (.error, .error):
return true
default:
return false
}
}
}
/// A Unicode encoding form that translates between Unicode scalar values and
/// form-specific code units.
///
/// The `UnicodeCodec` protocol declares methods that decode code unit
/// sequences into Unicode scalar values and encode Unicode scalar values
/// into code unit sequences. The standard library implements codecs for the
/// UTF-8, UTF-16, and UTF-32 encoding schemes as the `UTF8`, `UTF16`, and
/// `UTF32` types, respectively. Use the `Unicode.Scalar` type to work with
/// decoded Unicode scalar values.
public protocol UnicodeCodec : Unicode.Encoding {
/// Creates an instance of the codec.
init()
/// Starts or continues decoding a code unit sequence into Unicode scalar
/// values.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances:
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code uses the `UTF8` codec to encode a
/// fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
)
/// Searches for the first occurrence of a `CodeUnit` that is equal to 0.
///
/// Is an equivalent of `strlen` for C-strings.
///
/// - Complexity: O(*n*)
static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int
}
/// A codec for translating between Unicode scalar values and UTF-8 code
/// units.
extension Unicode.UTF8 : UnicodeCodec {
/// Creates an instance of the UTF-8 codec.
@inlinable // FIXME(sil-serialize-all)
public init() { self = ._swift3Buffer(ForwardParser()) }
/// Starts or continues decoding a UTF-8 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard case ._swift3Buffer(var parser) = self else {
Builtin.unreachable()
}
defer { self = ._swift3Buffer(parser) }
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF8.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Attempts to decode a single UTF-8 code unit sequence starting at the LSB
/// of `buffer`.
///
/// - Returns:
/// - result: The decoded code point if the code unit sequence is
/// well-formed; `nil` otherwise.
/// - length: The length of the code unit sequence in bytes if it is
/// well-formed; otherwise the *maximal subpart of the ill-formed
/// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading
/// code units that were valid or 1 in case none were valid. Unicode
/// recommends to skip these bytes and replace them by a single
/// replacement character (U+FFFD).
///
/// - Requires: There is at least one used byte in `buffer`, and the unused
/// space in `buffer` is filled with some value not matching the UTF-8
/// continuation byte form (`0b10xxxxxx`).
@inlinable // FIXME(sil-serialize-all)
public // @testable
static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) {
// Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ].
if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ ... ... ... CU0 ].
let value = buffer & 0xff
return (value, 1)
}
var p = ForwardParser()
p._buffer._storage = buffer
p._buffer._bitCount = 32
var i = EmptyCollection<UInt8>().makeIterator()
switch p.parseScalar(from: &i) {
case .valid(let s):
return (
result: UTF8.decode(s).value,
length: UInt8(truncatingIfNeeded: s.count))
case .error(let l):
return (result: nil, length: UInt8(truncatingIfNeeded: l))
case .emptyInput: Builtin.unreachable()
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code encodes a fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var s = encode(input)!._biasedBits
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// UTF-8 continuation byte.
///
/// Continuation bytes take the form `0b10xxxxxx`. For example, a lowercase
/// "e" with an acute accent above it (`"é"`) uses 2 bytes for its UTF-8
/// representation: `0b11000011` (195) and `0b10101001` (169). The second
/// byte is a continuation byte.
///
/// let eAcute = "é"
/// for codeUnit in eAcute.utf8 {
/// print(codeUnit, UTF8.isContinuation(codeUnit))
/// }
/// // Prints "195 false"
/// // Prints "169 true"
///
/// - Parameter byte: A UTF-8 code unit.
/// - Returns: `true` if `byte` is a continuation byte; otherwise, `false`.
@inlinable // FIXME(sil-serialize-all)
public static func isContinuation(_ byte: CodeUnit) -> Bool {
return byte & 0b11_00__0000 == 0b10_00__0000
}
@inlinable // FIXME(sil-serialize-all)
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CodeUnit>
) -> Int {
return Int(_swift_stdlib_strlen_unsigned(input))
}
// Support parsing C strings as-if they are UTF8 strings.
@inlinable // FIXME(sil-serialize-all)
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CChar>
) -> Int {
return Int(_swift_stdlib_strlen(input))
}
}
/// A codec for translating between Unicode scalar values and UTF-16 code
/// units.
extension Unicode.UTF16 : UnicodeCodec {
/// Creates an instance of the UTF-16 codec.
@inlinable // FIXME(sil-serialize-all)
public init() { self = ._swift3Buffer(ForwardParser()) }
/// Starts or continues decoding a UTF-16 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf16))
/// // Prints "[10024, 85, 110, 105, 99, 111, 100, 101, 10024]"
///
/// var codeUnitIterator = str.utf16.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf16Decoder = UTF16()
/// Decode: while true {
/// switch utf16Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@inlinable // FIXME(sil-serialize-all)
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard case ._swift3Buffer(var parser) = self else {
Builtin.unreachable()
}
defer { self = ._swift3Buffer(parser) }
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF16.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Try to decode one Unicode scalar, and return the actual number of code
/// units it spanned in the input. This function may consume more code
/// units than required for this scalar.
@inlinable // FIXME(sil-serialize-all)
internal mutating func _decodeOne<I : IteratorProtocol>(
_ input: inout I
) -> (UnicodeDecodingResult, Int) where I.Element == CodeUnit {
let result = decode(&input)
switch result {
case .scalarValue(let us):
return (result, UTF16.width(us))
case .emptyInput:
return (result, 0)
case .error:
return (result, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires two code units for its UTF-16
/// representation. The following code encodes a fermata in UTF-16:
///
/// var codeUnits: [UTF16.CodeUnit] = []
/// UTF16.encode("𝄐", into: { codeUnits.append($0) })
/// print(codeUnits)
/// // Prints "[55348, 56592]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@inlinable // FIXME(sil-serialize-all)
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var s = encode(input)!._storage
processCodeUnit(UInt16(truncatingIfNeeded: s))
s &>>= 16
if _fastPath(s == 0) { return }
processCodeUnit(UInt16(truncatingIfNeeded: s))
}
}
/// A codec for translating between Unicode scalar values and UTF-32 code
/// units.
extension Unicode.UTF32 : UnicodeCodec {
/// Creates an instance of the UTF-32 codec.
@inlinable // FIXME(sil-serialize-all)
public init() { self = ._swift3Codec }
/// Starts or continues decoding a UTF-32 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string
/// into an array of `Unicode.Scalar` instances. This is a demonstration
/// only---if you need the Unicode scalar representation of a string, use
/// its `unicodeScalars` view.
///
/// // UTF-32 representation of "✨Unicode✨"
/// let codeUnits: [UTF32.CodeUnit] =
/// [10024, 85, 110, 105, 99, 111, 100, 101, 10024]
///
/// var codeUnitIterator = codeUnits.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf32Decoder = UTF32()
/// Decode: while true {
/// switch utf32Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@inlinable // FIXME(sil-serialize-all)
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
return UTF32._decode(&input)
}
@inlinable // FIXME(sil-serialize-all)
internal static func _decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
var parser = ForwardParser()
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF32.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Encodes a Unicode scalar as a UTF-32 code unit by calling the given
/// closure.
///
/// For example, like every Unicode scalar, the musical fermata symbol ("𝄐")
/// can be represented in UTF-32 as a single code unit. The following code
/// encodes a fermata in UTF-32:
///
/// var codeUnit: UTF32.CodeUnit = 0
/// UTF32.encode("𝄐", into: { codeUnit = $0 })
/// print(codeUnit)
/// // Prints "119056"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@inlinable // FIXME(sil-serialize-all)
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
processCodeUnit(UInt32(input))
}
}
/// Translates the given input from one Unicode encoding to another by calling
/// the given closure.
///
/// The following example transcodes the UTF-8 representation of the string
/// `"Fermata 𝄐"` into UTF-32.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// var codeUnits: [UTF32.CodeUnit] = []
/// let sink = { codeUnits.append($0) }
/// transcode(bytes.makeIterator(), from: UTF8.self, to: UTF32.self,
/// stoppingOnError: false, into: sink)
/// print(codeUnits)
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 119056]"
///
/// The `sink` closure is called with each resulting UTF-32 code unit as the
/// function iterates over its input.
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `inputEncoding`. If `stopOnError` is `false`, the entire iterator will
/// be exhausted. Otherwise, iteration will stop if an encoding error is
/// detected.
/// - inputEncoding: The Unicode encoding of `input`.
/// - outputEncoding: The destination Unicode encoding.
/// - stopOnError: Pass `true` to stop translation when an encoding error is
/// detected in `input`. Otherwise, a Unicode replacement character
/// (`"\u{FFFD}"`) is inserted for each detected error.
/// - processCodeUnit: A closure that processes one `outputEncoding` code
/// unit at a time.
/// - Returns: `true` if the translation detected encoding errors in `input`;
/// otherwise, `false`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func transcode<
Input : IteratorProtocol,
InputEncoding : Unicode.Encoding,
OutputEncoding : Unicode.Encoding
>(
_ input: Input,
from inputEncoding: InputEncoding.Type,
to outputEncoding: OutputEncoding.Type,
stoppingOnError stopOnError: Bool,
into processCodeUnit: (OutputEncoding.CodeUnit) -> Void
) -> Bool
where InputEncoding.CodeUnit == Input.Element {
var input = input
// NB. It is not possible to optimize this routine to a memcpy if
// InputEncoding == OutputEncoding. The reason is that memcpy will not
// substitute U+FFFD replacement characters for ill-formed sequences.
var p = InputEncoding.ForwardParser()
var hadError = false
loop:
while true {
switch p.parseScalar(from: &input) {
case .valid(let s):
let t = OutputEncoding.transcode(s, from: inputEncoding)
guard _fastPath(t != nil), let s = t else { break }
s.forEach(processCodeUnit)
continue loop
case .emptyInput:
return hadError
case .error:
if _slowPath(stopOnError) { return true }
hadError = true
}
OutputEncoding.encodedReplacementCharacter.forEach(processCodeUnit)
}
}
/// Instances of conforming types are used in internal `String`
/// representation.
public // @testable
protocol _StringElement {
static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit
static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self
}
extension UTF16.CodeUnit : _StringElement {
@inlinable // FIXME(sil-serialize-all)
public // @testable
static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit {
return x
}
@inlinable // FIXME(sil-serialize-all)
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF16.CodeUnit {
return utf16
}
}
extension UTF8.CodeUnit : _StringElement {
@inlinable // FIXME(sil-serialize-all)
public // @testable
static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit {
_sanityCheck(x <= 0x7f, "should only be doing this with ASCII")
return UTF16.CodeUnit(truncatingIfNeeded: x)
}
@inlinable // FIXME(sil-serialize-all)
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF8.CodeUnit {
_sanityCheck(utf16 <= 0x7f, "should only be doing this with ASCII")
return UTF8.CodeUnit(truncatingIfNeeded: utf16)
}
}
extension UTF16 {
/// Returns the number of code units required to encode the given Unicode
/// scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let anA: Unicode.Scalar = "A"
/// print(anA.value)
/// // Prints "65"
/// print(UTF16.width(anA))
/// // Prints "1"
///
/// let anApple: Unicode.Scalar = "🍎"
/// print(anApple.value)
/// // Prints "127822"
/// print(UTF16.width(anApple))
/// // Prints "2"
///
/// - Parameter x: A Unicode scalar value.
/// - Returns: The width of `x` when encoded in UTF-16, either `1` or `2`.
@inlinable // FIXME(sil-serialize-all)
public static func width(_ x: Unicode.Scalar) -> Int {
return x.value <= 0xFFFF ? 1 : 2
}
/// Returns the high-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: Unicode.Scalar = "🍎"
/// print(UTF16.leadSurrogate(apple)
/// // Prints "55356"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The leading surrogate code unit of `x` when encoded in UTF-16.
@inlinable // FIXME(sil-serialize-all)
public static func leadSurrogate(_ x: Unicode.Scalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return 0xD800 + UTF16.CodeUnit(truncatingIfNeeded:
(x.value - 0x1_0000) &>> (10 as UInt32))
}
/// Returns the low-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: Unicode.Scalar = "🍎"
/// print(UTF16.trailSurrogate(apple)
/// // Prints "57166"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The trailing surrogate code unit of `x` when encoded in UTF-16.
@inlinable // FIXME(sil-serialize-all)
public static func trailSurrogate(_ x: Unicode.Scalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return 0xDC00 + UTF16.CodeUnit(truncatingIfNeeded:
(x.value - 0x1_0000) & (((1 as UInt32) &<< 10) - 1))
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// high-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a lead surrogate. The `apple` string contains a single
/// emoji character made up of a surrogate pair when encoded in UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isLeadSurrogate(unit))
/// }
/// // Prints "true"
/// // Prints "false"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// low-surrogate code unit follows `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a high-surrogate code unit; otherwise,
/// `false`.
@inlinable // FIXME(sil-serialize-all)
public static func isLeadSurrogate(_ x: CodeUnit) -> Bool {
return (x & 0xFC00) == 0xD800
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// low-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a trailing surrogate. The `apple` string contains a
/// single emoji character made up of a surrogate pair when encoded in
/// UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isTrailSurrogate(unit))
/// }
/// // Prints "false"
/// // Prints "true"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// high-surrogate code unit precedes `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a low-surrogate code unit; otherwise,
/// `false`.
@inlinable // FIXME(sil-serialize-all)
public static func isTrailSurrogate(_ x: CodeUnit) -> Bool {
return (x & 0xFC00) == 0xDC00
}
@inlinable // FIXME(sil-serialize-all)
public // @testable
static func _copy<T : _StringElement, U : _StringElement>(
source: UnsafeMutablePointer<T>,
destination: UnsafeMutablePointer<U>,
count: Int
) {
if MemoryLayout<T>.stride == MemoryLayout<U>.stride {
_memcpy(
dest: UnsafeMutablePointer(destination),
src: UnsafeMutablePointer(source),
size: UInt(count) * UInt(MemoryLayout<U>.stride))
}
else {
for i in 0..<count {
let u16 = T._toUTF16CodeUnit((source + i).pointee)
(destination + i).pointee = U._fromUTF16CodeUnit(u16)
}
}
}
/// Returns the number of UTF-16 code units required for the given code unit
/// sequence when transcoded to UTF-16, and a Boolean value indicating
/// whether the sequence was found to contain only ASCII characters.
///
/// The following example finds the length of the UTF-16 encoding of the
/// string `"Fermata 𝄐"`, starting with its UTF-8 representation.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// let result = transcodedLength(of: bytes.makeIterator(),
/// decodedAs: UTF8.self,
/// repairingIllFormedSequences: false)
/// print(result)
/// // Prints "Optional((10, false))"
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `sourceEncoding`. If `repairingIllFormedSequences` is `true`, the
/// entire iterator will be exhausted. Otherwise, iteration will stop if
/// an ill-formed sequence is detected.
/// - sourceEncoding: The Unicode encoding of `input`.
/// - repairingIllFormedSequences: Pass `true` to measure the length of
/// `input` even when `input` contains ill-formed sequences. Each
/// ill-formed sequence is replaced with a Unicode replacement character
/// (`"\u{FFFD}"`) and is measured as such. Pass `false` to immediately
/// stop measuring `input` when an ill-formed sequence is encountered.
/// - Returns: A tuple containing the number of UTF-16 code units required to
/// encode `input` and a Boolean value that indicates whether the `input`
/// contained only ASCII characters. If `repairingIllFormedSequences` is
/// `false` and an ill-formed sequence is detected, this method returns
/// `nil`.
@inlinable // FIXME(sil-serialize-all)
public static func transcodedLength<
Input : IteratorProtocol,
Encoding : Unicode.Encoding
>(
of input: Input,
decodedAs sourceEncoding: Encoding.Type,
repairingIllFormedSequences: Bool
) -> (count: Int, isASCII: Bool)?
where Encoding.CodeUnit == Input.Element {
var utf16Count = 0
var i = input
var d = Encoding.ForwardParser()
// Fast path for ASCII in a UTF8 buffer
if sourceEncoding == Unicode.UTF8.self {
var peek: Encoding.CodeUnit = 0
while let u = i.next() {
peek = u
guard _fastPath(peek < 0x80) else { break }
utf16Count = utf16Count + 1
}
if _fastPath(peek < 0x80) { return (utf16Count, true) }
var d1 = UTF8.ForwardParser()
d1._buffer.append(numericCast(peek))
d = _identityCast(d1, to: Encoding.ForwardParser.self)
}
var utf16BitUnion: CodeUnit = 0
while true {
let s = d.parseScalar(from: &i)
if _fastPath(s._valid != nil), let scalarContent = s._valid {
let utf16 = transcode(scalarContent, from: sourceEncoding)
._unsafelyUnwrappedUnchecked
utf16Count += utf16.count
for x in utf16 { utf16BitUnion |= x }
}
else if let _ = s._error {
guard _fastPath(repairingIllFormedSequences) else { return nil }
utf16Count += 1
utf16BitUnion |= UTF16._replacementCodeUnit
}
else {
return (utf16Count, utf16BitUnion < 0x80)
}
}
}
}
// Unchecked init to avoid precondition branches in hot code paths where we
// already know the value is a valid unicode scalar.
extension Unicode.Scalar {
/// Create an instance with numeric value `value`, bypassing the regular
/// precondition checks for code point validity.
@inlinable // FIXME(sil-serialize-all)
internal init(_unchecked value: UInt32) {
_sanityCheck(value < 0xD800 || value > 0xDFFF,
"high- and low-surrogate code points are not valid Unicode scalar values")
_sanityCheck(value <= 0x10FFFF, "value is outside of Unicode codespace")
self._value = value
}
}
extension UnicodeCodec {
@inlinable // FIXME(sil-serialize-all)
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CodeUnit>
) -> Int {
var length = 0
while input[length] != 0 {
length += 1
}
return length
}
}
@available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:into:)'")
public func transcode<Input, InputEncoding, OutputEncoding>(
_ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type,
_ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void,
stopOnError: Bool
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
/// A namespace for Unicode utilities.
@_frozen // FIXME(sil-serialize-all)
public enum Unicode {}
| apache-2.0 | 9fffee5ff80532cac05db5fcfafb49fd | 37.087051 | 87 | 0.641563 | 3.927513 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/InputBar/Emoji/Emojis.swift | 1 | 4342 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
import WireCommonComponents
typealias Emoji = String
final class EmojiDataSource: NSObject, UICollectionViewDataSource {
enum Update {
case insert(Int)
case reload(Int)
}
typealias CellProvider = (Emoji, IndexPath) -> UICollectionViewCell
let cellProvider: CellProvider
private var sections: [EmojiSection]
private let recentlyUsed: RecentlyUsedEmojiSection
init(provider: @escaping CellProvider) {
cellProvider = provider
self.recentlyUsed = RecentlyUsedEmojiPeristenceCoordinator.loadOrCreate()
sections = EmojiSectionType.all.compactMap(FileEmojiSection.init)
super.init()
insertRecentlyUsedSectionIfNeeded()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return sections.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self[section].emoji.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return cellProvider(self[indexPath], indexPath)
}
subscript (index: Int) -> EmojiSection {
return sections[index]
}
subscript (indexPath: IndexPath) -> Emoji {
return sections[indexPath.section][indexPath.item]
}
func sectionIndex(for type: EmojiSectionType) -> Int? {
return sections.map { $0.type }.firstIndex(of: type)
}
func register(used emoji: Emoji) -> Update? {
let shouldReload = recentlyUsed.register(emoji)
let shouldInsert = insertRecentlyUsedSectionIfNeeded()
defer { RecentlyUsedEmojiPeristenceCoordinator.store(recentlyUsed) }
switch (shouldInsert, shouldReload) {
case (true, _): return .insert(0)
case (false, true): return .reload(0)
default: return nil
}
}
@discardableResult func insertRecentlyUsedSectionIfNeeded() -> Bool {
guard let first = sections.first, !(first is RecentlyUsedEmojiSection), !recentlyUsed.emoji.isEmpty else { return false }
sections.insert(recentlyUsed, at: 0)
return true
}
}
enum EmojiSectionType: String {
case recent, people, nature, food, travel, activities, objects, symbols, flags
var icon: StyleKitIcon {
switch self {
case .recent: return .clock
case .people: return .emoji
case .nature: return .flower
case .food: return .cake
case .travel: return .car
case .activities: return .ball
case .objects: return .crown
case .symbols: return .asterisk
case .flags: return .flag
}
}
static var all: [EmojiSectionType] {
return [
EmojiSectionType.recent,
.people,
.nature,
.food,
.travel,
.activities,
.objects,
.symbols,
.flags
]
}
}
protocol EmojiSection {
var emoji: [Emoji] { get }
var type: EmojiSectionType { get }
}
extension EmojiSection {
subscript(index: Int) -> Emoji {
return emoji[index]
}
}
struct FileEmojiSection: EmojiSection {
init?(_ type: EmojiSectionType) {
let filename = "emoji_\(type.rawValue)"
guard let url = Bundle.main.url(forResource: filename, withExtension: "plist") else { return nil }
guard let emoji = NSArray(contentsOf: url) as? [Emoji] else { return nil }
self.emoji = emoji
self.type = type
}
let emoji: [Emoji]
let type: EmojiSectionType
}
| gpl-3.0 | 1259bfd52b4a0e302bf8e989c5f4241c | 28.14094 | 129 | 0.659143 | 4.64385 | false | false | false | false |
Den-Ree/InstagramAPI | src/InstagramAPI/InstagramAPI/Instagram/InstagramClient.swift | 2 | 9782 | //
// Instagram.swift
// ConceptOffice
//
// Created by Denis on 26.02.16.
// Copyright © 2016 Den Ree. All rights reserved.
//
import UIKit
import SafariServices
import KeychainAccess
import Alamofire
import AlamofireObjectMapper
public enum Instagram {}
private let instagramManagerKeychainStore = "com.InstagramClient.keychainStore"
final class InstagramClient {
// MARK: - Properties
fileprivate lazy var keychainStore: Keychain = {
return Keychain(service: instagramManagerKeychainStore)
}()
fileprivate var networkManager: Alamofire.SessionManager = .default
// MARK: - Public
var isLogged: Bool {
return self.keychainStore["isLogged"] == "true"
}
var loggedUserId: String {
get {
return self.keychainStore["lastUserId"]!
}
set (newValue) {
self.keychainStore["lastUserId"] = newValue
}
}
public enum InstagramAuthUrlFragment {
case empty
case code(String)
case accessToken(String)
}
struct InstagramAuthorisationUrl {
var clientSideFlowUrl: URL? {
let parameters: [String : Any] = [Instagram.Keys.Auth.clientId: Instagram.Constants.appClientId,
Instagram.Keys.Auth.redirectUri: Instagram.Constants.appRedirectURL,
Instagram.Keys.Response.type: Instagram.Keys.Response.token,
Instagram.Keys.Response.scope: Instagram.LoginScope.allScopesValue]
return InstagramClient().encode(Instagram.Constants.baseUrl + "oauth/authorize/", parameters: parameters)
}
var serverSideFlowUrl: URL? {
let parameters: [String : Any] = [Instagram.Keys.Auth.clientId: Instagram.Constants.appClientId,
Instagram.Keys.Auth.redirectUri: Instagram.Constants.appRedirectURL,
Instagram.Keys.Response.type: Instagram.Keys.Response.code,
Instagram.Keys.Response.scope: Instagram.LoginScope.allScopesValue]
return InstagramClient().encode(Instagram.Constants.baseUrl + "oauth/authorize/", parameters: parameters)
}
}
func send<T: AnyInstagramResponse>(_ router: AnyInstagramNetworkRouter, completion: @escaping (T?, Error?) -> Void) {
do {
guard let accessToken = keychainStore[Instagram.Keys.Auth.accessToken + loggedUserId] else {
completion(nil, nil)
return
}
let request = try router.asURLRequest(withAccessToken: accessToken)
request.description(router: router)
networkManager.request(request).validate().responseObject(completionHandler: { (response: DataResponse<T>) in
self.checkAccessTokenExpiration(response)
response.description()
completion(response.result.value, response.result.error)
})
} catch {
completion(nil, error)
}
}
}
extension InstagramClient {
struct Notifications {
static let noLoggedInAccounts = "InstagramClientNoLoggedInAccountsNotification"
static let mediaWasChanged = "InstagramClientMediaDidChangedNotification"
static let accessTokenExpired = "InstagramClientMediaAccessTokenExpired"
}
}
// MARL: Authorization
extension InstagramClient {
fileprivate func getAuthUrlFragment(_ Url: URL) -> InstagramAuthUrlFragment {
let appRedirectUrl: URL = URL(string: Instagram.Constants.appRedirectURL)!
// Check if our Url isRedirect
if appRedirectUrl.scheme == Url.scheme && appRedirectUrl.host == Url.host {
// Then check both flows
var components = Url.absoluteString.components(separatedBy: Instagram.Keys.Auth.accessToken + "=")
if components.count == 2 {
return .accessToken(components.last!)
}
components = Url.absoluteString.components(separatedBy: Instagram.Keys.Auth.code + "=")
if components.count == 2 {
return .code(components.last!)
}
}
return .empty
}
func receiveLoggedUser(_ Url: URL, completion: ((String?, Error?) -> Void)?) {
switch InstagramClient().getAuthUrlFragment(Url) {
case .empty: return
case .accessToken(let accessToken):
self.keychainStore[Instagram.Keys.Auth.accessToken] = accessToken
let router = InstagramUserRouter.getUser(.owner)
self.send(router, completion: { [weak self] (response: InstagramModelResponse<InstagramUser>?, error: Error?) in
if error == nil && response?.data != nil && response?.data.id != nil {
let currentAccessToken = self?.keychainStore[Instagram.Keys.Auth.accessToken]
self?.keychainStore[Instagram.Keys.Auth.accessToken + (response?.data.id)!] = currentAccessToken
do {
try self?.keychainStore.remove(Instagram.Keys.Auth.accessToken)
} catch {
print(error.localizedDescription)
}
self?.cleanCookies()
self?.keychainStore["isLogged"] = "true"
self?.loggedUserId = (response?.data.id)!
completion?(self?.loggedUserId, nil)
} else {
completion?(nil, nil)
}
})
break
case .code(let code):
let parameters = [Instagram.Keys.Auth.clientId: Instagram.Constants.appClientId,
Instagram.Keys.Auth.clientSecret: Instagram.Constants.appClientSecret,
Instagram.Keys.Auth.grantType: Instagram.Constants.grantType,
Instagram.Keys.Auth.redirectUri: Instagram.Constants.appRedirectURL,
Instagram.Keys.Auth.code: code]
let url = URL(string: Instagram.Constants.baseUrl + "oauth/access_token/")
var request = URLRequest.init(url: url!)
request.httpMethod = HTTPMethod.post.rawValue
let stringParams = parameters.parametersString()
let dataParams = stringParams.data(using: String.Encoding.utf8, allowLossyConversion: true)
let paramsLength = String(format: "%d", dataParams!.count)
request.setValue(paramsLength, forHTTPHeaderField: "Content-Length")
request.httpBody = dataParams
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
networkManager.request(request).response(completionHandler: {(response: DefaultDataResponse?) in
if let response = response {
do {
let json = try JSONSerialization.jsonObject(with: response.data!, options: .mutableContainers) as! Dictionary<String, Any>
if let accessToken = json[Instagram.Keys.Auth.accessToken] as? String {
let accessTokenUrl = Instagram.Constants.appRedirectURL + "/" + Instagram.Keys.Auth.accessToken + "=" + accessToken
self.receiveLoggedUser(URL(string: accessTokenUrl)!, completion: nil)
}
completion?(self.loggedUserId, nil)
} catch {
completion?(nil, nil)
}
}
})
break
}
}
func checkAccessTokenExpiration<T: AnyInstagramResponse>(_ response: DataResponse<T>) {
if response.result.value?.meta.errorType.rawValue == "OAuthAccessTokenError"{
print(Notifications.accessTokenExpired)
self.keychainStore[Instagram.Keys.Auth.accessToken + loggedUserId] = nil
self.endLogin()
}
}
func endLogin() {
self.loggedUserId = ""
self.keychainStore["isLogged"] = "false"
self.cleanCookies()
}
}
extension InstagramClient {
func encode(_ path: String?, parameters: [String: Any]) -> URL? {
guard let path = path, let encodedPath = path.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let url = URL(string: encodedPath) else {
return nil
}
do {
let initialRequest = URLRequest(url: url)
let request = try URLEncoding(destination: .methodDependent).encode(initialRequest, with: parameters)
return request.url
} catch {
print("\((error as NSError).localizedDescription)")
return nil
}
}
func cleanCookies() {
keychainStore[Instagram.Keys.Auth.accessToken] = nil
let storage = HTTPCookieStorage.shared
if let cookies = storage.cookies {
for (_, cookie) in cookies.enumerated() {
storage.deleteCookie(cookie)
}
}
}
}
extension URLRequest {
// MARK: Request description
func description(router: AnyInstagramNetworkRouter) {
router.describe()
if self.url != nil {
print("URL: \(String(describing: self.url!.absoluteString))")
} else {
print("URL: nil")
}
if self.httpBody != nil {
guard let json = try? JSONSerialization.jsonObject(with: self.httpBody!, options: .allowFragments) as! [String:Any] else {
return
}
print("HTTP Body: \(json)")
} else {
print("HTTP Body: nil")
}
}
}
extension DataResponse {
func description() {
print("\n")
print("Instagram Network Responce Description...")
if self.result.error == nil {
print("Error: nil")
} else {
print("Error: \(String(describing: self.result.error?.localizedDescription))")
}
if self.result.isSuccess {
print("Is success: true")
} else {
print("Is success: false")
}
if self.result.value == nil {
print("Result: nil")
} else {
print("Result: \(String(describing: self.result.value))")
}
print("\n")
}
}
extension Dictionary {
func parametersString() -> String {
var paramsString = [String]()
for (key, value) in self {
guard let stringValue = value as? String, let stringKey = key as? String else {
return ""
}
paramsString += [stringKey + "=" + "\(stringValue)"]
}
return (paramsString.isEmpty ? "" : paramsString.joined(separator: "&"))
}
}
| mit | 8de9fa3b7dc277b17701b2fcd1cd819f | 35.225926 | 167 | 0.650751 | 4.581265 | false | false | false | false |
formbound/SQL | Tests/SQLTests/SQLTests.swift | 2 | 1118 | import XCTest
@testable import SQL
struct User {
let username: String
let password: String
let isAdmin: Bool
}
extension User: ModelProtocol {
typealias PrimaryKey = Int
enum Field: String, ModelField {
case username
case password
case id
case isAdmin
static let tableName: String = "users"
static let primaryKey: Field = .id
}
func serialize() -> [Field : ValueConvertible?] {
return [
.username: username,
.password: password,
.isAdmin: isAdmin
]
}
init<Row: RowProtocol>(row: TableRow<User, Row>) throws {
username = try row.value(.username)
password = try row.value(.password)
isAdmin = try row.value(.isAdmin)
}
}
public class SQLTests: XCTestCase {
//TODO: Add tests
func testSelectQuery() {
User.select(where: User.Field.id == 1)
}
}
extension SQLTests {
public static var allTests: [(String, (SQLTests) -> () throws -> Void)] {
return [
("testSelectQuery", testSelectQuery),
]
}
}
| mit | aec990f728adbee57ccd635e2810c10e | 20.5 | 77 | 0.581395 | 4.316602 | false | true | false | false |
watson-developer-cloud/ios-sdk | Sources/AssistantV2/Models/MessageOutput.swift | 1 | 2315 | /**
* (C) Copyright IBM Corp. 2018, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import IBMSwiftSDKCore
/**
Assistant output to be rendered or processed by the client.
*/
public struct MessageOutput: Codable, Equatable {
/**
Output intended for any channel. It is the responsibility of the client application to implement the supported
response types.
*/
public var generic: [RuntimeResponseGeneric]?
/**
An array of intents recognized in the user input, sorted in descending order of confidence.
*/
public var intents: [RuntimeIntent]?
/**
An array of entities identified in the user input.
*/
public var entities: [RuntimeEntity]?
/**
An array of objects describing any actions requested by the dialog node.
*/
public var actions: [DialogNodeAction]?
/**
Additional detailed information about a message response and how it was generated.
*/
public var debug: MessageOutputDebug?
/**
An object containing any custom properties included in the response. This object includes any arbitrary properties
defined in the dialog JSON editor as part of the dialog node output.
*/
public var userDefined: [String: JSON]?
/**
Properties describing any spelling corrections in the user input that was received.
*/
public var spelling: MessageOutputSpelling?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case generic = "generic"
case intents = "intents"
case entities = "entities"
case actions = "actions"
case debug = "debug"
case userDefined = "user_defined"
case spelling = "spelling"
}
}
| apache-2.0 | 58bbb7d62782632d569924f5889d71aa | 30.712329 | 119 | 0.692873 | 4.763374 | false | false | false | false |
aestusLabs/ASChatApp | ChooseDayOfWeekWidget.swift | 1 | 10038 | //
// ChooseDayOfWeekWidget.swift
// ChatAppOrigionalFiles
//
// Created by Ian Kohlert on 2017-07-28.
// Copyright © 2017 aestusLabs. All rights reserved.
//
import Foundation
import UIKit
class ChooseDayOfWeekButton: UIButton {
var buttonTag: WidgetTagNames = .error
let gradient = CAGradientLayer()
override init (frame: CGRect) {
super.init(frame: frame)
self.layer.shadowColor = UIColor.lightGray.cgColor
self.layer.shadowOpacity = 0.25
self.layer.shadowOffset = CGSize(width: 2, height: 4)
self.layer.shadowRadius = 4
// gradient.frame = self.bounds
//
// let red = UIColor(red: 1.0, green: 0.28627451, blue: 0.568627451, alpha: 1.0)
// let orange = UIColor(red: 1.0, green: 0.462745098, blue: 0.462745098, alpha: 1.0)
// gradient.colors = [red.cgColor, orange.cgColor]
//
// gradient.startPoint = CGPoint.zero
// gradient.endPoint = CGPoint(x: 1, y: 1)
// self.layer.insertSublayer(gradient, at: 0)
self.layer.borderColor = appColours.getMainAppColour().cgColor
self.layer.borderWidth = 1
self.backgroundColor = UIColor.white
self.layer.cornerRadius = 20
self.setTitleColor(UIColor.black, for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightBold)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
}
func createChooseDayOfWeekButton(text: String, tag: WidgetTagNames) -> ChooseDayOfWeekButton{
let button = ChooseDayOfWeekButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
button.setTitle(text, for: .normal)
button.buttonTag = tag
return button
}
//enum daysOfWeek {
// case mon, tue, wed, thu, fri, sat, sun
//}
//
//class DailyReminderCard: UIView {
//
// var helperBackground = UIView()
// var helperText = UILabel()
// var mondayCircle = Circle()
// var tuesdayCircle = Circle()
// var wednesdayCircle = Circle()
// var thursdayCircle = Circle()
// var fridayCircle = Circle()
// var saturdayCircle = Circle()
// var sundayCircle = Circle()
// var changeTimeButton = UIButton()
// var m = UILabel()
// var t = UILabel()
// var w = UILabel()
// var th = UILabel()
// var f = UILabel()
// var s = UILabel()
// var su = UILabel()
//
// var unselectedCircledColour = UIColor(red: 0.925490196, green: 0.925490196, blue: 0.925490196, alpha: 1.0)
// var circleActiveColour = UIColor.black
// var textActiveColour = UIColor.white
//
// var arrayOfCircles: [Circle] = []
// var arrayOfLetters: [UILabel] = []
//
// override init(frame: CGRect) {
// super.init(frame: frame)
// self.backgroundColor = appColours.getHelperSuggestionColour()
// self.layer.cornerRadius = 3
// self.layer.shadowColor = UIColor.black.cgColor
// self.layer.shadowOpacity = 0.25
// self.layer.shadowOffset = CGSize(width: 2, height: 4)
// self.layer.shadowRadius = 4
//
// helperBackground = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 35))
// helperBackground.backgroundColor = appColours.getBehindHelperTextHomeBackground()
// self.addSubview(helperBackground)
//
//// let helperCircle = HelperCircle(frame: CGRect(x: 15, y: 5, width: 20, height: 20))
//// self.addSubview(helperCircle)
//
// helperText = UILabel(frame: CGRect(x: 50, y: 10, width: self.frame.width - 60, height: 30))
// helperText.font = UIFont.monospacedDigitSystemFont(ofSize: 18, weight: UIFontWeightMedium)
// self.addSubview(helperText)
//
//// helperCircle.center.y = helperBackground.center.y
//// helperText.center.y = helperBackground.center.y
//
// arrayOfCircles = [mondayCircle, tuesdayCircle, wednesdayCircle, thursdayCircle, fridayCircle, saturdayCircle, sundayCircle]
// arrayOfLetters = [m, t, w, th, f, s, su]
// let arrayOfText = ["m", "t", "w", "t", "f", "s", "s"]
//
// var count = 0
//
// let cardWidth = self.frame.width
// let incrementNumber = cardWidth / 8
// var amountToIncrement = incrementNumber
// for _ in arrayOfCircles {
// arrayOfLetters[count] = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 15))
// arrayOfLetters[count].text = arrayOfText[count]
// arrayOfLetters[count].textAlignment = .center
// arrayOfLetters[count].textColor = UIColor.darkGray
//
// arrayOfCircles[count] = Circle(frame: CGRect(x: 0, y: helperBackground.frame.maxY + 16, width: 30, height: 30))
//
// arrayOfCircles[count].backgroundColor = unselectedCircledColour
// arrayOfCircles[count].center.x = amountToIncrement
// self.addSubview(arrayOfCircles[count])
// arrayOfLetters[count].center = arrayOfCircles[count].center
// self.addSubview(arrayOfLetters[count])
// amountToIncrement += incrementNumber
// count += 1
// }
//
//// let buttonWidth = getWidthOfButton(text: "change time")
//// changeTimeButton = UIButton(frame: CGRect(x: 0, y: arrayOfCircles[0].frame.maxY + 18, width: buttonWidth, height: 40))
//// changeTimeButton.set
//// changeTimeButton.center.x = helperBackground.center.x
////
//// self.addSubview(changeTimeButton)
//
//
// }
//
// required init(coder aDecoder: NSCoder) {
// fatalError("This class does not support NSCoding")
// }
//
// func changeHelperText(text: String) {
// helperText.text = text
// }
//
// func changeCircleToActive(day: daysOfWeek) {
// if day == .mon {
// arrayOfCircles[0].changeColour(colour: circleActiveColour)
// arrayOfLetters[0].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
// arrayOfLetters[0].textColor = textActiveColour
// } else if day == .tue {
// arrayOfCircles[1].changeColour(colour: circleActiveColour)
// arrayOfLetters[1].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
// arrayOfLetters[1].textColor = textActiveColour
// } else if day == .wed {
// arrayOfCircles[2].changeColour(colour: circleActiveColour)
// arrayOfLetters[2].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
// arrayOfLetters[2].textColor = textActiveColour
// } else if day == .thu {
// arrayOfCircles[3].changeColour(colour: circleActiveColour)
// arrayOfLetters[3].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
// arrayOfLetters[3].textColor = textActiveColour
// } else if day == .fri {
// arrayOfCircles[4].changeColour(colour: circleActiveColour)
// arrayOfLetters[4].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
// arrayOfLetters[4].textColor = textActiveColour
// } else if day == .sat {
// arrayOfCircles[5].changeColour(colour: circleActiveColour)
// arrayOfLetters[5].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
// arrayOfLetters[5].textColor = textActiveColour
// } else if day == .sun {
// arrayOfCircles[6].changeColour(colour: circleActiveColour)
// arrayOfLetters[6].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
// arrayOfLetters[6].textColor = textActiveColour
// }
// }
// func changeCircleToInactive(day: daysOfWeek) {
// if day == .mon {
// arrayOfCircles[0].changeColour(colour: unselectedCircledColour)
// arrayOfLetters[0].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightRegular)
// arrayOfLetters[0].textColor = UIColor.darkGray
// } else if day == .tue {
// arrayOfCircles[1].changeColour(colour: unselectedCircledColour)
// arrayOfLetters[1].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightRegular)
// arrayOfLetters[1].textColor = UIColor.darkGray
// } else if day == .wed {
// arrayOfCircles[2].changeColour(colour: unselectedCircledColour)
// arrayOfLetters[2].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightRegular)
// arrayOfLetters[2].textColor = UIColor.darkGray
// } else if day == .thu {
// arrayOfCircles[3].changeColour(colour: unselectedCircledColour)
// arrayOfLetters[3].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightRegular)
// arrayOfLetters[3].textColor = UIColor.darkGray
// } else if day == .fri {
// arrayOfCircles[4].changeColour(colour: unselectedCircledColour)
// arrayOfLetters[4].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightRegular)
// arrayOfLetters[4].textColor = UIColor.darkGray
// } else if day == .sat {
// arrayOfCircles[5].changeColour(colour: unselectedCircledColour)
// arrayOfLetters[5].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightRegular)
// arrayOfLetters[5].textColor = UIColor.darkGray
// } else if day == .sun {
// arrayOfCircles[6].changeColour(colour: unselectedCircledColour)
// arrayOfLetters[6].font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightRegular)
// arrayOfLetters[6].textColor = UIColor.darkGray
// }
// }
//}
//
//func createDailyReminderCard(screenWidth: CGFloat) -> DailyReminderCard {
// let view = DailyReminderCard(frame: CGRect(x: 20, y: 0, width: screenWidth - 40, height: 150))
// return view
//
//}
| mit | 430cf68ed868ada66e01f33089c6b038 | 43.411504 | 133 | 0.621202 | 3.906968 | false | false | false | false |
RedMadRobot/DAO | Example/RealmDAOTests/RealmDAOMessagesTests.swift | 1 | 2681 | //
// RealmDAOMessagesTests.swift
// DAO
//
// Created by Ivan Vavilov on 4/28/17.
// Copyright © 2017 RedMadRobot LLC. All rights reserved.
//
import XCTest
import DAO
@testable import DAO_Example
final class RealmDAOMessagesTests: XCTestCase {
private var dao: RealmDAO<Message, DBMessage>!
override func setUp() {
super.setUp()
dao = RealmDAO(RLMMessageTranslator())
}
override func tearDown() {
super.tearDown()
try! dao.erase()
dao = nil
}
func testPersistMessage() {
let message = Message(entityId: "abc", text: "text")
XCTAssertNoThrow(try dao.persist(message), "Persist is failed")
XCTAssertEqual(message, dao.read(message.entityId))
}
func testReadMessage() {
let message = Message(entityId: "def", text: "text 2")
XCTAssertNoThrow(try dao.persist(message), "Persist is failed")
XCTAssertEqual(message, dao.read("def"))
}
func testEraseMessage() {
let message = Message(entityId: "ghi", text: "text 2")
XCTAssertNoThrow(try dao.persist(message), "Persist or erase is failed")
XCTAssertNoThrow(try dao.erase("ghi"), "Persist or erase is failed")
XCTAssertNil(dao.read("ghi"))
}
func testPersistListOfMessages() {
XCTAssertEqual(dao.read().count, 0)
let message1 = Message(entityId: "1", text: "1")
let message2 = Message(entityId: "2", text: "2")
let message3 = Message(entityId: "3", text: "3")
XCTAssertNoThrow(try dao.persist([message1, message2, message3]), "Persist is failed")
let threeMessages = dao.read(orderedBy: "entryId", ascending: true)
XCTAssertEqual(threeMessages.count, 3)
XCTAssertEqual(threeMessages[0].entityId, "1")
XCTAssertEqual(threeMessages[1].entityId, "2")
XCTAssertEqual(threeMessages[2].entityId, "3")
let message55 = Message(entityId: "55", text: "55")
let message66 = Message(entityId: "66", text: "66")
XCTAssertNoThrow(try dao.persist([message1, message2, message3, message55, message66]), "Persist is failed")
let fiveMessages = dao.read(orderedBy: "entryId", ascending: true)
XCTAssertEqual(fiveMessages.count, 5)
XCTAssertEqual(fiveMessages[0].entityId, "1")
XCTAssertEqual(fiveMessages[1].entityId, "2")
XCTAssertEqual(fiveMessages[2].entityId, "3")
XCTAssertEqual(fiveMessages[3].entityId, "55")
XCTAssertEqual(fiveMessages[4].entityId, "66")
}
}
| mit | b5d6692234842fc6d71c01e8a7f4f751 | 31.289157 | 116 | 0.614552 | 4.161491 | false | true | false | false |
gstro/cryptopals-swift | Sources/Cryptopals/Utils.swift | 1 | 6834 | import Foundation
import Cryptor
import Files
import CryptoSwift
public struct Utils {
// MARK: - Private properties and functions.
/**
English language character frequencies, source:
http://www.macfreek.nl/memory/Letter_Distribution
*/
private static let charFreq: [Character: Int] = [
"a": 653,
"b": 126,
"c": 223,
"d": 328,
"e": 1026,
"f": 198,
"g": 162,
"h": 498,
"i": 567,
"j": 10,
"k": 56,
"l": 331,
"m": 203,
"n": 571,
"o": 616,
"p": 150,
"q": 8,
"r": 499,
"s": 532,
"t": 752,
"u": 228,
"v": 80,
"w": 170,
"x": 14,
"y": 143,
"z": 5,
" ": 1829
]
/**
Grades the given string, based on known character frequencies for the
English language, with larger values indicating higher likelihood for the
phrase to be valid words.
- Parameter str: The string to score.
- Returns: An integer representing the score. Larger numbers indicate
higher likelihood of valid words.
*/
private static func score(_ str: String) -> Int {
return str.lowercased()
.reduce(0) { $0 + (charFreq[$1] ?? 0) }
}
/**
Scores a given byte as an XOR key against the given bytes.
- Parameters:
- key: A byte to test as an XOR key against a byte array.
- bytes: A byte array used for testing the key.
- Returns: A named-value tuple of the provided key and its score.
*/
private static func testKey(_ key: UInt8, bytes: [UInt8]) -> (key: UInt8, score: Int) {
let xorBytes = bytes.xor(key)
let data: Data = CryptoUtils.data(from: xorBytes)
guard let decoded = String(data: data, encoding: .utf8)
else { return (key: key, score: 0) }
return (key: key, score: score(decoded))
}
// MARK: - Public properties and functions.
/**
Supplies the contents of a file as a string if the file can be read,
otherwise nil.
- Note: For compatibility with xcode and swiftpm,
store all resources in ~/Cryptopals/Resources. For
continuous integration, store files in project root/Resources,
and pass CI_BUILD flag to tester
- Parameter named: The filename to read.
- Returns: The file contents as a string or nil.
*/
public static func fileContents(named: String) -> String? {
#if CI_BUILD
return try? Folder
.current
.subfolder(named: "Resources")
.file(named: named)
.readAsString()
#else
return try? Folder
.home
.subfolder(named: "Cryptopals")
.subfolder(named: "Resources")
.file(named: named)
.readAsString()
#endif
}
/**
Cycles through the range of UInt8 values, testing each byte against the
given byte array, and supplies the best scoring key if one was found,
otherwise nil.
- Parameter bytes: The byte array to use for scoring possible keys.
- Returns: A named-value tuple of the highest scoring key and its score,
or nil if none was found.
*/
public static func solveSingleByteXor(_ bytes: [UInt8]) -> (key: UInt8, score: Int)? {
return [UInt8](UInt8.min...UInt8.max)
.map { testKey($0, bytes: bytes) }
.sorted { $0.score > $1.score }
.first
}
/**
Gives the score of a given key size for an array of bytes based on the
hamming distance after breaking the array into sized chunks. Lower scores
indicate higher likelihood of key size used.
- Parameters:
- keySize: The size of the key to use for scoring.
- bytes: The array of bytes to use for scoring.
- Returns: Score indicating possibility that provided key size is correct.
*/
public static func scoreKeySize(_ keySize: Int, bytes: [UInt8]) -> Int {
let chunkCount = bytes.count / keySize
return (0..<(chunkCount - 1)).reduce(0) { (acc, iter) in
let chunk = Array(bytes[(iter * keySize)..<((iter + 2) * keySize)])
let first = Array(chunk.prefix(upTo: keySize))
let last = Array(chunk.suffix(from: keySize))
return acc + first.hamming(last)
} / chunkCount / keySize
}
/**
Checks the given line for repeating chunks of bytes of the given size.
- Parameters:
- line: The line to check for repeating bytes
- sized: The chunk size to divide the line.
- Returns: If the provided line repeated bytes chunks of the given size
*/
public static func repeatsBytes(_ line: String, sized: Int) -> Bool {
var counts = [String: Int]()
return CryptoUtils
.byteArray(fromHex: line)
.chunks(sized)
.contains { counts.updateValue(1, forKey: $0.hexString()) != nil }
}
/**
CBC Mode crypto operations.
*/
public enum CbcOp {
case encrypt
case decrypt
fileprivate func run(_ block: [UInt8], prev: [UInt8], ecb: AES) -> ([UInt8], [UInt8])? {
switch self {
case .encrypt:
guard let cypherBlock: [UInt8] = try? ecb.encrypt(prev.xor(block))
else { return nil }
return (cypherBlock, cypherBlock)
case .decrypt:
guard let decrypted = try? ecb.decrypt(block)
else { return nil }
return (prev.xor(decrypted), block)
}
}
}
/**
Run a CBC Mode crypto operation.
- Parameters:
- bytes: The bytes on which to perform the operation.
- keyBytes: The bytes for the key used in the operation.
- iv: The initialization vector.
- op: The selected CBC operation to perform.
- Returns: The transformed bytes if successful, or nil if unsuccessful.
*/
public static func cbc(_ bytes: [UInt8], keyBytes: [UInt8], iv: [UInt8], op: CbcOp) -> [UInt8]? {
func go(_ acc: [[UInt8]], rem: [[UInt8]], previous: [UInt8], ecb: AES) -> [[UInt8]]? {
guard let block = rem.first
else { return acc }
guard let (next, prev) = op.run(block, prev: previous, ecb: ecb)
else { return nil }
return go(acc + [next], rem: Array(rem.dropFirst()), previous: prev, ecb: ecb)
}
guard let ecb = try? AES.init(key: keyBytes, blockMode: .ECB, padding: .noPadding)
else { return nil }
let padSize = keyBytes.count
let chunked = bytes.chunks(padSize)
return go([], rem: chunked, previous: iv, ecb: ecb)?.reduce([], +)
}
}
| mit | b24394a4a58a49b4b62b5d0c5123c498 | 31.855769 | 101 | 0.563945 | 4.087321 | false | false | false | false |
kshin/Kana | Tests/Formatters/SeasonFormatterTests.swift | 1 | 1098 | //
// SeasonFormatterTests.swift
// Kana
//
// Created by Ivan Lisovyi on 4/26/17.
// Copyright © 2017 Ivan Lisovyi. All rights reserved.
//
import XCTest
import Unbox
@testable import Kana
class SeasonFormatterTests: XCTestCase {
func testThatItFormatsSessionCorrectly() {
var expected: Season = .spring
var actual = SeasonFomatter().format(unboxedValue: 172)
XCTAssertEqual(expected, actual)
expected = .winter
actual = SeasonFomatter().format(unboxedValue: 171)
XCTAssertEqual(expected, actual)
expected = .summer
actual = SeasonFomatter().format(unboxedValue: 173)
XCTAssertEqual(expected, actual)
expected = .fall
actual = SeasonFomatter().format(unboxedValue: 174)
XCTAssertEqual(expected, actual)
}
func testThatItProvidesCorrectDefaultValue() {
let expected: Season = .winter
let actual = SeasonFomatter().format(unboxedValue: 175)
XCTAssertEqual(expected, actual)
}
}
| mit | 67d1a0b9100c8b0049c7767af7f660d5 | 24.511628 | 63 | 0.627165 | 4.609244 | false | true | false | false |
xwu/swift | test/refactoring/ConvertAsync/labeled_closure_params.swift | 5 | 4186 | // REQUIRES: concurrency
// RUN: %empty-directory(%t)
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MULTIPLE-LABELED-RESULTS %s
func mutlipleLabeledResults(completion: @escaping (_ first: String, _ second: String) -> Void) { }
// MULTIPLE-LABELED-RESULTS: {
// MULTIPLE-LABELED-RESULTS-NEXT: Task {
// MULTIPLE-LABELED-RESULTS-NEXT: let result = await mutlipleLabeledResults()
// MULTIPLE-LABELED-RESULTS-NEXT: completion(result.first, result.second)
// MULTIPLE-LABELED-RESULTS-NEXT: }
// MULTIPLE-LABELED-RESULTS-NEXT: }
// MULTIPLE-LABELED-RESULTS: func mutlipleLabeledResults() async -> (first: String, second: String) { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MIXED-LABELED-RESULTS %s
func mixedLabeledResult(completion: @escaping (_ first: String, String) -> Void) { }
// MIXED-LABELED-RESULTS: {
// MIXED-LABELED-RESULTS-NEXT: Task {
// MIXED-LABELED-RESULTS-NEXT: let result = await mixedLabeledResult()
// MIXED-LABELED-RESULTS-NEXT: completion(result.first, result.1)
// MIXED-LABELED-RESULTS-NEXT: }
// MIXED-LABELED-RESULTS-NEXT: }
// MIXED-LABELED-RESULTS: func mixedLabeledResult() async -> (first: String, String) { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=SINGLE-LABELED-RESULT %s
func singleLabeledResult(completion: @escaping (_ first: String) -> Void) { }
// SINGLE-LABELED-RESULT: {
// SINGLE-LABELED-RESULT-NEXT: Task {
// SINGLE-LABELED-RESULT-NEXT: let result = await singleLabeledResult()
// SINGLE-LABELED-RESULT-NEXT: completion(result)
// SINGLE-LABELED-RESULT-NEXT: }
// SINGLE-LABELED-RESULT-NEXT: }
// SINGLE-LABELED-RESULT: func singleLabeledResult() async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=SINGLE-LABELED-RESULT-WITH-ERROR %s
func singleLabeledResultWithError(completion: @escaping (_ first: String?, _ error: Error?) -> Void) { }
// SINGLE-LABELED-RESULT-WITH-ERROR: {
// SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: Task {
// SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: do {
// SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: let result = try await singleLabeledResultWithError()
// SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: completion(result, nil)
// SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: } catch {
// SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: completion(nil, error)
// SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: }
// SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: }
// SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: }
// SINGLE-LABELED-RESULT-WITH-ERROR: func singleLabeledResultWithError() async throws -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MULTIPLE-LABELED-RESULT-WITH-ERROR %s
func multipleLabeledResultWithError(completion: @escaping (_ first: String?, _ second: String?, _ error: Error?) -> Void) { }
// MULTIPLE-LABELED-RESULT-WITH-ERROR: {
// MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: Task {
// MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: do {
// MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: let result = try await multipleLabeledResultWithError()
// MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: completion(result.first, result.second, nil)
// MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: } catch {
// MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: completion(nil, nil, error)
// MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: }
// MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: }
// MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: }
// MULTIPLE-LABELED-RESULT-WITH-ERROR: func multipleLabeledResultWithError() async throws -> (first: String, second: String) { }
func testConvertCall() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=CONVERT-CALL %s
mutlipleLabeledResults() { (a, b) in
print(a)
print(b)
}
// CONVERT-CALL: let (a, b) = await mutlipleLabeledResults()
// CONVERT-CALL-NEXT: print(a)
// CONVERT-CALL-NEXT: print(b)
}
| apache-2.0 | 6c2aed90a0ceb10fb0031c6ec4b719b7 | 57.138889 | 168 | 0.733397 | 3.237432 | false | false | false | false |
sabbek/EasySwift | EasySwift/EasySwift/AppDelegate.swift | 1 | 5727 | //
// AppDelegate.swift
// EasySwift
//
// Created by Sabbe on 21/03/17.
// Copyright © 2017 sabbe.kev. All rights reserved.
//
// MIT License
//
// Copyright (c) 2017 sabbek
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import 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: "EasySwift")
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 | 0043a86799ac732faf66e80f560d6d95 | 48.362069 | 285 | 0.698393 | 5.458532 | false | false | false | false |
danielmartin/swift | test/Driver/Dependencies/fail-with-bad-deps.swift | 3 | 2557 | /// main ==> depends-on-main | bad ==> depends-on-bad
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/fail-with-bad-deps/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: Handled main.swift
// CHECK-FIRST: Handled bad.swift
// CHECK-FIRST: Handled depends-on-main.swift
// CHECK-FIRST: Handled depends-on-bad.swift
// Reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/fail-with-bad-deps/*.swiftdeps %t
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-NONE %s
// CHECK-NONE-NOT: Handled
// Reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/fail-with-bad-deps/*.swiftdeps %t
// RUN: touch -t 201401240006 %t/bad.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-BUILD-ALL %s
// CHECK-BUILD-ALL-NOT: warning
// CHECK-BUILD-ALL: Handled bad.swift
// CHECK-BUILD-ALL-DAG: Handled main.swift
// CHECK-BUILD-ALL-DAG: Handled depends-on-main.swift
// CHECK-BUILD-ALL-DAG: Handled depends-on-bad.swift
// Reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/fail-with-bad-deps/*.swiftdeps %t
// RUN: touch -t 201401240007 %t/bad.swift %t/main.swift
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies-bad.py -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-WITH-FAIL %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps
// CHECK-WITH-FAIL: Handled main.swift
// CHECK-WITH-FAIL-NOT: Handled depends
// CHECK-WITH-FAIL: Handled bad.swift
// CHECK-WITH-FAIL-NOT: Handled depends
// CHECK-RECORD-DAG: "./bad.swift": !private [
// CHECK-RECORD-DAG: "./main.swift": [
// CHECK-RECORD-DAG: "./depends-on-main.swift": !dirty [
// CHECK-RECORD-DAG: "./depends-on-bad.swift": [
| apache-2.0 | 79fd7670a31aa497a4750499580fbe34 | 52.270833 | 294 | 0.703168 | 2.935706 | false | false | false | false |
karen-fuentes/DSAReview | DSAWeekOne.playground/Contents.swift | 1 | 9909 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
// create a function that returns the amount of times a palindrome appears in a scentence ex "bob" : 2 , Mom: 3, "racecar": 1
func howManyPalindrome(with sentence: String) -> [String:Int] {
var palindromeDict = [String:Int]()
let words = sentence.components(separatedBy: " ")
words.forEach { (word) in
if isPalindrome(word: word) {
let counter = palindromeDict[word] ?? 0
palindromeDict[word] = counter + 1
}
}
return palindromeDict
}
// Below is the helper function that checks whether the word is an actual palindrome. While the current inex which starts off at 0 is less than half of the length of charactes in the word we will check if the character at the current index is equal to the last character and keep moving on both ends of the word itself until we reach the midpoint
func isPalindrome(word: String) -> Bool {
var currentIndex = 0
let characters = Array(word.lowercased().characters)
while currentIndex < characters.count/2 {
if characters[currentIndex] != characters[characters.count - currentIndex - 1 ] {
return false
}
currentIndex += 1
}
return true
}
//howManyPalindrome(with: "racecar racecar bob bob bob anna sushi")
/*
Clarifying Questions: Reverse A String
1) Can we use a higher ordered function?
2) Can I use .reverse()?
3) How do I handle whitespace and punctuation?
*/
/*
Identifying inputs and ouputs
1) input: String
output: String
2) input: String
output: Void (Print the Reversed String)
3) input: Void (By extending Swift String Struct)
output: Void
*/
func reverseAString(str: String) -> String {
var myStack: [Character] = [] // no class array is the Data Structure used for myStack
for character in str.characters {
myStack.append(character)
}
var reversedStr = ""
while !myStack.isEmpty {
reversedStr += String(myStack.popLast()!)
//reversedStr.append(myStack.popLast()!)
}
return reversedStr
}
func reverseAString2(str: String) -> String {
var myReversedStr: String = ""
for character in str.characters {
var temp = String(character) + myReversedStr
withUnsafePointer(to: &temp, { (addr) in
print(addr)
})
print(temp)
myReversedStr = temp
}
var temp = String(Character("F")) + myReversedStr
withUnsafePointer(to: &temp, { (addr) in
print(addr)
})
print(temp)
return myReversedStr
}
reverseAString2(str: "hello")
reverseAString(str: "hello")
/*
https://oj.leetcode.com/problems/two-sum/
#1 Two Sum
Level: medium
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
*/
func twoSum(of arr: [Int], target: Int) -> [Int] {
var hashMap = [Int: Int]()
var result = [Int]()
for index in 0..<arr.count{
let numberToFind = target - arr[index]
if let numberToFindIndex = hashMap[numberToFind] {
result.append(numberToFindIndex + 1)
result.append(index + 1)
return result
} else {
hashMap[arr[index]] = index
}
print(hashMap)
}
return result
}
//twoSum(of: [2,7,11,15], target: 26)
/*
https://oj.leetcode.com/problems/add-two-numbers/
#2 Add Two Numbers
Level: medium
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
*/
class ListNode {
var value: Int
var next: ListNode?
init () {
value = 0
next = nil
}
init (nodeValue: Int, nodeNext: ListNode?) {
value = nodeValue
next = nodeNext
}
}
func addList(listOne: ListNode?, listTwo: ListNode?) -> ListNode? {
var temp1 = listOne
var temp2 = listTwo
let dummy = ListNode()
var current = dummy
var sum = 0
while temp1 != nil || temp2 != nil {
sum /= 10
if let n = temp1 {
sum += n.value
temp1 = n.next
}
if let n = temp2 {
sum += n.value
temp2 = n.next
}
current.next = ListNode(nodeValue: sum%10, nodeNext: nil)
if let n = current.next{
current = n
}
}
if sum / 10 == 1 {
current.next = ListNode(nodeValue: 1, nodeNext: nil)
}
return dummy
}
/* https://leetcode.com/problems/intersection-of-two-arrays/#/description
1. ask clarifying questions
how do we handle negaitve numbers
how should we order the return array
do we need to handle array of types other than Int
2. Identify inputs and outputs
input: [Int], [Int]
output; [Int]
3. Talk through the solution
a. SET turn both arrays into sets, then retirned the intersection of both sets
b. NO SET - iterate through an input array and for each value check to see if the seocond array contians that value. If it does and the final array doesnt yet contain that value, appened it to the final array
4. code and explain your solution
*/
// func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
// let testSetOne = Set(nums1)
// let testSetTwo = Set(nums2)
// return Array(testSetOne.intersection(testSetTwo))
// }
// Long way
func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var nums = [Int]()
for num in nums1 {
if nums2.contains(num) {
nums.append(num)
}
}
return Array(Set((nums)))
}
/* https://leetcode.com/problems/keyboard-row/#/description
1. ask clarifying questions
2. Identify inputs and outputs
input: [String]
output: [Sting]
3. Talk through the solution
4. code and explain your solution
*/
func findWords(_ words: [String]) -> [String] {
let firstRow:Set<Character> = ["q","w", "e", "r","t","y","u","i","o","p"]
let secondRow:Set<Character> = ["a","s","d", "f","g","h","j","k","l"]
let thirdRow:Set<Character> = ["z","x","c","v","b","n","m"]
var resultArr = [String]()
for word in words {
for char in word.lowercased().characters {
switch char {
//case _ where firstRow.contains(char):
default:
break
}
}
}
return [""]
}
func findWords2(_ words: [String]) -> [String] {
let row1: Set<Character> = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]
let row2: Set<Character> = ["a", "s", "d", "f", "g", "h", "j", "k", "l"]
let row3: Set<Character> = ["z", "x", "c", "v", "b", "n", "m"]
var finalArr = [String]()
func allCharsIn(row: Set<Character>, with str: String) -> Bool {
for c in str.lowercased().characters {
if !row.contains(c) {
return false
}
}
return true
}
for word in words {
let firstLetter = word.lowercased()[word.startIndex]
var shouldAppend = true
switch firstLetter {
case _ where row1.contains(firstLetter):
shouldAppend = allCharsIn(row: row1, with: word)
case _ where row2.contains(firstLetter):
shouldAppend = allCharsIn(row: row2, with: word)
case _ where row3.contains(firstLetter):
shouldAppend = allCharsIn(row: row3, with: word)
default:
shouldAppend = false
}
if shouldAppend{
finalArr.append(word)
}
}
return finalArr
}
//https://leetcode.com/problems/move-zeroes/#/description
func removeZeros(arr: [Int]) -> [Int] {
var zeroArr = [Int]()
var nonZeroArr = [Int]()
for value in arr {
if value == 0 {
zeroArr.append(value)
} else {
nonZeroArr.append(value)
}
}
return nonZeroArr + zeroArr
}
func removeZerosHigherOrder(arr: [Int]) -> [Int] {
var zeroCount = 0
for num in arr {
if num == 0 {
zeroCount += 1
}
}
return arr.filter{$0 != 0} + Array(repeating: 0, count: zeroCount)
}
func removeZerosTwo(arr: inout [Int]) {
var zeroFinderIndex = 0
var numberFinderIndex = 0
while zeroFinderIndex < arr.count && numberFinderIndex < arr.count - 1 {
if arr[zeroFinderIndex] == 0 {
numberFinderIndex += 1
if arr[numberFinderIndex] != 0 {
swap(&arr[zeroFinderIndex], &arr[numberFinderIndex])
}
} else {
zeroFinderIndex += 1
}
}
}
var testArr = [1,0,0,0,0,1]
//removeZerosTwo(arr: &testArr)
//
// return nums.filter { $0 != 0 } + [Int](repeating: 0, count: nums.filter { $0 == 0 }.count)
//https://leetcode.com/problems/majority-element/#/description
class Solution {
func majorityElement(_ nums: [Int]) -> Int {
var myDict = [Int:Int]()
var majority = nums.count/2
for number in nums {
if myDict[number] != nil {
myDict[number]! += 1
} else {
myDict[number] = 1
}
}
for (keys,value) in myDict {
if value > majority {
return keys
}
}
return 0
}
}
| mit | 24593f6966b8e2a7eb8c6355399758c6 | 25.494652 | 346 | 0.585125 | 3.831787 | false | false | false | false |
SwiftyMagic/Magic | Magic/Magic/UIKit/UINavigationItemExtension.swift | 1 | 2246 | //
// UINavigationItemExtension.swift
// Magic
//
// Created by Broccoli on 2016/12/7.
// Copyright © 2016年 broccoliii. All rights reserved.
//
import Foundation
enum LoadingPosition : Int {
case center = 0
case left
case right
}
fileprivate var kLoadingPositionAssociationKey = "kLoadingPositionAssociationKey"
fileprivate var kSubstitutedViewAssociationKey = "kSubstitutedViewAssociationKey"
// MARK: - Methods
extension UINavigationItem {
func startAnimating(at position: LoadingPosition) {
stopAnimating()
objc_setAssociatedObject(self, kLoadingPositionAssociationKey, position, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let loadingView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
switch position {
case .left:
objc_setAssociatedObject(self, kSubstitutedViewAssociationKey, leftBarButtonItem!.customView!, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
leftBarButtonItem!.customView! = loadingView
case .center:
objc_setAssociatedObject(self, kSubstitutedViewAssociationKey, titleView!, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
titleView! = loadingView
case .right:
objc_setAssociatedObject(self, kSubstitutedViewAssociationKey, rightBarButtonItem!.customView!, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
rightBarButtonItem!.customView! = loadingView
}
loadingView.startAnimating()
}
func stopAnimating() {
let positionToRestore = objc_getAssociatedObject(self, kLoadingPositionAssociationKey) as! LoadingPosition
let componentToRestore = objc_getAssociatedObject(self, kSubstitutedViewAssociationKey) as! UIView
switch positionToRestore {
case .left:
leftBarButtonItem!.customView! = componentToRestore
case .center:
titleView! = componentToRestore
case .right:
rightBarButtonItem!.customView! = componentToRestore
}
objc_setAssociatedObject(self, kLoadingPositionAssociationKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(self, kSubstitutedViewAssociationKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
| mit | be68d1071ef49f0438f607715ca6a05c | 37.672414 | 143 | 0.712885 | 5.240654 | false | false | false | false |
ReactiveCocoa/ReactiveSwift | Sources/Observers/LazyMap.swift | 1 | 1385 | extension Operators {
internal final class LazyMap<Value, NewValue, Error: Swift.Error>: UnaryAsyncOperator<Value, NewValue, Error> {
let transform: (Value) -> NewValue
let box = Atomic<Value?>(nil)
let valueDisposable = SerialDisposable()
init(
downstream: Observer<NewValue, Error>,
downstreamLifetime: Lifetime,
target: Scheduler,
transform: @escaping (Value) -> NewValue
) {
self.transform = transform
super.init(downstream: downstream, downstreamLifetime: downstreamLifetime, target: target)
downstreamLifetime += valueDisposable
}
override func receive(_ value: Value) {
// Schedule only when there is no prior outstanding value.
if box.swap(value) == nil {
valueDisposable.inner = target.schedule {
if let value = self.box.swap(nil) {
self.unscheduledSend(self.transform(value))
}
}
}
}
override func terminate(_ termination: Termination<Error>) {
if case .interrupted = termination {
// `interrupted` immediately cancels any scheduled value.
//
// On the other hand, completion and failure does not cancel anything, and is scheduled to run after any
// scheduled value. `valueDisposable` will naturally be disposed by `downstreamLifetime` as soon as the
// downstream has processed the termination.
valueDisposable.dispose()
}
super.terminate(termination)
}
}
}
| mit | b2297d2c8dacd58f2df17d36e338799e | 31.209302 | 112 | 0.708303 | 4.00289 | false | false | false | false |
carabina/TouchGradientPicker | TouchGradientPicker/CenterColorGradientBuilder.swift | 1 | 1452 | //
// CenterColorGradientBuilder.swift
// TouchGradientPicker
//
// Created by Mike Mertsock on 8/19/15.
// Copyright (c) 2015 Esker Apps. All rights reserved.
//
import UIKit
public class CenterColorGradientBuilder: GradientBuilder {
public private(set) var currentValue: CenterColorGradient
public struct CenterColorBuilderParams {
public var hue: ((Pan, CGFloat) -> CGFloat)?
func colorFromPan(pan: Pan, panStartValue: UIColor) -> UIColor {
if let newHue = hue?(pan, panStartValue.hue) {
return panStartValue.colorWithHueComponent(newHue)
}
return panStartValue
}
}
public var centerColor = CenterColorBuilderParams()
public var hueVariance: ((Pan, CGFloat) -> CGFloat)? // = identity()
public init(initialValue: CenterColorGradient) {
currentValue = initialValue
}
public func gradientFromPan(pan: Pan, panStartValue: GradientType) -> GradientType {
let panStartValue = (panStartValue as? CenterColorGradient) ?? currentValue
var newCenterColor = centerColor.colorFromPan(pan, panStartValue: panStartValue.centerColor)
var newHueVariance = hueVariance?(pan, panStartValue.hueVariance)
currentValue = CenterColorGradient(
centerColor: newCenterColor,
hueVariance: newHueVariance ?? panStartValue.hueVariance)
return currentValue
}
}
| mit | 772c28caff03e808623d5985ad564015 | 33.571429 | 100 | 0.678375 | 4.5375 | false | false | false | false |
google/eddystone | tools/gatt-config/ios/Beaconfig/Beaconfig/UserInformation.swift | 2 | 4060 | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import UIKit
let kGetProjectsServer = "https://cloudresourcemanager.googleapis.com/v1beta1/projects"
enum GettingProjectsListState {
case UserHasNoProjects
case UnableToGetProjects
case GotUserProjects
}
///
/// Using Storyboard segues to load the UserLoginViewController was a safe choice, but segues
/// create a new instance of the view controller every time the segue is triggered. We needed
/// a class to hold the state of the view controller.
///
class UserInformation {
var userImage: UIImage
var userName: String?
var userEmail: String?
var userProjects: NSMutableArray?
var statusInfo: String
var userCurrentlySignedIn: Bool
var projectsArray: NSMutableArray!
var gotProjectsListCallback: ((state: GettingProjectsListState) -> Void)?
var selectedProjectIndex: Int?
init() {
userImage = UIImage(named: "Google")!
statusInfo = "Currently not signed in"
userCurrentlySignedIn = false
projectsArray = ["Not Selected"]
}
/// We want to clear all the data we have when the user signs out.
func clearData() {
userImage = UIImage(named: "Google")!
statusInfo = "Currently not signed in"
userCurrentlySignedIn = false
projectsArray = ["Not Selected"]
selectedProjectIndex = nil
}
func parseUserProjects(data: NSData) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
if let projectsList = json["projects"] as? NSArray {
for project in projectsList {
if let
projectID = project["projectId"],
ID = projectID as? String {
projectsArray.addObject(ID)
}
}
if let callback = gotProjectsListCallback {
callback(state: GettingProjectsListState.GotUserProjects)
}
} else {
/// The user has no projects.
if let callback = gotProjectsListCallback {
callback(state: GettingProjectsListState.UserHasNoProjects)
}
}
} catch {
print("error serializing JSON: \(error)")
}
}
func getprojectListHTTPRequest() {
if GIDSignIn.sharedInstance().currentUser != nil {
let bearer = GIDSignIn.sharedInstance().currentUser.authentication.accessToken
let bearerHeader = "Bearer \(bearer)"
let server = kGetProjectsServer
let url = NSURL(string: server)
let httpHeaders = ["Authorization" : bearerHeader,
"Accept" : "application/json"]
if let requestURL = url {
HTTPRequest.makeHTTPRequest(requestURL,
method: "GET",
postBody: nil,
requestHeaders: httpHeaders) { statusCode, data, error in
if statusCode == 200 {
self.parseUserProjects(data!)
} else {
if let callback = self.gotProjectsListCallback {
callback(state:
GettingProjectsListState.UnableToGetProjects)
}
}
}
}
}
}
func getProjectList(callback: (state: GettingProjectsListState) -> Void) {
gotProjectsListCallback = callback
getprojectListHTTPRequest()
}
}
| apache-2.0 | ad93b5f77679d2e37040f805e111f434 | 34.304348 | 97 | 0.622414 | 5.024752 | false | false | false | false |
huonw/swift | test/SILGen/nested_types_referencing_nested_functions.swift | 3 | 1058 |
// RUN: %target-swift-emit-silgen -module-name nested_types_referencing_nested_functions -enable-sil-ownership %s | %FileCheck %s
do {
func foo() { bar(2) }
func bar<T>(_: T) { foo() }
class Foo {
// CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_CACycfc : $@convention(method) (@owned Foo) -> @owned Foo {
init() {
foo()
}
// CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_C3zimyyF : $@convention(method) (@guaranteed Foo) -> ()
func zim() {
foo()
}
// CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_C4zangyyxlF : $@convention(method) <T> (@in_guaranteed T, @guaranteed Foo) -> ()
func zang<T>(_ x: T) {
bar(x)
}
// CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_CfD : $@convention(method) (@owned Foo) -> ()
deinit {
foo()
}
}
let x = Foo()
x.zim()
x.zang(1)
_ = Foo.zim
_ = Foo.zang as (Foo) -> (Int) -> ()
_ = x.zim
_ = x.zang as (Int) -> ()
}
| apache-2.0 | c3d7d0c100139dbae8af317df7d083b3 | 30.117647 | 162 | 0.600189 | 3.057803 | false | false | false | false |
huonw/swift | test/IRGen/subclass.swift | 3 | 2630 | // RUN: %target-swift-frontend -enable-objc-interop -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// CHECK-DAG: %swift.refcounted = type {
// CHECK-DAG: [[TYPE:%swift.type]] = type
// CHECK-DAG: [[OBJC_CLASS:%objc_class]] = type {
// CHECK-DAG: [[OPAQUE:%swift.opaque]] = type
// CHECK-DAG: [[A:%T8subclass1AC]] = type <{ [[REF:%swift.refcounted]], %TSi, %TSi }>
// CHECK-DAG: [[INT:%TSi]] = type <{ i64 }>
// CHECK-DAG: [[B:%T8subclass1BC]] = type <{ [[REF]], [[INT]], [[INT]], [[INT]] }>
// CHECK: @_DATA__TtC8subclass1A = private constant {{.*\* } }}{
// CHECK: @"$S8subclass1ACMf" = internal global [[A_METADATA:<{.*i64 }>]] <{
// CHECK: void ([[A]]*)* @"$S8subclass1ACfD",
// CHECK: i8** @"$SBoWV",
// CHECK: i64 ptrtoint ([[OBJC_CLASS]]* @"$S8subclass1ACMm" to i64),
// CHECK: [[OBJC_CLASS]]* @"OBJC_CLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK: [[OPAQUE]]* @_objc_empty_cache,
// CHECK: [[OPAQUE]]* null,
// CHECK: i64 add (i64 ptrtoint ({ {{.*}} }* @_DATA__TtC8subclass1A to i64), i64 1),
// CHECK: i64 ([[A]]*)* @"$S8subclass1AC1fSiyF",
// CHECK: [[A]]* ([[TYPE]]*)* @"$S8subclass1AC1gACyFZ"
// CHECK: }>
// CHECK: @_DATA__TtC8subclass1B = private constant {{.*\* } }}{
// CHECK: @"$S8subclass1BCMf" = internal global <{ {{.*}} }> <{
// CHECK: void ([[B]]*)* @"$S8subclass1BCfD",
// CHECK: i8** @"$SBoWV",
// CHECK: i64 ptrtoint ([[OBJC_CLASS]]* @"$S8subclass1BCMm" to i64),
// CHECK: [[TYPE]]* {{.*}} @"$S8subclass1ACMf",
// CHECK: [[OPAQUE]]* @_objc_empty_cache,
// CHECK: [[OPAQUE]]* null,
// CHECK: i64 add (i64 ptrtoint ({ {{.*}} }* @_DATA__TtC8subclass1B to i64), i64 1),
// CHECK: i64 ([[B]]*)* @"$S8subclass1BC1fSiyF",
// CHECK: [[A]]* ([[TYPE]]*)* @"$S8subclass1AC1gACyFZ"
// CHECK: }>
// CHECK: @objc_classes = internal global [2 x i8*] [i8* {{.*}} @"$S8subclass1ACN" {{.*}}, i8* {{.*}} @"$S8subclass1BCN" {{.*}}]
class A {
var x = 0
var y = 0
func f() -> Int { return x }
class func g() -> A { return A() }
init() { }
}
class B : A {
var z : Int = 10
override func f() -> Int { return z }
}
class G<T> : A {
}
// Ensure that downcasts to generic types instantiate generic metadata instead
// of trying to reference global metadata. <rdar://problem/14265663>
// CHECK: define hidden swiftcc %T8subclass1GCySiG* @"$S8subclass9a_to_gint1aAA1GCySiGAA1AC_tF"(%T8subclass1AC*) {{.*}} {
func a_to_gint(a: A) -> G<Int> {
// CHECK: call swiftcc %swift.metadata_response @"$S8subclass1GCySiGMa"(i64 0)
// CHECK: call i8* @swift_dynamicCastClassUnconditional
return a as! G<Int>
}
// CHECK: }
| apache-2.0 | a3b01c943d5bf337a750e8165203160b | 39.461538 | 135 | 0.585932 | 2.874317 | false | false | false | false |
fvaldez/score_point_ios | scorePoint/RoundView.swift | 1 | 931 | //
// RoundView.swift
// scorePoint
//
// Created by Adriana Gonzalez on 5/3/16.
// Copyright © 2016 Adriana Gonzalez. All rights reserved.
//
import UIKit
@IBDesignable
class RoundView: UIView {
var makeCircle = false
@IBInspectable var cornerRadius: CGFloat = 5.0 {
didSet{
setupView()
}
}
@IBInspectable var fullCircle: Bool = false{
didSet{
makeCircle = fullCircle
setupView()
}
}
override func awakeFromNib() {
setupView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setupView()
}
func setupView(){
if(makeCircle == true){
self.layer.cornerRadius = self.frame.size.width/2
self.layer.masksToBounds = true
}else{
self.layer.cornerRadius = cornerRadius
}
}
}
| mit | bf4d22f72556db9fbb6c6e0d92fc1265 | 18.375 | 61 | 0.564516 | 4.769231 | false | false | false | false |
luyi326/SwiftIO | Sources/inet+Extensions.swift | 1 | 7076 | //
// Inet+Utilities.swift
// SwiftIO
//
// Created by Jonathan Wight on 5/20/15.
//
// Copyright (c) 2014, Jonathan Wight
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 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 HOLDER 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 Darwin
import SwiftUtilities
// MARK: in_addr extensions
extension in_addr: Equatable {
}
public func == (lhs: in_addr, rhs: in_addr) -> Bool {
return unsafeBitwiseEquality(lhs, rhs)
}
extension in_addr: CustomStringConvertible {
public var description: String {
var s = self
return tryElseFatalError() {
return try Swift.withUnsafeMutablePointer(&s) {
let ptr = UnsafePointer <Void> ($0)
return try inet_ntop(addressFamily: AF_INET, address: ptr)
}
}
}
}
// MARK: in6_addr extensions
extension in6_addr: Equatable {
}
public func == (lhs: in6_addr, rhs: in6_addr) -> Bool {
return unsafeBitwiseEquality(lhs, rhs)
}
extension in6_addr: CustomStringConvertible {
public var description: String {
var s = self
return tryElseFatalError() {
return try Swift.withUnsafeMutablePointer(&s) {
let ptr = UnsafePointer <Void> ($0)
return try inet_ntop(addressFamily: AF_INET6, address: ptr)
}
}
}
}
// MARK: Swift wrapper functions for useful (but fiddly) POSIX network functions
/**
`inet_ntop` wrapper that takes an address in network byte order (big-endian) to presentation format.
- parameter addressFamily: IPv4 (AF_INET) or IPv6 (AF_INET6) family.
- parameter address: The address structure to convert.
- throws: @schwa what's proper documentation for this?
- returns: The IP address in presentation format
*/
public func inet_ntop(addressFamily addressFamily: Int32, address: UnsafePointer <Void>) throws -> String {
var buffer: Array <Int8>
var size: Int
switch addressFamily {
case AF_INET:
size = Int(INET_ADDRSTRLEN)
case AF_INET6:
size = Int(INET6_ADDRSTRLEN)
default:
fatalError("Unknown address family")
}
buffer = Array <Int8> (count: size, repeatedValue: 0)
return buffer.withUnsafeMutableBufferPointer() {
(inout outputBuffer: UnsafeMutableBufferPointer <Int8>) -> String in
let result = inet_ntop(addressFamily, address, outputBuffer.baseAddress, socklen_t(size))
return String(CString: result, encoding: NSASCIIStringEncoding)!
}
}
// MARK: -
public func getnameinfo(addr: UnsafePointer<sockaddr>, addrlen: socklen_t, inout hostname: String?, inout service: String?, flags: Int32) throws {
var hostnameBuffer = [Int8](count: Int(NI_MAXHOST), repeatedValue: 0)
var serviceBuffer = [Int8](count: Int(NI_MAXSERV), repeatedValue: 0)
let result = hostnameBuffer.withUnsafeMutableBufferPointer() {
(inout hostnameBufferPtr: UnsafeMutableBufferPointer<Int8>) -> Int32 in
serviceBuffer.withUnsafeMutableBufferPointer() {
(inout serviceBufferPtr: UnsafeMutableBufferPointer<Int8>) -> Int32 in
let result = getnameinfo(
addr, addrlen,
hostnameBufferPtr.baseAddress, socklen_t(NI_MAXHOST),
serviceBufferPtr.baseAddress, socklen_t(NI_MAXSERV),
flags)
if result == 0 {
hostname = String(CString: hostnameBufferPtr.baseAddress, encoding: NSASCIIStringEncoding)
service = String(CString: serviceBufferPtr.baseAddress, encoding: NSASCIIStringEncoding)
}
return result
}
}
guard result == 0 else {
throw Errno(rawValue: errno) ?? Error.Unknown
}
}
// MARK: -
public func getaddrinfo(hostname: String?, service: String? = nil, hints: addrinfo, block: UnsafePointer<addrinfo> throws -> Bool) throws {
let hostname = hostname ?? ""
let service = service ?? ""
var hints = hints
var info: UnsafeMutablePointer <addrinfo> = nil
let result = getaddrinfo(hostname, service, &hints, &info)
guard result == 0 else {
let ptr = gai_strerror(result)
if let string = String(UTF8String: ptr) {
throw Error.Generic(string)
}
else {
throw Error.Unknown
}
}
var current = info
while current != nil {
if try block(current) == false {
break
}
current = current.memory.ai_next
}
freeaddrinfo(info)
}
public func getaddrinfo(hostname: String?, service: String? = nil, hints: addrinfo) throws -> [Address] {
var addresses: [Address] = []
try getaddrinfo(hostname, service: service, hints: hints) {
let addr = sockaddr_storage(addr: $0.memory.ai_addr, length: Int($0.memory.ai_addrlen))
let address = Address(sockaddr: addr)
addresses.append(address)
return true
}
return Array(Set(addresses)).sort(<)
}
// MARK: -
public extension in_addr {
var octets: (UInt8, UInt8, UInt8, UInt8) {
let address = UInt32(networkEndian: s_addr)
return (
UInt8((address >> 24) & 0xFF),
UInt8((address >> 16) & 0xFF),
UInt8((address >> 8) & 0xFF),
UInt8(address & 0xFF)
)
}
}
public extension in6_addr {
var words: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) {
assert(sizeof(in6_addr) == sizeof((UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)))
var copy = self
return withUnsafePointer(©) {
let networkWords = UnsafeBufferPointer <UInt16> (start: UnsafePointer <UInt16> ($0), count: 8)
let words = networkWords.map() { UInt16(networkEndian: $0) }
return (words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7])
}
}
}
| mit | 4fcd2fb5dd5c6ec2cfbb4e3383333698 | 33.857143 | 146 | 0.655314 | 4.184506 | false | false | false | false |
izandotnet/ULAQ | ULAQ/InAppPurchaseManager.swift | 1 | 6343 | //
// InAppPurchaseManager.swift
// ULAQ
//
// Created by Rohaizan Roosley on 10/05/2017.
// Copyright © 2017 Rohaizan Roosley. All rights reserved.
//
import StoreKit
import SpriteKit
protocol InAppPurchaseManagerDelegate: class {
func didFinishTask(sender: InAppPurchaseManager)
func transactionInProgress(sender: InAppPurchaseManager)
func transactionCompleted(sender: InAppPurchaseManager)
}
class InAppPurchaseManager: NSObject, SKProductsRequestDelegate,SKPaymentTransactionObserver {
var productID = ""
var productsRequest = SKProductsRequest()
var iapProducts = [SKProduct]()
var transactionTitle = ""
var transactionMsg = ""
var parent: SKScene?
weak var delegate:InAppPurchaseManagerDelegate?
override init() {
self.productID = ""
self.productsRequest = SKProductsRequest()
self.iapProducts = [SKProduct]()
super.init()
self.fetchAvailableProducts()
}
func fetchAvailableProducts() {
delegate?.transactionInProgress(sender: self)
let productIdentifiers = NSSet(objects:PREMIUM_PROD_ID)
productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers as! Set<String>)
productsRequest.delegate = self
productsRequest.start()
}
func buyPremium(){
delegate?.transactionInProgress(sender: self)
purchaseMyProduct(product: iapProducts[0])
}
func restorePurchase(){
delegate?.transactionInProgress(sender: self)
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().restoreCompletedTransactions()
}
// MARK: - RESTORE
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
if (queue.transactions.count < 1){
self.showDialog(title: "Restore Purchase Failed!", message: "You have not made any purchase.")
}
for transaction in queue.transactions {
let t: SKPaymentTransaction = transaction
let prodID = t.payment.productIdentifier as String
switch prodID {
case PREMIUM_PROD_ID:
UnlockSkinManager().buyPremium()
self.showDialog(title: "Restore Purchase Successful!", message: "You have successfully restored your purchase.")
delegate?.didFinishTask(sender: self)
SKPaymentQueue.default().finishTransaction(transaction)
default:
self.showDialog(title: "Restore Purchase Failed!", message: "You have not made any purchase.")
SKPaymentQueue.default().finishTransaction(transaction)
}
}
delegate?.transactionCompleted(sender: self)
}
// MARK: - RESTORE ERROR
func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
self.showDialog(title: "Restore Purchase Failed!", message: "You have not made any purchase.")
delegate?.transactionCompleted(sender: self)
}
// MARK: - REQUEST IAP PRODUCTS
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
if (response.products.count > 0) {
iapProducts = response.products
}
delegate?.transactionCompleted(sender: self)
}
// MARK:- IAP PAYMENT QUEUE
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction:AnyObject in transactions {
if let trans = transaction as? SKPaymentTransaction {
switch trans.transactionState {
case .purchased:
SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
if productID == PREMIUM_PROD_ID {
UnlockSkinManager().buyPremium()
self.showDialog(title: "Purchase Successful!", message: "Thank you for buying. All skins has been unlocked. Hope you will enjoy the game. ")
delegate?.didFinishTask(sender: self)
}
break
case .failed:
self.showDialog(title: "Restore Purchase Failed!", message: "You have not made any purchase.")
SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
break
case .restored:
self.showDialog(title: "Restore Purchase Successful!", message: "You have successfully restored your purchase.")
SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
break
default: break
}
}
}
delegate?.transactionCompleted(sender: self)
}
// MARK: - MAKE PURCHASE OF A PRODUCT
func canMakePurchases() -> Bool { return SKPaymentQueue.canMakePayments() }
func purchaseMyProduct(product: SKProduct) {
if self.canMakePurchases() {
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().add(payment)
print("PRODUCT TO PURCHASE: \(product.productIdentifier)")
productID = product.productIdentifier
} else {
// IAP Purchases dsabled on the Device
self.showDialog(title: "Purchase Error", message: "Purchase is disabled in your device")
}
delegate?.transactionCompleted(sender: self)
}
//MARK: Private functions
private func showDialog(title:String, message:String){
self.transactionTitle = title
self.transactionMsg = message
delegate?.transactionCompleted(sender: self)
}
}
| mit | df32de7d366d7f3fd743b250d1d5706a | 34.233333 | 164 | 0.587196 | 5.888579 | false | false | false | false |
BridgeTheGap/KRClient | KRClient/Classes/Error.swift | 1 | 4043 | //
// KRClientError.swift
// Pods
//
// Created by Joshua Park on 9/8/16.
//
//
public enum KRClientError: Error {
public struct Domain {
static let `default` = "pod.KRClient"
static let request = "\(Domain.default).request"
static let response = "\(Domain.default).response"
}
public struct ErrorCode {
static let unknown = 0
// KRClient operation related errors
static let invalidOperation = 100
static let propagatedError = 101
// Request related errors
static let requestFailure = 200
static let stringToURLConversionFailure = 201
// Response related errors
static let dataValidationFailure = 300
static let dataConversionFailure = 310
}
public struct UserInfoKey {
static let debugSuggestion = "DebugSuggestion"
static let errorLocation = "ErrorLocation"
static let expectedDataType = "ExpectedDataType"
static let urlResponse = "URLResponse"
}
public class Location: NSObject {
public var file: String
public var line: Int
public override var description: String { return "\(type(of: self))(\(file):\(line))" }
public init(file: String, line: Int) { (self.file, self.line) = (file, line) }
}
case unknown
case invalidOperation(description: String?, location: (file: String, line: Int))
case propagatedError(error: NSError, location: (file: String, line: Int))
case requestFailure(description: String?)
case stringToURLConversionFailure(string: String)
case dataValidationFailure
case dataConversionFailure(type: Any)
var nsError: NSError {
switch self {
case .unknown:
return NSError(domain: Domain.default, code: ErrorCode.unknown, userInfo: nil)
case .invalidOperation(description: let description, location: let location):
return NSError(domain: Domain.default, code: ErrorCode.requestFailure, userInfo: [
NSLocalizedDescriptionKey: "An invalid operation was attempted.",
NSLocalizedFailureReasonErrorKey: description ?? "Unknown.",
UserInfoKey.errorLocation: Location(file: location.0, line: location.1)
])
case .propagatedError(error: let error, location: let location):
return NSError(domain: Domain.default, code: ErrorCode.propagatedError, userInfo: [
NSUnderlyingErrorKey: error,
UserInfoKey.errorLocation: Location(file: location.0, line: location.1)
])
case .requestFailure(description: let description):
return NSError(domain: Domain.request, code: ErrorCode.requestFailure, userInfo: [
NSLocalizedDescriptionKey: "Failed to make an HTTP request.",
NSLocalizedFailureReasonErrorKey: description ?? "Unknown."
])
case .stringToURLConversionFailure(string: let string):
return NSError(domain: Domain.request, code: ErrorCode.stringToURLConversionFailure, userInfo: [
NSLocalizedDescriptionKey: "Failed to initialze a URL instance with string: \(string)."
])
case .dataValidationFailure:
return NSError(domain: Domain.response, code: ErrorCode.dataValidationFailure, userInfo:[
NSLocalizedDescriptionKey: "The response data failed to pass validation.",
])
case .dataConversionFailure(type: let type):
return NSError(domain: Domain.response, code: ErrorCode.dataConversionFailure, userInfo: [
NSLocalizedDescriptionKey: "The response data failed to convert to appropriate type.",
UserInfoKey.expectedDataType: type
])
}
}
}
| mit | cdf1826b7aaa6eff3834c146f72f2662 | 36.091743 | 108 | 0.612417 | 5.45614 | false | false | false | false |
jovito-royeca/ManaKit | Sources/Classes/NSAttributedString+Utilities.swift | 1 | 8124 | //
// NSAttributedString+Utilities.swift
// ManaKit
//
// Created by Jovito Royeca on 20/06/2018.
//
import UIKit
import Kanna
public extension NSAttributedString {
convenience init(symbol: String, pointSize: CGFloat) {
let newAttributedString = NSMutableAttributedString()
let text = symbol.trimmingCharacters(in: CharacterSet.whitespaces)
var fragmentText = NSMutableString()
var sentinel = 0
if text.count == 0 {
self.init(string: symbol)
return
}
repeat {
for i in sentinel...text.count - 1 {
let c = text[text.index(text.startIndex, offsetBy: i)]
if c == "{" {
let code = NSMutableString()
for j in i...text.count - 1 {
let cc = text[text.index(text.startIndex, offsetBy: j)]
code.append(String(cc))
if cc == "}" {
sentinel = j + 1
break
}
}
var cleanCode = code.replacingOccurrences(of: "{", with: "")
.replacingOccurrences(of: "}", with: "")
.replacingOccurrences(of: "/", with: "")
if cleanCode.lowercased() == "chaos" {
cleanCode = "Chaos"
}
guard let image = ManaKit.sharedInstance.symbolImage(name: cleanCode as String) else {
self.init(string: symbol)
return
}
let imageAttachment = NSTextAttachment()
imageAttachment.image = image
var width = CGFloat(16)
let height = CGFloat(16)
var imageOffsetY = CGFloat(0)
if cleanCode == "100" {
width = 35
} else if cleanCode == "1000000" {
width = 60
}
if height > pointSize {
imageOffsetY = -(height - pointSize) / 2.0
} else {
imageOffsetY = -(pointSize - height) / 2.0
}
imageAttachment.bounds = CGRect(x: 0, y: imageOffsetY, width: width, height: height)
let attachmentString = NSAttributedString(attachment: imageAttachment)
let attributedString = NSMutableAttributedString(string: fragmentText as String)
attributedString.append(attachmentString)
newAttributedString.append(attributedString)
fragmentText = NSMutableString()
break
} else {
fragmentText.append(String(c))
sentinel += 1
}
}
} while sentinel <= text.count - 1
let attributedString = NSMutableAttributedString(string: fragmentText as String)
newAttributedString.append(attributedString)
self.init(attributedString: newAttributedString)
}
convenience init(html: String) {
let style = "<style>" +
"body { font-family: -apple-system; font-size:15; } " +
"</style>"
let html = "\(style)\(html)"
var links = [[String: Any]]()
guard let doc = try? HTML(html: html, encoding: .utf16) else {
self.init(string: html)
return
}
// Search for links
for link in doc.css("a, link") {
if let text = link.text,
let href = link["href"] {
links.append([text: href])
}
}
guard let data = html.data(using: String.Encoding.utf16) else {
self.init(string: html)
return
}
let options = [convertFromNSAttributedStringDocumentAttributeKey(NSAttributedString.DocumentAttributeKey.documentType): convertFromNSAttributedStringDocumentType(NSAttributedString.DocumentType.html)]
guard let attributedString = try? NSMutableAttributedString(data: data,
options: convertToNSAttributedStringDocumentReadingOptionKeyDictionary(options),
documentAttributes: nil) else {
self.init(string: html)
return
}
// add tappble links
for link in links {
for (k,v) in link {
let foundRange = attributedString.mutableString.range(of: k)
if foundRange.location != NSNotFound {
attributedString.addAttribute(NSAttributedString.Key.link, value: v, range: foundRange)
// attributedString.addAttribute(NSForegroundColorAttributeName, value: kGlobalTintColor, range: foundRange)
// attributedString.addAttribute(NSUnderlineColorAttributeName, value: kGlobalTintColor, range: foundRange)
}
}
}
self.init(attributedString: attributedString)
}
func widthOf(symbol: String) -> CGFloat {
let text = symbol.trimmingCharacters(in: CharacterSet.whitespaces)
var width = CGFloat(0)
var sentinel = 0
if text.count == 0 {
return width
}
repeat {
for i in sentinel...text.count - 1 {
let c = text[text.index(text.startIndex, offsetBy: i)]
if c == "{" {
let code = NSMutableString()
for j in i...text.count - 1 {
let cc = text[text.index(text.startIndex, offsetBy: j)]
code.append(String(cc))
if cc == "}" {
sentinel = j + 1
break
}
}
var cleanCode = code.replacingOccurrences(of: "{", with: "")
.replacingOccurrences(of: "}", with: "")
.replacingOccurrences(of: "/", with: "")
if cleanCode.lowercased() == "chaos" {
cleanCode = "Chaos"
}
if cleanCode == "100" {
width += 35
} else if cleanCode == "1000000" {
width += 60
} else {
width += CGFloat(16)
}
break
} else {
sentinel += 1
}
}
} while sentinel <= text.count - 1
return width
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringDocumentAttributeKey(_ input: NSAttributedString.DocumentAttributeKey) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringDocumentType(_ input: NSAttributedString.DocumentType) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToNSAttributedStringDocumentReadingOptionKeyDictionary(_ input: [String: Any]) -> [NSAttributedString.DocumentReadingOptionKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.DocumentReadingOptionKey(rawValue: key), value)})
}
| mit | 979e7189c629fed720986569fff21966 | 37.320755 | 209 | 0.474643 | 6.094524 | false | false | false | false |
royhsu/chocolate-touch | Chocolate/ChocolateTests/MockWebRequest.swift | 1 | 1959 | //
// MockWebRequest.swift
// Chocolate
//
// Created by 許郁棋 on 2016/9/30.
// Copyright © 2016年 Tiny World. All rights reserved.
//
import CHFoundation
import Chocolate
import Foundation
struct MockWebRequest {
static let jsonObject1: [String: String] = [ "name": "Roy" ]
static let jsonObject2: [String: [String]] = [ "hobbies": [ "drawing", "basketball" ] ]
static func newWebRequest() -> CHCacheWebRequest {
let url1 = URL(string: "https://example.com")!
let urlRequest1 = URLRequest(url: url1)
var webService1 = WebService<Any>(urlRequest: urlRequest1)
let mockSession1 = MockURLSession()
mockSession1.data = try! JSONSerialization.data(
withJSONObject: jsonObject1,
options: []
)
webService1.urlSession = mockSession1
let url2 = URL(string: "https://example2.com")!
let urlRequest2 = URLRequest(url: url2)
var webService2 = WebService<Any>(urlRequest: urlRequest2)
let mockSession2 = MockURLSession()
mockSession2.data = try! JSONSerialization.data(
withJSONObject: jsonObject2,
options: []
)
webService2.urlSession = mockSession2
let webServiceGroup = WebServiceGroup(
webServices: [ webService1, webService2 ]
)
let webRequest = CHCacheWebRequest(webServiceGroup: webServiceGroup) { objects in
let jsonObject1 = objects[0] as! [String: Any]
let name = jsonObject1["name"] as! String
let jsonObject2 = objects[1] as! [String: Any]
let hobbies = jsonObject2["hobbies"] as! [String]
return [
"name": name,
"hobbies": hobbies
]
}
return webRequest
}
}
| mit | b7d385a87f40904c61757c52526c7d04 | 28.104478 | 91 | 0.560513 | 4.620853 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/WordPressTest/EditorSettingsServiceTests.swift | 1 | 6169 | import Foundation
@testable import WordPress
private class TestableEditorSettingsService: EditorSettingsService {
let mockApi: WordPressComRestApi
init(managedObjectContext context: NSManagedObjectContext, wpcomApi: WordPressComRestApi) {
mockApi = wpcomApi
super.init(managedObjectContext: context)
}
override func api(for blog: Blog) -> WordPressComRestApi? {
return mockApi
}
override var apiForDefaultAccount: WordPressComRestApi? {
return mockApi
}
}
class EditorSettingsServiceTest: XCTestCase {
var contextManager: TestContextManager!
var context: NSManagedObjectContext!
var remoteApi: MockWordPressComRestApi!
var service: EditorSettingsService!
var database: KeyValueDatabase!
var account: WPAccount!
override func setUp() {
super.setUp()
contextManager = TestContextManager()
context = contextManager.mainContext
remoteApi = MockWordPressComRestApi()
database = EphemeralKeyValueDatabase()
service = TestableEditorSettingsService(managedObjectContext: context, wpcomApi: remoteApi)
Environment.replaceEnvironment(contextManager: contextManager)
setupDefaultAccount(with: context)
}
func setupDefaultAccount(with context: NSManagedObjectContext) {
account = ModelTestHelper.insertAccount(context: context)
account.authToken = "auth"
account.uuid = "uuid"
AccountService(managedObjectContext: context).setDefaultWordPressComAccount(account)
}
override func tearDown() {
ContextManager.overrideSharedInstance(nil)
super.tearDown()
}
func testLocalSettingsMigrationPostAztec() {
let blog = makeTestBlog()
// Self-Hosted sites will default to Aztec
blog.account = nil
sync(with: blog)
// Call GET settings from remote
XCTAssertTrue(remoteApi.getMethodCalled)
// Respond with mobile editor not yet set on the server
let response = responseWith(mobileEditor: "")
remoteApi.successBlockPassedIn?(response, HTTPURLResponse())
// Begin migration from local to remote
// Should call POST local settings to remote (migration)
XCTAssertTrue(remoteApi.postMethodCalled)
XCTAssertTrue(remoteApi.URLStringPassedIn?.contains("platform=mobile&editor=gutenberg") ?? false)
// Respond with mobile editor set on the server
let finalResponse = responseWith(mobileEditor: "gutenberg")
remoteApi.successBlockPassedIn?(finalResponse, HTTPURLResponse())
waitForExpectations(timeout: 0.1) { (error) in
// The default value should be now on local and remote
XCTAssertEqual(blog.mobileEditor, .gutenberg)
}
}
func testAppWideGutenbergSyncWithServer() {
service.migrateGlobalSettingToRemote(isGutenbergEnabled: true)
XCTAssertTrue(remoteApi.postMethodCalled)
XCTAssertTrue(remoteApi.URLStringPassedIn?.contains("me/gutenberg") ?? false)
let parameters = remoteApi.parametersPassedIn as? [String: Any]
XCTAssertEqual(parameters?["editor"] as? String, MobileEditor.gutenberg.rawValue)
}
func testAppWideAztecSyncWithServer() {
database.set(false, forKey: GutenbergSettings.Key.appWideEnabled)
service.migrateGlobalSettingToRemote(isGutenbergEnabled: false)
XCTAssertTrue(remoteApi.postMethodCalled)
XCTAssertTrue(remoteApi.URLStringPassedIn?.contains("me/gutenberg") ?? false)
let parameters = remoteApi.parametersPassedIn as? [String: Any]
XCTAssertEqual(parameters?["editor"] as? String, MobileEditor.aztec.rawValue)
}
func testPostAppWideEditorSettingResponseIsHandledProperlyWithGutenberg() {
let numberOfBlogs = 10
let blogs = addBlogsToAccount(count: numberOfBlogs)
let response = bulkResponse(with: .gutenberg, count: numberOfBlogs)
service.migrateGlobalSettingToRemote(isGutenbergEnabled: true)
remoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse())
blogs.forEach {
XCTAssertTrue($0.isGutenbergEnabled)
}
}
func testPostAppWideEditorSettingResponseIsHandledProperlyWithAztec() {
let numberOfBlogs = 10
let blogs = addBlogsToAccount(count: numberOfBlogs)
let response = bulkResponse(with: .aztec, count: numberOfBlogs)
blogs.forEach {
// Pre-set gutenberg to be sure it is overiden with aztec
$0.mobileEditor = .gutenberg
}
service.migrateGlobalSettingToRemote(isGutenbergEnabled: false)
remoteApi.successBlockPassedIn?(response as AnyObject, HTTPURLResponse())
blogs.forEach {
XCTAssertFalse($0.isGutenbergEnabled)
XCTAssertEqual($0.editor, .aztec)
}
}
}
extension EditorSettingsServiceTest {
func addBlogsToAccount(count: Int) -> [Blog] {
let blogs = makeTestBlogs(count: count)
account.addBlogs(Set(blogs))
return blogs
}
func makeTestBlogs(count: Int) -> [Blog] {
return (1...count).map(makeTestBlog)
}
func makeTestBlog(withID id: Int = 1) -> Blog {
let blog = ModelTestHelper.insertDotComBlog(context: context)
blog.dotComID = NSNumber(value: id)
blog.account?.authToken = "auth"
return blog
}
func bulkResponse(with editor: MobileEditor, count: Int) -> [String: String] {
return (1...count).reduce(into: [String: String]()) {
$0["\($1)"] = editor.rawValue
}
}
func responseWith(mobileEditor: String) -> AnyObject {
return [
"editor_mobile": mobileEditor,
"editor_web": "classic",
] as AnyObject
}
func sync(with blog: Blog) {
let expec = expectation(description: "success")
expec.assertForOverFulfill = true
service.syncEditorSettings(for: blog, success: {
expec.fulfill()
}) { (error) in
XCTFail("This call should succeed. Error: \(error)")
expec.fulfill()
}
}
}
| gpl-2.0 | 4d4db6e948606220a340d75e15902850 | 34.251429 | 105 | 0.678068 | 4.907717 | false | true | false | false |
iXieYi/Weibo_DemoTest | Weibo_DemoTest/Weibo_DemoTest/VisitorView.swift | 1 | 9052 | //
// VisitorView.swift
// Weibo_DemoTest
//
// Created by 谢毅 on 16/12/12.
// Copyright © 2016年 xieyi. All rights reserved.
//
import UIKit
///访客视图
////代理协议
//protocol VisitorViewDelegate:NSObjectProtocol{
//
///// 注册
// func visitorViewDidRegister()
///// 登录
// func visitorViewDidLogin()
//}
/// 访客视图处理 - 用户未登录界面显示
class VisitorView: UIView {
//定义代理,weak一旦被释放,会变成nil weak 因此不能使用let修饰
// weak var delegate:VisitorViewDelegate?
//
// @objc private func clickLogin(){
//
// delegate?.visitorViewDidLogin()
//
// }
// @objc private func clickRegister(){
//
// delegate?.visitorViewDidRegister()
//
// }
//MARK: -设置视图信息
/// 设置视图信息
///
/// - parameter imageName: 图片名称,首页设置为nil
/// - parameter title: 消息文字
func setupInfo(imageName:String?,title:String){
messageLabel1.text = title
guard let imgName = imageName else{
startAnim()
return
}
iconView.image = UIImage(named:imageName!)
//隐藏小房子
homeIconView.hidden = true
//将遮罩图像移动到底层
sendSubviewToBack(maskIconView)
}
private func startAnim(){
let anim = CABasicAnimation(keyPath: "transform.rotation")
anim.toValue = 2*M_PI
anim.repeatCount = MAXFLOAT //设置其不停旋转
anim.duration = 20 //20秒动画时长
//可以用在不断重复的动画上,当动画绑定的图层视图被销毁时,动画会自动被销毁
anim.removedOnCompletion = false //表示完成之后不删除动画,解决当用户切换视图又返回时动画会停止的问题
//添加到图层上
iconView.layer.addAnimation(anim, forKey: nil)
}
//MARK:- 构造函数
//initWithFrame 是UIView指定的构造函数
//使用纯代码开发
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
//使用SB或者xib开发加载的函数
required init?(coder aDecoder: NSCoder) {
//如果使用sb开发这个视图,会直接奔溃
fatalError("init(coder:) has not been implemented")
// setupUI()
}
//MARK: - 懒加载控件
//图标,使用image:构造函数创建的imageView默认就是image的大小
//小滚动
private lazy var iconView:UIImageView = UIImageView(imageName: "visitordiscover_feed_image_smallicon")
//遮罩
private lazy var maskIconView:UIImageView = UIImageView(imageName: "visitordiscover_feed_mask_smallicon")
//小房子
private lazy var homeIconView:UIImageView = UIImageView(imageName:"visitordiscover_feed_image_house")
//消息文字(在便利构造函数中实现)
private lazy var messageLabel1:UILabel = UILabel(title: "")
//登陆按钮
lazy var loginButton:UIButton = UIButton(title: "登录", color:UIColor.orangeColor() , backimageName: "common_button_white_disable")
//注册按钮
lazy var registerButton:UIButton = UIButton(title: "注册", color:UIColor.orangeColor() , backimageName: "common_button_white_disable")
}
//类似于OC的分类,分类中不能定义 存储性的数据,swift也是如此的
//私有属性放在代码下端,便于空间的添加,避免跨度太大
extension VisitorView{
/// 设置界面
private func setupUI(){
//1.添加界面,按图层顺序添加
addSubview(iconView)
addSubview(maskIconView)
addSubview(homeIconView)
addSubview(messageLabel1)
addSubview(registerButton)
addSubview(loginButton)
//2.添加自动布局
/* 自动布局的公式
"view1.attr1 = view2.attr2 * multiplier + constant"
添加约束要添加在其父视图上,子视图需要有统一的参照物
*/
//translatesAutoresizingMaskIntoConstraints默认是ture支持setFrame方式设置控件,false表示设置支持自动布局设置控件位置
//(纯代码设置自动布局时必须加上)
for v in subviews{//遍历所有子视图,使用自动布局
v.translatesAutoresizingMaskIntoConstraints = false
}
//1.图标
/// 水平方向上的限制
///
/// @param iconView 需要布局的图标
/// @param .CenterX 需要图标设置的限制参数(约束属性)
/// @param .Equal 是否等于(约束关系)
/// @param self 该视图的参照物(参照视图)
/// @param .CenterX 参照物对应类别的限制参数(参照属性)
/// @param 1.0 公式中的放大倍数
/// @param 0 约束数值
addConstraint(NSLayoutConstraint(item: iconView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0))
//垂直方向上的限制
addConstraint(NSLayoutConstraint(item: iconView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: -60))
//2.小房子
addConstraint(NSLayoutConstraint(item: homeIconView, attribute: .CenterX, relatedBy: .Equal, toItem: iconView, attribute: .CenterX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: homeIconView, attribute: .CenterY, relatedBy: .Equal, toItem: iconView, attribute: .CenterY, multiplier: 1.0, constant: 0))
//3.消息文字(参照转轮,水平居中,在其底部)
addConstraint(NSLayoutConstraint(item: messageLabel1, attribute: .CenterX, relatedBy: .Equal, toItem: iconView, attribute: .CenterX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: messageLabel1, attribute: .Top, relatedBy: .Equal, toItem: iconView, attribute: .Bottom, multiplier: 1.0, constant: 16))
addConstraint(NSLayoutConstraint(item: messageLabel1, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 224))
addConstraint(NSLayoutConstraint(item: messageLabel1, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 36))
//4.注册按钮
addConstraint(NSLayoutConstraint(item: registerButton, attribute: .Right, relatedBy: .Equal, toItem: messageLabel1, attribute: .CenterX, multiplier: 1.0, constant: -30))
addConstraint(NSLayoutConstraint(item: registerButton, attribute: .Top, relatedBy: .Equal, toItem: messageLabel1, attribute: .Bottom, multiplier: 1.0, constant: 16))
addConstraint(NSLayoutConstraint(item: registerButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100))
addConstraint(NSLayoutConstraint(item: registerButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 36))
//5.登陆按钮
addConstraint(NSLayoutConstraint(item: loginButton, attribute: .Left, relatedBy: .Equal, toItem: messageLabel1, attribute: .CenterX, multiplier: 1.0, constant: 30))
addConstraint(NSLayoutConstraint(item: loginButton, attribute: .Top, relatedBy: .Equal, toItem: messageLabel1, attribute: .Bottom, multiplier: 1.0, constant: 16))
addConstraint(NSLayoutConstraint(item: loginButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100))
addConstraint(NSLayoutConstraint(item: loginButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 36))
//6.遮罩
/*
VFL:可视化格式语言
H : 水平方向
V : 垂直方向
| :边界(与方向连用,以确定是哪个方向上的边界)
[] :包装控件
views :是一个字典,[名字:控件名] -VFL 字符串中表示控件字符串(名称是为了知道去设置哪个控件的约束)
metrics:是一个字典,[名字:NSNumber] -VFL 字符串中表示某一个数值
*/
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[mask]-0-|", options:[], metrics:nil, views: ["mask":maskIconView]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[mask]-(btnHeight)-[regbtn]", options:[], metrics:["btnHeight":-36], views: ["mask":maskIconView,"regbtn":registerButton]))
//设置背景颜色,设置灰度图,目前UI元素中大多使用灰度图和纯色图(安全色)
backgroundColor = UIColor(white: 237.0/255.0, alpha: 1.0)
//添加监听方法(代理实现的监听)
// registerButton.addTarget(self, action: "clickRegister", forControlEvents: .TouchUpInside)
// loginButton.addTarget(self, action: "clickLogin", forControlEvents: .TouchUpInside)
}
} | mit | 995e9bc806712f1e198fffeb366ec260 | 40.606557 | 196 | 0.668199 | 3.876273 | false | false | false | false |
jovito-royeca/Cineko | Cineko/MediaInfoTableViewCell.swift | 1 | 1961 | //
// MediaInfoTableViewCell.swift
// Cineko
//
// Created by Jovit Royeca on 11/04/2016.
// Copyright © 2016 Jovito Royeca. All rights reserved.
//
import UIKit
class MediaInfoTableViewCell: UITableViewCell {
// MARK: Outlets
@IBOutlet weak var dateIcon: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var durationIcon: UIImageView!
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var ratingIcon: UIImageView!
@IBOutlet weak var ratingLabel: UILabel!
// MARK: Overrides
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
dateLabel.adjustsFontSizeToFitWidth = true
durationLabel.adjustsFontSizeToFitWidth = true
ratingLabel.adjustsFontSizeToFitWidth = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// MARK: Custom Methods
func changeColor(backgroundColor: UIColor?, fontColor: UIColor?) {
self.backgroundColor = backgroundColor
if let image = dateIcon.image {
let tintedImage = image.imageWithRenderingMode(.AlwaysTemplate)
dateIcon.image = tintedImage
dateIcon.tintColor = fontColor
}
if let image = durationIcon.image {
let tintedImage = image.imageWithRenderingMode(.AlwaysTemplate)
durationIcon.image = tintedImage
durationIcon.tintColor = fontColor
}
if let image = ratingIcon.image {
let tintedImage = image.imageWithRenderingMode(.AlwaysTemplate)
ratingIcon.image = tintedImage
ratingIcon.tintColor = fontColor
}
dateLabel.textColor = fontColor
durationLabel.textColor = fontColor
ratingLabel.textColor = fontColor
}
}
| apache-2.0 | 72252e276b3f01ad08259870942fd0c9 | 30.111111 | 75 | 0.654592 | 5.568182 | false | false | false | false |
shaps80/Peek | Pod/Classes/Peekable/UIBarButtonItem+Peekable.swift | 1 | 2209 | /*
Copyright © 23/04/2016 Shaps
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
extension UIBarButtonItem {
open override func preparePeek(with coordinator: Coordinator) {
var detail = ""
if let model = target as? Peekable {
detail = String(describing: model.classForCoder)
}
var title = ""
if let action = action {
title = String(describing: action)
}
coordinator.appendStatic(keyPath: title, title: title, detail: detail, value: target, in: .actions)
coordinator.appendDynamic(keyPaths: [
"title",
"image",
"landscapeImagePhone"
], forModel: self, in: .appearance)
coordinator.appendDynamic(keyPaths: [
"tag"
], forModel: self, in: .general)
coordinator.appendDynamic(keyPaths: [
"imageInsets",
"landscapeImagePhoneInsets"
], forModel: self, in: .layout)
coordinator.appendDynamic(keyPaths: ["enabled"], forModel: self, in: .behaviour)
super.preparePeek(with: coordinator)
}
}
| mit | 005e3e583c186f6f732b5516d0b36b13 | 34.612903 | 107 | 0.662138 | 4.906667 | false | false | false | false |
abertelrud/swift-package-manager | Sources/SPMTestSupport/MockTarget.swift | 2 | 2648 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import PackageModel
public struct MockTarget {
public enum `Type` {
case regular, test, binary
}
public let name: String
public let dependencies: [TargetDescription.Dependency]
public let path: String?
public let url: String?
public let checksum: String?
public let settings: [TargetBuildSettingDescription.Setting]
public let type: Type
public init(
name: String,
dependencies: [TargetDescription.Dependency] = [],
type: Type = .regular,
path: String? = nil,
url: String? = nil,
settings: [TargetBuildSettingDescription.Setting] = [],
checksum: String? = nil
) throws {
self.name = name
self.dependencies = dependencies
self.type = type
self.path = path
self.url = url
self.settings = settings
self.checksum = checksum
}
func convert() throws -> TargetDescription {
switch self.type {
case .regular:
return try TargetDescription(
name: self.name,
dependencies: self.dependencies,
path: self.path,
exclude: [],
sources: nil,
publicHeadersPath: nil,
type: .regular,
settings: self.settings
)
case .test:
return try TargetDescription(
name: self.name,
dependencies: self.dependencies,
path: self.path,
exclude: [],
sources: nil,
publicHeadersPath: nil,
type: .test,
settings: self.settings
)
case .binary:
return try TargetDescription(
name: self.name,
dependencies: self.dependencies,
path: self.path,
url: self.url,
exclude: [],
sources: nil,
publicHeadersPath: nil,
type: .binary,
settings: [],
checksum: self.checksum
)
}
}
}
| apache-2.0 | e39779d5e5f48198c0b53d545368a880 | 30.152941 | 80 | 0.506798 | 5.317269 | false | false | false | false |
hirohisa/PageController | PageController/PageController.swift | 1 | 8138 | //
// PageController.swift
// PageController
//
// Created by Hirohisa Kawasaki on 6/24/15.
// Copyright (c) 2015 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
public protocol PageControllerDelegate: class {
func pageController(_ pageController: PageController, didChangeVisibleController visibleViewController: UIViewController, fromViewController: UIViewController?)
}
open class PageController: UIViewController {
open weak var delegate: PageControllerDelegate?
public var menuBar: MenuBar = MenuBar(frame: CGRect.zero)
public var visibleViewController: UIViewController? {
didSet {
if let visibleViewController = visibleViewController {
viewDidScroll()
delegate?.pageController(self, didChangeVisibleController: visibleViewController, fromViewController: oldValue)
}
}
}
public var viewControllers: [UIViewController] = [] {
didSet {
menuBar.items = viewControllers.map { $0.title ?? "" }
}
}
let containerView = ContainerView(frame: CGRect.zero)
open override func viewDidLoad() {
super.viewDidLoad()
configure()
}
/// the top from adjusted content inset with menu bar frame
public var adjustedContentInsetTop: CGFloat {
if #available(iOS 11.0, *) {
return menuBar.frame.height
}
return menuBar.frame.height + (navigationController?.navigationBar.frame.height ?? 0) + UIApplication.shared.statusBarFrame.height
}
/// set frame to MenuBar.frame on viewDidLoad
open var frameForMenuBar: CGRect {
var frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)
if let frameForNavigationBar = navigationController?.navigationBar.frame {
frame.origin.y = frameForNavigationBar.maxY
}
return frame
}
/// set frame to containerView.frame on viewDidLoad
open var frameForScrollView: CGRect {
return CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
}
var frameForLeftContentController: CGRect {
var frame = frameForScrollView
frame.origin.x = 0
return frame
}
var frameForCenterContentController: CGRect {
var frame = frameForScrollView
frame.origin.x = frame.width
return frame
}
var frameForRightContentController: CGRect {
var frame = frameForScrollView
frame.origin.x = frame.width * 2
return frame
}
func configure() {
automaticallyAdjustsScrollViewInsets = false
if #available(iOS 11.0, *) {
containerView.contentInsetAdjustmentBehavior = .never
}
containerView.frame = view.bounds
containerView.contentSize = CGSize(width: containerView.frame.width * 3, height: containerView.frame.height)
view.addSubview(containerView)
menuBar.frame = frameForMenuBar
view.addSubview(menuBar)
containerView.controller = self
menuBar.controller = self
reloadPages(at: 0)
containerView.contentOffset = frameForCenterContentController.origin
}
public func reloadPages(at index: Int) {
// print("Function: \(#function), line: \(#line), index: \(index) ")
for viewController in children {
if viewController != viewControllers[index] {
hideViewController(viewController)
}
}
loadPages(at: index)
}
public func switchPage(AtIndex index: Int) {
if containerView.isDragging {
return
}
guard let viewController = viewControllerForCurrentPage() else { return }
let currentIndex = NSArray(array: viewControllers).index(of: viewController)
if currentIndex != index {
reloadPages(at: index)
}
}
func loadPages() {
if let viewController = viewControllerForCurrentPage() {
let index = NSArray(array: viewControllers).index(of: viewController)
loadPages(at: index)
}
}
func loadPages(at index: Int) {
// print("Function: \(#function), index: \(index)")
if index >= viewControllers.count { return }
let visibleViewController = viewControllers[index]
switchVisibleViewController(visibleViewController)
// offsetX < 0 or offsetX > contentSize.width
let frameOfContentSize = CGRect(x: 0, y: 0, width: containerView.contentSize.width, height: containerView.contentSize.height)
for viewController in children {
if viewController != visibleViewController && !viewController.view.include(frameOfContentSize) {
hideViewController(viewController)
}
}
// center
displayViewController(visibleViewController, frame: frameForCenterContentController)
// left
var exists = children.filter { $0.view.include(frameForLeftContentController) }
if exists.isEmpty {
displayViewController(viewControllers[(index - 1).relative(viewControllers.count)], frame: frameForLeftContentController)
}
// right
exists = children.filter { $0.view.include(frameForRightContentController) }
if exists.isEmpty {
displayViewController(viewControllers[(index + 1).relative(viewControllers.count)], frame: frameForRightContentController)
}
}
func switchVisibleViewController(_ viewController: UIViewController) {
if visibleViewController != viewController {
visibleViewController = viewController
}
}
typealias Page = (from: Int, to: Int)
func getPage() -> Page? {
guard let visibleViewController = visibleViewController, let viewController = viewControllerForCurrentPage() else { return nil }
let from = NSArray(array: viewControllers).index(of: visibleViewController)
let to = NSArray(array: viewControllers).index(of: viewController)
return Page(from: from, to: to)
}
func viewDidScroll() {
guard let page = getPage() else { return }
if page.from != page.to {
move(page: page)
return
}
if !containerView.isTracking || !containerView.isDragging {
return
}
if page.from == page.to {
revert(page: page)
}
}
func viewDidEndDecelerating() {
guard let page = getPage(), !containerView.isDragging else { return }
revert(page: page)
}
func revert(page: Page) {
menuBar.revert(to: page.to)
}
func move(page: Page) {
let width = containerView.frame.width
if containerView.contentOffset.x > width * 1.5 {
menuBar.move(from: page.from, until: page.to)
} else if containerView.contentOffset.x < width * 0.5 {
menuBar.move(from: page.from, until: page.to)
}
}
func displayViewController(_ viewController: UIViewController, frame: CGRect) {
guard !children.contains(viewController), !viewController.view.isDescendant(of: containerView) else {
// already added
viewController.view.frame = frame
return
}
viewController.willMove(toParent: self)
addChild(viewController)
viewController.view.frame = frame
containerView.addSubview(viewController.view)
viewController.didMove(toParent: self)
}
func hideViewController(_ viewController: UIViewController) {
guard children.contains(viewController), viewController.view.isDescendant(of: containerView) else { return }
viewController.willMove(toParent: nil)
viewController.view.removeFromSuperview()
viewController.removeFromParent()
viewController.didMove(toParent: nil)
}
}
extension PageController: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
viewDidScroll()
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
viewDidEndDecelerating()
}
}
| mit | 1bc97a51abd7d3efd0794a5022c82961 | 32.908333 | 164 | 0.65102 | 5.18014 | false | false | false | false |
tomasharkema/HoelangTotTrein.iOS | HoelangTotTrein/Dictionary.swift | 1 | 1307 | //
// Dictionary.swift
// HoelangTotTrein
//
// Created by Tomas Harkema on 15-02-15.
// Copyright (c) 2015 Tomas Harkema. All rights reserved.
//
import Foundation
extension Dictionary {
func mapKeys<U> (transform: Key -> U) -> Array<U> {
var results: Array<U> = []
for k in self.keys {
results.append(transform(k))
}
return results
}
func mapValues<U> (transform: Value -> U) -> Array<U> {
var results: Array<U> = []
for v in self.values {
results.append(transform(v))
}
return results
}
func map<U> (transform: Value -> U) -> Array<U> {
return self.mapValues(transform)
}
func map<U> (transform: (Key, Value) -> U) -> Array<U> {
var results: Array<U> = []
for k in self.keys {
results.append(transform(k as Key, self[ k ]! as Value))
}
return results
}
func map<K: Hashable, V> (transform: (Key, Value) -> (K, V)) -> Dictionary<K, V> {
var results: Dictionary<K, V> = [:]
for k in self.keys {
if let value = self[ k ] {
let (u, w) = transform(k, value)
results.updateValue(w, forKey: u)
}
}
return results
}
}
| apache-2.0 | 7e388ede89ee4b492bcdd799ace11b84 | 25.14 | 86 | 0.510329 | 3.630556 | false | false | false | false |
openium/SwiftiumKit | Sources/SwiftiumKit/Additions/Foundation/StringExtensions.swift | 1 | 9548 | //
// String+SKAdditions.swift
// SwiftiumKit
//
// Created by Richard Bergoin on 10/03/16.
// Copyright © 2016 Openium. All rights reserved.
//
import Foundation
import CommonCrypto
// MARK: Hashes
private typealias SKCryptoFunctionPointer = (UnsafeRawPointer?, CC_LONG, UnsafeMutablePointer<UInt8>?) -> UnsafeMutablePointer<UInt8>?
private enum CryptoAlgorithm {
case md5, sha1, sha224, sha256, sha384, sha512
var cryptoFunction: SKCryptoFunctionPointer {
var result: SKCryptoFunctionPointer
switch self {
case .md5: result = CC_MD5
case .sha1: result = CC_SHA1
case .sha224: result = CC_SHA224
case .sha256: result = CC_SHA256
case .sha384: result = CC_SHA384
case .sha512: result = CC_SHA512
}
return result
}
var digestLength: Int {
var length: Int32
switch self {
case .md5: length = CC_MD5_DIGEST_LENGTH
case .sha1: length = CC_SHA1_DIGEST_LENGTH
case .sha224: length = CC_SHA224_DIGEST_LENGTH
case .sha256: length = CC_SHA256_DIGEST_LENGTH
case .sha384: length = CC_SHA384_DIGEST_LENGTH
case .sha512: length = CC_SHA512_DIGEST_LENGTH
}
return Int(length)
}
}
extension String.UTF8View {
var md5: Data {
return self.hashUsingAlgorithm(.md5)
}
var sha1: Data {
return self.hashUsingAlgorithm(.sha1)
}
var sha224: Data {
return self.hashUsingAlgorithm(.sha224)
}
var sha256: Data {
return self.hashUsingAlgorithm(.sha256)
}
var sha384: Data {
return self.hashUsingAlgorithm(.sha384)
}
var sha512: Data {
return self.hashUsingAlgorithm(.sha512)
}
fileprivate func hashUsingAlgorithm(_ algorithm: CryptoAlgorithm) -> Data {
let cryptoFunction = algorithm.cryptoFunction
let length = algorithm.digestLength
return self.hash(cryptoFunction, length: length)
}
fileprivate func hash(_ cryptoFunction: SKCryptoFunctionPointer, length: Int) -> Data {
let hashBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
//defer { hashBytes.dealloc(length) }
_ = cryptoFunction(Array<UInt8>(self), UInt32(self.count), hashBytes)
return Data(bytesNoCopy: UnsafeMutablePointer<UInt8>(hashBytes), count: length, deallocator: .free)
}
}
extension String {
public var md5HashData: Data {
return self.utf8.md5
}
/// Converts string UTF8 data to MD5 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing MD5 hash
public var md5: String {
return self.md5HashData.base16EncodedString()
}
public var sha1HashData: Data {
return self.utf8.sha1
}
/// Converts string UTF8 data to SHA1 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing SHA1 hash
public var sha1: String {
return self.sha1HashData.base16EncodedString()
}
public var sha224HashData: Data {
return self.utf8.sha224
}
/// Converts string UTF8 data to SHA224 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing SHA224 hash
public var sha224: String {
return self.sha224HashData.base16EncodedString()
}
public var sha256HashData: Data {
return self.utf8.sha256
}
/// Converts string UTF8 data to SHA256 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing SHA256 hash
public var sha256: String {
return self.sha256HashData.base16EncodedString()
}
public var sha384HashData: Data {
return self.utf8.sha384
}
/// Converts string UTF8 data to SHA384 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing SHA384 hash
public var sha384: String {
return self.sha384HashData.base16EncodedString()
}
public var sha512HashData: Data {
return self.utf8.sha512
}
/// Converts string UTF8 data to SHA512 checksum (lowercase hexadecimal)
/// :returns: lowercase hexadecimal string containing SHA512 hash
public var sha512: String {
return self.sha512HashData.base16EncodedString()
}
public func hmacSha1(_ key: String) -> String {
let keyData = Array<UInt8>(key.utf8)
let length = Int(20)
let hashBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
//defer { hashBytes.dealloc(length) }
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), keyData, key.utf8.count, Array<UInt8>(self.utf8), self.utf8.count, hashBytes)
//sk_crypto_hmac_sha1(Array<UInt8>(self.utf8), UInt32(self.utf8.count), keyData, UInt32(key.utf8.count), hashBytes)
let data = Data(bytesNoCopy: UnsafeMutablePointer<UInt8>(hashBytes), count: length, deallocator: .free)
return data.base16EncodedString()
}
/**
Int subscript to String
Usage example :
````
var somestring = "some string"
let substring = somestring[3]
let substringNegativeIndex = somestring[-1]
````
- Parameter i: index of the string
- Returns: a String containing the character at position i or nil if index is out of string bounds
*/
public subscript(i: Int) -> String? {
get {
guard i >= -count && i < count else { return nil }
let charIndex: Index
if i >= 0 {
charIndex = index(startIndex, offsetBy: i)
} else {
charIndex = index(startIndex, offsetBy: count + i)
}
return String(self[charIndex])
}
set(newValue) {
guard i >= 0 && i < count else {
preconditionFailure("String subscript can only be used if the condition (index >= 0 && index < count) is fulfilled")
}
guard newValue != nil else {
preconditionFailure("String replacement should not be nil")
}
let lowerIndex = index(startIndex, offsetBy: i, limitedBy: endIndex)!
let upperIndex = index(startIndex, offsetBy: i + 1, limitedBy: endIndex)!
let range = Range<String.Index>(uncheckedBounds: (lower: lowerIndex, upper: upperIndex))
if !range.isEmpty {
self = self.replacingCharacters(in: range, with: newValue!)
}
}
}
/**
Int closed range subscript to String
Usage example :
````
let somestring = "some string"
let substring = somestring[0..3]
````
- Parameter range: a closed range of the string
- Returns: a substring containing the characters in the specified closed range
*/
public subscript(range: ClosedRange<Int>) -> String {
let maxLowerBound = max(0, range.lowerBound)
let maxSupportedLowerOffset = maxLowerBound
let maxSupportedUpperOffset = range.upperBound - maxLowerBound + 1
let lowerIndex = index(startIndex, offsetBy: maxSupportedLowerOffset, limitedBy: endIndex) ?? endIndex
let upperIndex = index(lowerIndex, offsetBy: maxSupportedUpperOffset, limitedBy: endIndex) ?? endIndex
return String(self[lowerIndex..<upperIndex])
}
/**
Int range subscript to String
Usage example :
````
let somestring = "some string"
let substring = somestring[0..<3]
````
- Parameter range: a range of the string
- Returns: a substring containing the characters in the specified range
*/
public subscript(range: Range<Int>) -> String {
let maxLowerBound = max(0, range.lowerBound)
let maxSupportedLowerOffset = maxLowerBound
let maxSupportedUpperOffset = range.upperBound - maxLowerBound
let lowerIndex = index(startIndex, offsetBy: maxSupportedLowerOffset, limitedBy: endIndex) ?? endIndex
let upperIndex = index(lowerIndex, offsetBy: maxSupportedUpperOffset, limitedBy: endIndex) ?? endIndex
return String(self[lowerIndex..<upperIndex])
}
}
extension String {
public var isEmail: Bool {
let emailRegex = "[_A-Za-z0-9-+]+(?:\\.[_A-Za-z0-9-+]+)*@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
}
public func firstLowercased() -> String {
var firstLowercased = self
if let firstCharLowercased = self[0]?.lowercased() {
firstLowercased[0] = firstCharLowercased
}
return firstLowercased
}
}
extension String {
@discardableResult
public mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) -> Int {
var range: Range<Index>?
var replaced = 0
repeat {
range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..<self.endIndex }, locale: locale)
if let range = range {
self.replaceSubrange(range, with: replacement)
replaced += 1
}
} while range != nil
return replaced
}
}
| apache-2.0 | e5f797e5b751417ecea1b4717a2b93c7 | 32.149306 | 215 | 0.62627 | 4.467478 | false | false | false | false |
allbto/WayThere | ios/WayThere/Pods/Nimble/Nimble/Matchers/BeCloseTo.swift | 81 | 4746 | import Foundation
let DefaultDelta = 0.0001
internal func isCloseTo(actualValue: Double?, expectedValue: Double, delta: Double, failureMessage: FailureMessage) -> Bool {
failureMessage.postfixMessage = "be close to <\(stringify(expectedValue))> (within \(stringify(delta)))"
if actualValue != nil {
failureMessage.actualValue = "<\(stringify(actualValue!))>"
} else {
failureMessage.actualValue = "<nil>"
}
return actualValue != nil && abs(actualValue! - expectedValue) < delta
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(expectedValue: Double, within delta: Double = DefaultDelta) -> NonNilMatcherFunc<Double> {
return NonNilMatcherFunc { actualExpression, failureMessage in
return isCloseTo(actualExpression.evaluate(), expectedValue, delta, failureMessage)
}
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(expectedValue: NMBDoubleConvertible, within delta: Double = DefaultDelta) -> NonNilMatcherFunc<NMBDoubleConvertible> {
return NonNilMatcherFunc { actualExpression, failureMessage in
return isCloseTo(actualExpression.evaluate()?.doubleValue, expectedValue.doubleValue, delta, failureMessage)
}
}
@objc public class NMBObjCBeCloseToMatcher : NMBMatcher {
var _expected: NSNumber
var _delta: CDouble
init(expected: NSNumber, within: CDouble) {
_expected = expected
_delta = within
}
public func matches(actualExpression: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let matcher = NonNilMatcherWrapper(NonNilBasicMatcherWrapper(beCloseTo(self._expected, within: self._delta)))
return matcher.matches(expr, failureMessage: failureMessage)
}
public func doesNotMatch(actualExpression: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let matcher = NonNilMatcherWrapper(NonNilBasicMatcherWrapper(beCloseTo(self._expected, within: self._delta)))
return matcher.doesNotMatch(expr, failureMessage: failureMessage)
}
public var within: (CDouble) -> NMBObjCBeCloseToMatcher {
return ({ delta in
return NMBObjCBeCloseToMatcher(expected: self._expected, within: delta)
})
}
}
extension NMBObjCMatcher {
public class func beCloseToMatcher(expected: NSNumber, within: CDouble) -> NMBObjCBeCloseToMatcher {
return NMBObjCBeCloseToMatcher(expected: expected, within: within)
}
}
public func beCloseTo(expectedValues: [Double], within delta: Double = DefaultDelta) -> NonNilMatcherFunc <[Double]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be close to <\(stringify(expectedValues))> (each within \(stringify(delta)))"
if let actual = actualExpression.evaluate() {
if actual.count != expectedValues.count {
return false
} else {
for (index, actualItem) in enumerate(actual) {
if fabs(actualItem - expectedValues[index]) > delta {
return false
}
}
return true
}
}
return false
}
}
// MARK: - Operators
infix operator ≈ {}
public func ≈(lhs: Expectation<[Double]>, rhs: [Double]) {
lhs.to(beCloseTo(rhs))
}
public func ≈(lhs: Expectation<Double>, rhs: Double) {
lhs.to(beCloseTo(rhs))
}
public func ≈(lhs: Expectation<Double>, rhs: (expected: Double, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
public func ==(lhs: Expectation<Double>, rhs: (expected: Double, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
// make this higher precedence than exponents so the Doubles either end aren't pulled in
// unexpectantly
infix operator ± { precedence 170 }
public func ±(lhs: Double, rhs: Double) -> (expected: Double, delta: Double) {
return (expected: lhs, delta: rhs)
}
| mit | 23fae880b254a5c72e7759a4b9d18dfb | 39.135593 | 140 | 0.684966 | 4.852459 | false | false | false | false |
AnRanScheme/MagiRefresh | MagiRefresh/Classes/MagiRefresh.swift | 3 | 4049 | //
// Magi.swift
// magiLoadingPlaceHolder
//
// Created by 安然 on 2018/8/6.
// Copyright © 2018年 anran. All rights reserved.
//
import UIKit
public class MagiRefresh {
static let MagiHeaderKeyPath = "MagiHeaderKeyPath"
static let MagiFooterKeyPath = "MagiHeaderKeyPath"
public var placeHolder: MagiPlaceHolder? {
didSet {
guard let scrollView = self.scrollView else { return }
for view in scrollView.subviews {
if view.isKind(of: MagiPlaceHolder.self) {
view.removeFromSuperview()
}
}
if let place = placeHolder {
scrollView.addSubview(place)
place.isHidden = true
}
}
}
public var header: MagiRefreshHeaderConrol? {
willSet{
if header != newValue {
guard let scrollView = self.scrollView else { return }
header?.removeFromSuperview()
scrollView.willChangeValue(
forKey: MagiRefresh.MagiHeaderKeyPath)
if let newValue = newValue {
scrollView.addSubview(newValue)
}
scrollView.didChangeValue(
forKey: MagiRefresh.MagiHeaderKeyPath)
}
}
}
public var footer: MagiRefreshFooterConrol? {
willSet{
if footer != newValue {
guard let scrollView = self.scrollView else { return }
footer?.removeFromSuperview()
scrollView.willChangeValue(
forKey: MagiRefresh.MagiFooterKeyPath)
if let newValue = newValue {
scrollView.addSubview(newValue)
}
scrollView.didChangeValue(
forKey: MagiRefresh.MagiFooterKeyPath)
}
}
}
var scrollView: UIScrollView?
// MAKR: - 根据 DataSource 判断是否自动显示 PlaceHolder
public func startLoading() {
placeHolder?.isHidden = true
}
public func endLoading() {
getDataAndSet()
}
public func showPlaceHolder() {
scrollView?.layoutSubviews()
placeHolder?.isHidden = false
if let place = placeHolder {
scrollView?.bringSubviewToFront(place)
}
}
public func hidePlaceHolder() {
placeHolder?.isHidden = true
}
// MARK: - Private Method
fileprivate func totalDataCount() -> NSInteger {
guard let scrollView = self.scrollView else { return 0 }
var totalCount: NSInteger = 0
if scrollView.isKind(of: UITableView.classForCoder()) {
let tableView = scrollView as? UITableView
if let section = tableView?.numberOfSections, section >= 1 {
for index in 0..<section {
totalCount += tableView?.numberOfRows(inSection: index) ?? 0
}
}
}
else if scrollView.isKind(of: UICollectionView.classForCoder()) {
let collectionView = scrollView as? UICollectionView
if let section = collectionView?.numberOfSections, section >= 1 {
for index in 0..<section {
totalCount += collectionView?.numberOfItems(inSection: index) ?? 0
}
}
}
return totalCount
}
public func getDataAndSet() {
guard let _ = placeHolder else { return }
if totalDataCount() == 0 {
show()
}
else {
hide()
}
}
fileprivate func show() {
if placeHolder?.isAutoShowPlaceHolder == false {
placeHolder?.isHidden = true
return
}
showPlaceHolder()
}
fileprivate func hide() {
if placeHolder?.isAutoShowPlaceHolder == false {
placeHolder?.isHidden = true
return
}
hidePlaceHolder()
}
}
| mit | 855eb3ebc0c87aa242b5df9d3f02de42 | 28.573529 | 86 | 0.538041 | 5.617318 | false | false | false | false |
kickstarter/ios-oss | Library/ViewModels/ProjectActivityLaunchCellViewModel.swift | 1 | 1989 | import Foundation
import KsApi
import Prelude
import ReactiveExtensions
import ReactiveSwift
public protocol ProjectActivityLaunchCellViewModelInputs {
/// Call to set the activity and project.
func configureWith(activity: Activity, project: Project)
}
public protocol ProjectActivityLaunchCellViewModelOutputs {
/// Emits the background image URL.
var backgroundImageURL: Signal<URL?, Never> { get }
/// Emits the title of the activity.
var title: Signal<String, Never> { get }
}
public protocol ProjectActivityLaunchCellViewModelType {
var inputs: ProjectActivityLaunchCellViewModelInputs { get }
var outputs: ProjectActivityLaunchCellViewModelOutputs { get }
}
public final class ProjectActivityLaunchCellViewModel: ProjectActivityLaunchCellViewModelType,
ProjectActivityLaunchCellViewModelInputs, ProjectActivityLaunchCellViewModelOutputs {
public init() {
let activityAndProject = self.activityAndProjectProperty.signal.skipNil()
let project = activityAndProject.map(second)
self.backgroundImageURL = project.map { $0.photo.med }.map(URL.init(string:))
self.title = project.map { project in
Strings.dashboard_activity_project_name_launched(
project_name: project.name,
launch_date: Format.date(
secondsInUTC: project.dates.launchedAt,
dateStyle: .long, timeStyle: .none
).nonBreakingSpaced(),
goal: Format.currency(project.stats.goal, country: project.country).nonBreakingSpaced()
)
}
}
fileprivate let activityAndProjectProperty = MutableProperty<(Activity, Project)?>(nil)
public func configureWith(activity: Activity, project: Project) {
self.activityAndProjectProperty.value = (activity, project)
}
public let backgroundImageURL: Signal<URL?, Never>
public let title: Signal<String, Never>
public var inputs: ProjectActivityLaunchCellViewModelInputs { return self }
public var outputs: ProjectActivityLaunchCellViewModelOutputs { return self }
}
| apache-2.0 | bce425f2f80375a7ac71574d77979828 | 35.163636 | 95 | 0.766214 | 4.769784 | false | false | false | false |
kickstarter/ios-oss | Library/CreateBackingConstructorTests.swift | 1 | 6170 | import Foundation
@testable import KsApi
@testable import Library
import Prelude
import XCTest
final class CreateBackingInputConstructorTests: XCTestCase {
func testCreateBackingInput_NoShipping_NotApplePay() {
let project = Project.template
let reward = Reward.noReward
let applePayParams = ApplePayParams(
paymentInstrumentName: "paymentInstrumentName",
paymentNetwork: "paymentNetwork",
transactionIdentifier: "transactionIdentifier",
token: "token"
)
let data = CreateBackingData(
project: project,
rewards: [reward],
pledgeTotal: 10,
selectedQuantities: [reward.id: 1],
shippingRule: nil,
paymentSourceId: UserCreditCards.amex.id,
setupIntentClientSecret: nil,
applePayParams: applePayParams,
refTag: RefTag.projectPage
)
let input = CreateBackingInput.input(from: data, isApplePay: false)
XCTAssertEqual(input.amount, "10.00")
XCTAssertNil(input.applePay)
XCTAssertNil(input.locationId)
XCTAssertEqual(input.projectId, "UHJvamVjdC0x")
XCTAssertEqual(input.rewardIds, ["UmV3YXJkLTA="])
XCTAssertEqual(input.paymentSourceId, "6")
XCTAssertEqual(input.refParam, "project_page")
}
func testCreateBackingInput_WithShipping_RefTagNil_IsApplePay() {
let project = Project.template
let reward = Reward.template
let shippingRule = ShippingRule.template
|> ShippingRule.lens.location .. Location.lens.id .~ 1
|> ShippingRule.lens.cost .~ 5.0
let applePayParams = ApplePayParams(
paymentInstrumentName: "paymentInstrumentName",
paymentNetwork: "paymentNetwork",
transactionIdentifier: "transactionIdentifier",
token: "token"
)
let data: CreateBackingData = (
project: project,
rewards: [reward],
pledgeTotal: 15,
selectedQuantities: [reward.id: 1],
shippingRule: shippingRule,
paymentSourceId: "123",
setupIntentClientSecret: "xyz",
applePayParams: applePayParams,
refTag: nil
)
let input = CreateBackingInput.input(from: data, isApplePay: true)
XCTAssertEqual(input.amount, "15.00")
XCTAssertEqual(input.applePay, applePayParams)
XCTAssertEqual(input.locationId, "1")
XCTAssertEqual(input.projectId, "UHJvamVjdC0x")
XCTAssertEqual(input.rewardIds, ["UmV3YXJkLTE="])
XCTAssertNil(input.paymentSourceId)
XCTAssertNil(input.refParam)
}
func testCreateBackingInput_WithShipping_RefTag_HasAddOns() {
let project = Project.template
let reward = Reward.template
let shippingRule = ShippingRule.template
|> ShippingRule.lens.location .. Location.lens.id .~ 1
|> ShippingRule.lens.cost .~ 5.0
let applePayParams = ApplePayParams(
paymentInstrumentName: "paymentInstrumentName",
paymentNetwork: "paymentNetwork",
transactionIdentifier: "transactionIdentifier",
token: "token"
)
let addOn1 = Reward.template
|> Reward.lens.id .~ 2
let addOn2 = Reward.template
|> Reward.lens.id .~ 3
let data: CreateBackingData = (
project: project,
rewards: [reward, addOn1, addOn2],
pledgeTotal: 15,
selectedQuantities: [reward.id: 1, addOn1.id: 2, addOn2.id: 3],
shippingRule: shippingRule,
paymentSourceId: "123",
setupIntentClientSecret: "xyz",
applePayParams: applePayParams,
refTag: .discovery
)
let input = CreateBackingInput.input(from: data, isApplePay: true)
XCTAssertEqual(input.amount, "15.00")
XCTAssertEqual(input.applePay, applePayParams)
XCTAssertEqual(input.locationId, "1")
XCTAssertEqual(input.projectId, "UHJvamVjdC0x")
XCTAssertEqual(
input.rewardIds,
["UmV3YXJkLTE=", "UmV3YXJkLTI=", "UmV3YXJkLTI=", "UmV3YXJkLTM=", "UmV3YXJkLTM=", "UmV3YXJkLTM="]
)
XCTAssertNil(input.paymentSourceId)
XCTAssertEqual(input.refParam, "discovery")
}
func testCreateBackingInput_WithApplePay_AndPaymentSource_AndSetupIntentClientSecret_OnlyApplePayIsValid_Success() {
let applePayParams = ApplePayParams(
paymentInstrumentName: "paymentInstrumentName",
paymentNetwork: "paymentNetwork",
transactionIdentifier: "transactionIdentifier",
token: "token"
)
let data: CreateBackingData = (
project: .template,
rewards: [.noReward],
pledgeTotal: 10,
selectedQuantities: [Reward.noReward.id: 1],
shippingRule: nil,
paymentSourceId: UserCreditCards.amex.id,
setupIntentClientSecret: "xyz",
applePayParams: applePayParams,
refTag: RefTag.projectPage
)
let input = CreateBackingInput.input(from: data, isApplePay: true)
XCTAssertNotNil(input.applePay)
XCTAssertNil(input.paymentSourceId)
XCTAssertNil(input.setupIntentClientSecret)
}
func testCreateBackingInput_WithNoApplePay_AndPaymentSource_AndSetupIntentClientSecret_OnlyPaymentSourceIsValid_Success() {
let data: CreateBackingData = (
project: .template,
rewards: [.noReward],
pledgeTotal: 10,
selectedQuantities: [Reward.noReward.id: 1],
shippingRule: nil,
paymentSourceId: UserCreditCards.amex.id,
setupIntentClientSecret: nil,
applePayParams: nil,
refTag: RefTag.projectPage
)
let input = CreateBackingInput.input(from: data, isApplePay: false)
XCTAssertNil(input.applePay)
XCTAssertEqual(input.paymentSourceId, UserCreditCards.amex.id)
XCTAssertNil(input.setupIntentClientSecret)
}
func testCreateBackingInput_WithNoApplePay_NoPaymentSource_AndSetupIntentClientSecret_OnlySetupIntentClientSecretIsValid_Success() {
let data: CreateBackingData = (
project: .template,
rewards: [.noReward],
pledgeTotal: 10,
selectedQuantities: [Reward.noReward.id: 1],
shippingRule: nil,
paymentSourceId: nil,
setupIntentClientSecret: "xyz",
applePayParams: nil,
refTag: RefTag.projectPage
)
let input = CreateBackingInput.input(from: data, isApplePay: false)
XCTAssertNil(input.applePay)
XCTAssertNil(input.paymentSourceId)
XCTAssertEqual(input.setupIntentClientSecret, "xyz")
}
}
| apache-2.0 | d7e5024de4f7e809699b4c57844d58d9 | 31.473684 | 134 | 0.707293 | 4.266943 | false | true | false | false |
crspybits/SMSyncServer | iOS/iOSTests/Pods/SMSyncServer/SMSyncServer/Classes/Internal/SMServerAPI.swift | 2 | 40569 | //
// SMSyncServer.swift
// NetDb
//
// Created by Christopher Prince on 12/1/15.
// Copyright © 2015 Spastic Muffin, LLC. All rights reserved.
//
// Networking interface to access SyncServer REST API.
// TODO: Can a stale security token from Google Drive be dealt with by doing a silent sign in?
import Foundation
import SMCoreLib
internal struct SMOperationResult {
var status:Int!
var error:String!
var count:Int!
}
internal struct SMServerAPIResult {
var returnCode:Int?
var error: NSError?
internal init() {
}
internal init(returnCode:Int?, error:NSError?) {
self.error = error
self.returnCode = returnCode
}
}
// Describes a file that is present on the local and/or remote systems.
// This inherits from NSObject so I can use the .copy() method.
internal class SMServerFile : NSObject, NSCopying, NSCoding {
// The permanent identifier for the file on the app and SyncServer.
internal var uuid: NSUUID!
internal var localURL: SMRelativeLocalURL?
// This must be unique across all remote files for the cloud user. (Because currently all remote files are required to be in a single remote directory).
// This optional for the case of transfering files from cloud storage where only a UUID is needed.
internal var remoteFileName:String?
// TODO: Add MD5 hash of file.
// This optional for the case of transfering files from cloud storage where only a UUID is needed.
internal var mimeType:String?
// App-dependent meta data, e.g., so that the app can know, when it downloads a file from the SyncServer, how to process the file. This is optional as the app may or may not want to use it.
internal var appMetaData:SMAppMetaData?
// Files newly uploaded to the server (i.e., their UUID doesn't exist yet there) must have version 0. Updated files must have a version equal to +1 of that on the server currently.
// This optional for the case of transfering files from cloud storage where only a UUID is needed.
internal var version: Int?
// Used when uploading changes to the SyncServer to keep track of the local file meta data.
internal var localFile:SMLocalFile?
// Used in a file index reply from the server to indicate the size of the file stored in cloud storage. (Will not be present in all replies, e.g., in a fileChangesRecovery).
internal var sizeBytes:Int?
// Indicates whether or not the file has been deleted on the server.
internal var deleted:Bool?
// To deal with conflict resolution. Leave this as nil if you don't want undeletion. Set to true if you do want undeletion.
internal var undeleteServerFile:Bool?
private override init() {
}
// Does not initialize localURL.
internal init(uuid fileUUID:NSUUID, remoteFileName fileName:String?=nil, mimeType fileMIMEType:String?=nil, appMetaData:SMAppMetaData?=nil, version fileVersion:Int?=nil) {
self.remoteFileName = fileName
self.uuid = fileUUID
self.version = fileVersion
self.mimeType = fileMIMEType
self.appMetaData = appMetaData
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.uuid, forKey: "uuid")
aCoder.encodeObject(self.localURL, forKey: "localURL")
aCoder.encodeObject(self.remoteFileName, forKey: "remoteFileName")
aCoder.encodeObject(self.mimeType, forKey: "mimeType")
// Since the appMetaData is JSON serializable, it should be encodable, right?
aCoder.encodeObject(self.appMetaData, forKey: "appMetaData")
aCoder.encodeObject(self.version, forKey: "version")
aCoder.encodeObject(self.sizeBytes, forKey: "sizeBytes")
aCoder.encodeObject(self.deleted, forKey: "deleted")
}
required init?(coder aDecoder: NSCoder) {
super.init()
self.uuid = aDecoder.decodeObjectForKey("uuid") as? NSUUID
self.localURL = aDecoder.decodeObjectForKey("localURL") as? SMRelativeLocalURL
self.remoteFileName = aDecoder.decodeObjectForKey("remoteFileName") as? String
self.mimeType = aDecoder.decodeObjectForKey("mimeType") as? String
self.appMetaData = aDecoder.decodeObjectForKey("appMetaData") as? [String:AnyObject]
self.version = aDecoder.decodeObjectForKey("version") as? Int
self.sizeBytes = aDecoder.decodeObjectForKey("sizeBytes") as? Int
self.deleted = aDecoder.decodeObjectForKey("deleted") as? Bool
}
@objc internal func copyWithZone(zone: NSZone) -> AnyObject {
let copy = SMServerFile()
copy.localURL = self.localURL
copy.remoteFileName = self.remoteFileName
copy.uuid = self.uuid
copy.mimeType = self.mimeType
// This is not a deep copy.
copy.appMetaData = self.appMetaData
copy.version = self.version
// Not creating a copy of localFile because it's a CoreData object and a copy doesn't make sense-- it refers to the same persistent object.
copy.localFile = self.localFile
copy.sizeBytes = self.sizeBytes
return copy
}
override internal var description: String {
get {
return "localURL: \(self.localURL); remoteFileName: \(self.remoteFileName); uuid: \(self.uuid); version: \(self.version); mimeType: \(self.mimeType); appFileType: \(self.appMetaData)"
}
}
internal class func create(fromDictionary dict:[String:AnyObject]) -> SMServerFile? {
let props = [SMServerConstants.fileIndexFileId, SMServerConstants.fileIndexFileVersion, SMServerConstants.fileIndexCloudFileName, SMServerConstants.fileIndexMimeType, SMServerConstants.fileIndexDeleted]
// Not including SMServerConstants.fileIndexAppFileType as it's optional
for prop in props {
if (nil == dict[prop]) {
Log.msg("Didn't have key \(prop) in the dict")
return nil
}
}
let newObj = SMServerFile()
if let cloudName = dict[SMServerConstants.fileIndexCloudFileName] as? String {
newObj.remoteFileName = cloudName
}
else {
Log.msg("Didn't get a string for cloudName")
return nil
}
if let uuid = dict[SMServerConstants.fileIndexFileId] as? String {
newObj.uuid = NSUUID(UUIDString: uuid)
}
else {
Log.msg("Didn't get a string for uuid")
return nil
}
newObj.version = SMExtras.getIntFromDictValue(dict[SMServerConstants.fileIndexFileVersion])
if nil == newObj.version {
Log.msg("Didn't get an Int for fileVersion: \(dict[SMServerConstants.fileIndexFileVersion].dynamicType)")
return nil
}
if let mimeType = dict[SMServerConstants.fileIndexMimeType] as? String {
newObj.mimeType = mimeType
}
else {
Log.msg("Didn't get a String for mimeType")
return nil
}
let fileDeleted = SMExtras.getIntFromDictValue(dict[SMServerConstants.fileIndexDeleted])
if nil == fileDeleted {
Log.msg("Didn't get an Int for fileDeleted: \(dict[SMServerConstants.fileIndexDeleted].dynamicType)")
return nil
}
else {
newObj.deleted = Bool(fileDeleted!)
}
if let appMetaData = dict[SMServerConstants.fileIndexAppMetaData] as? SMAppMetaData {
newObj.appMetaData = appMetaData
}
else {
Log.msg("Didn't get JSON for appMetaData")
}
let sizeBytes = SMExtras.getIntFromDictValue(dict[SMServerConstants.fileSizeBytes])
if nil == sizeBytes {
Log.msg("Didn't get an Int for sizeInBytes: \(dict[SMServerConstants.fileSizeBytes].dynamicType)")
}
else {
newObj.sizeBytes = sizeBytes!
}
return newObj
}
// Adds all except for localURL.
internal var dictionary:[String:AnyObject] {
get {
var result = [String:AnyObject]()
result[SMServerConstants.fileUUIDKey] = self.uuid.UUIDString
if self.version != nil {
result[SMServerConstants.fileVersionKey] = self.version
}
if self.remoteFileName != nil {
result[SMServerConstants.cloudFileNameKey] = self.remoteFileName
}
if self.mimeType != nil {
result[SMServerConstants.fileMIMEtypeKey] = self.mimeType
}
if self.appMetaData != nil {
result[SMServerConstants.appMetaDataKey] = self.appMetaData
}
return result
}
}
class func getFile(fromFiles files:[SMServerFile]?, withUUID uuid: NSUUID) -> SMServerFile? {
if nil == files || files?.count == 0 {
return nil
}
let result = files?.filter({$0.uuid.isEqual(uuid)})
if result!.count > 0 {
return result![0]
}
else {
return nil
}
}
}
internal protocol SMServerAPIUploadDelegate : class {
func smServerAPIFileUploaded(serverFile: SMServerFile)
}
internal protocol SMServerAPIDownloadDelegate : class {
func smServerAPIFileDownloaded(file: SMServerFile)
}
// http://stackoverflow.com/questions/24051904/how-do-you-add-a-dictionary-of-items-into-another-dictionary
private func += <KeyType, ValueType> (inout left: Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
internal class SMServerAPI {
internal var serverURL:NSURL!
internal var serverURLString:String {
return serverURL.absoluteString
}
internal static let session = SMServerAPI()
// Design-wise, it seems better to access a user/credentials delegate in the SMServerAPI class instead of letting this class access the SMSyncServerUser directly. This is because the SMSyncServerUser class needs to call the SMServerAPI interface (to sign a user in or create a new user), and such a direct cyclic dependency seems a poor design.
internal weak var userDelegate:SMServerAPIUserDelegate!
internal weak var uploadDelegate: SMServerAPIUploadDelegate?
internal weak var downloadDelegate: SMServerAPIDownloadDelegate?
private init() {
}
//MARK: Authentication/user-sign in
// All credentials parameters must be provided by serverCredentialParams.
internal func createNewUser(serverCredentialParams:[String:AnyObject], completion:((internalUserId:SMInternalUserId?, apiResult:SMServerAPIResult)->(Void))?) {
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationCreateNewUser)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: serverCredentialParams) { (serverResponse:[String:AnyObject]?, error:NSError?) in
var result = self.initialServerResponseProcessing(serverResponse, error: error)
var internalUserId:SMInternalUserId?
if nil == result.error {
internalUserId = serverResponse![SMServerConstants.internalUserId] as? String
if nil == internalUserId {
result.error = Error.Create("Didn't get InternalUserId back from server")
}
}
completion?(internalUserId: internalUserId, apiResult: result)
}
}
// All credentials parameters must be provided by serverCredentialParams.
internal func checkForExistingUser(serverCredentialParams:[String:AnyObject], completion:((internalUserId:String?, apiResult:SMServerAPIResult)->(Void))?) {
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationCheckForExistingUser)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: serverCredentialParams) { (serverResponse:[String:AnyObject]?, error:NSError?) in
var result = self.initialServerResponseProcessing(serverResponse, error: error)
var internalUserId:String?
if nil == result.error {
internalUserId = serverResponse![SMServerConstants.internalUserId] as? String
if nil == internalUserId && SMServerConstants.rcUserOnSystem == result.returnCode {
result.error = Error.Create("Didn't get InternalUserId back from server")
}
}
completion?(internalUserId: internalUserId, apiResult: result)
}
}
//MARK: File operations
internal func lock(completion:((apiResult:SMServerAPIResult)->(Void))?) {
let serverParams = self.userDelegate.userCredentialParams
Assert.If(nil == serverParams, thenPrintThisString: "No user server params!")
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationLock)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: serverParams!) { (serverResponse:[String:AnyObject]?, error:NSError?) in
let result = self.initialServerResponseProcessing(serverResponse, error: error)
completion?(apiResult: result)
}
}
internal func unlock(completion:((apiResult:SMServerAPIResult)->(Void))?) {
let serverParams = self.userDelegate.userCredentialParams
Assert.If(nil == serverParams, thenPrintThisString: "No user server params!")
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationUnlock)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: serverParams!) { (serverResponse:[String:AnyObject]?, error:NSError?) in
let result = self.initialServerResponseProcessing(serverResponse, error: error)
completion?(apiResult: result)
}
}
// You should probably use uploadFiles. This is exposed (i.e., not private) to enable testing.
// fileToUpload must have a localURL.
internal func uploadFile(fileToUpload: SMServerFile, completion:((apiResult:SMServerAPIResult)->(Void))?) {
let serverOpURL = NSURL(string: self.serverURLString + "/" + SMServerConstants.operationUploadFile)!
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
var parameters = userParams!
parameters += fileToUpload.dictionary
if fileToUpload.undeleteServerFile != nil {
Assert.If(fileToUpload.undeleteServerFile! == false, thenPrintThisString: "Yikes: Must give undeleteServerFile as true or nil")
parameters[SMServerConstants.undeleteFileKey] = true
}
SMServerNetworking.session.uploadFileTo(serverOpURL, fileToUpload: fileToUpload.localURL!, withParameters: parameters) { serverResponse, error in
let result = self.initialServerResponseProcessing(serverResponse, error: error)
completion?(apiResult: result)
}
}
// Recursive multiple file upload implementation. If there are no files in the filesToUpload parameter array, this doesn't call the server, and has no effect but calling the completion handler with nil parameters.
internal func uploadFiles(filesToUpload: [SMServerFile]?, completion:((apiResult:SMServerAPIResult)->(Void))?) {
if filesToUpload != nil && filesToUpload!.count >= 1 {
self.uploadFilesAux(filesToUpload!, completion: completion)
}
else {
Log.warning("No files to upload")
completion?(apiResult: SMServerAPIResult(returnCode: nil, error: nil))
}
}
// Assumes we've already validated that there is at least one file to upload.
// TODO: If we get a failure uploading an individual file, retry some MAX number of times.
private func uploadFilesAux(filesToUpload: [SMServerFile], completion:((apiResult:SMServerAPIResult)->(Void))?) {
if filesToUpload.count >= 1 {
let serverFile = filesToUpload[0]
Log.msg("Uploading file: \(serverFile.localURL)")
self.uploadFile(serverFile) { apiResult in
if (nil == apiResult.error) {
self.uploadDelegate?.smServerAPIFileUploaded(serverFile)
let remainingFiles = Array(filesToUpload[1..<filesToUpload.count])
self.uploadFilesAux(remainingFiles, completion: completion)
}
else {
completion?(apiResult: apiResult)
}
}
}
else {
// The base-case of the recursion: All has completed normally, will have nil parameters for completion.
completion?(apiResult: SMServerAPIResult(returnCode: nil, error: nil))
}
}
// Indicates that a group of files in the cloud should be deleted.
// You must have a lock beforehand. This does nothing, but calls the callback if filesToDelete is nil or is empty.
internal func deleteFiles(filesToDelete: [SMServerFile]?, completion:((apiResult:SMServerAPIResult)->(Void))?) {
if filesToDelete == nil || filesToDelete!.count == 0 {
completion?(apiResult: SMServerAPIResult(returnCode: nil, error: nil))
return
}
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationDeleteFiles)!
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
var serverParams = userParams!
var deletionServerParam = [AnyObject]()
for serverFile in filesToDelete! {
let serverFileDict = serverFile.dictionary
deletionServerParam.append(serverFileDict)
}
serverParams[SMServerConstants.filesToDeleteKey] = deletionServerParam
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: serverParams) { (serverResponse:[String:AnyObject]?, error:NSError?) in
let result = self.initialServerResponseProcessing(serverResponse, error: error)
completion?(apiResult: result)
}
}
// You must have obtained a lock beforehand, and uploaded/deleted one file after that.
internal func startOutboundTransfer(completion:((serverOperationId:String?, apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationStartOutboundTransfer)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: userParams!) { (serverResponse:[String:AnyObject]?, error:NSError?) in
var result = self.initialServerResponseProcessing(serverResponse, error: error)
let serverOperationId:String? = serverResponse?[SMServerConstants.resultOperationIdKey] as? String
Log.msg("\(serverOpURL); OperationId: \(serverOperationId)")
if (nil == result.error && nil == serverOperationId) {
result.error = Error.Create("No server operationId obtained")
}
completion?(serverOperationId: serverOperationId, apiResult:result)
}
}
// On success, the returned SMSyncServerFile objects will have nil localURL members.
internal func getFileIndex(requirePreviouslyHeldLock requirePreviouslyHeldLock:Bool=false, completion:((fileIndex:[SMServerFile]?, apiResult:SMServerAPIResult)->(Void))?) {
var params = self.userDelegate.userCredentialParams
Assert.If(nil == params, thenPrintThisString: "No user server params!")
Log.msg("parameters: \(params)")
params![SMServerConstants.requirePreviouslyHeldLockKey] = requirePreviouslyHeldLock
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationGetFileIndex)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: params!) { (serverResponse:[String:AnyObject]?, requestError:NSError?) in
let result = self.initialServerResponseProcessing(serverResponse, error: requestError)
if (result.error != nil) {
completion?(fileIndex: nil, apiResult:result)
return
}
var errorResult:NSError? = nil
let fileIndex = self.processFileIndex(serverResponse, error:&errorResult)
if (nil == fileIndex && nil == errorResult) {
errorResult = Error.Create("No file index was obtained from server")
}
completion?(fileIndex: fileIndex, apiResult:SMServerAPIResult(returnCode: result.returnCode, error: errorResult))
}
}
// If there was just no resultFileIndexKey in the server response, a nil file index is returned and error is nil.
// If the returned file index is not nil, then error will be nil.
private func processFileIndex(
serverResponse:[String:AnyObject]?, inout error:NSError?) -> [SMServerFile]? {
Log.msg("\(serverResponse?[SMServerConstants.resultFileIndexKey])")
var result = [SMServerFile]()
error = nil
if let fileIndex = serverResponse?[SMServerConstants.resultFileIndexKey] {
if let arrayOfDicts = fileIndex as? [[String:AnyObject]] {
for dict in arrayOfDicts {
let newFileMetaData = SMServerFile.create(fromDictionary: dict)
if (nil == newFileMetaData) {
error = Error.Create("Bad file index object!")
return nil
}
result.append(newFileMetaData!)
}
return result
}
else {
error = Error.Create("Did not get array of dicts from server")
return nil
}
}
else {
return nil
}
}
// Call this for an operation that has been successfully committed to see if it has subsequently completed and if it was successful.
// In the completion closure, operationError refers to a possible error in regards to the operation running on the server. The NSError refers to an error in communication with the server checking the operation status. Only when the NSError is nil can the other two completion handler parameters be non-nil. With a nil NSError, operationStatus will be non-nil.
// Does not require a server lock be held before the call.
internal func checkOperationStatus(serverOperationId operationId:String, completion:((operationResult: SMOperationResult?, apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
var parameters = userParams!
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationCheckOperationStatus)!
parameters[SMServerConstants.operationIdKey] = operationId
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: parameters) { (serverResponse:[String:AnyObject]?, requestError:NSError?) in
let result = self.initialServerResponseProcessing(serverResponse, error: requestError)
if (nil == result.error) {
var operationResult = SMOperationResult()
operationResult.status = SMExtras.getIntFromDictValue(serverResponse![SMServerConstants.resultOperationStatusCodeKey])
if nil == operationResult.status {
completion?(operationResult: nil, apiResult:SMServerAPIResult(returnCode: result.returnCode, error: Error.Create("Didn't get an operation status code from server")))
return
}
operationResult.count = SMExtras.getIntFromDictValue(serverResponse![SMServerConstants.resultOperationStatusCountKey])
if nil == operationResult.count {
completion?(operationResult: nil, apiResult:SMServerAPIResult(returnCode: result.returnCode, error: Error.Create("Didn't get an operation status count from server")))
return
}
operationResult.error = serverResponse![SMServerConstants.resultOperationStatusErrorKey] as? String
completion?(operationResult: operationResult, apiResult:result)
}
else {
completion?(operationResult: nil, apiResult:result)
}
}
}
// The Operation Id is not removed by a call to checkOperationStatus because if that method were to fail, the app would not know if the operation failed or succeeded. Use this to remove the Operation Id from the server.
internal func removeOperationId(serverOperationId operationId:String, completion:((apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
var parameters = userParams!
parameters[SMServerConstants.operationIdKey] = operationId
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationRemoveOperationId)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: parameters) { (serverResponse:[String:AnyObject]?, error:NSError?) in
let result = self.initialServerResponseProcessing(serverResponse, error: error)
completion?(apiResult: result)
}
}
// You must have obtained a lock beforehand. The serverOperationId may be returned nil even when there is no error: Just because an operationId has not been generated on the server yet.
internal func getOperationId(completion:((serverOperationId:String?, apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationGetOperationId)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: userParams!) { (serverResponse:[String:AnyObject]?, error:NSError?) in
let result = self.initialServerResponseProcessing(serverResponse, error: error)
let serverOperationId:String? = serverResponse?[SMServerConstants.resultOperationIdKey] as? String
Log.msg("\(serverOpURL); OperationId: \(serverOperationId)")
completion?(serverOperationId: serverOperationId, apiResult:result)
}
}
// You must have the server lock before calling.
// Removes PSOutboundFileChange's, removes the PSLock, and removes the PSOperationId.
// This is useful for cleaning up in the case of an error/failure during an upload/download operation.
internal func cleanup(completion:((apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
Log.msg("parameters: \(userParams)")
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationCleanup)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: userParams!) { (serverResponse:[String:AnyObject]?, error:NSError?) in
let result = self.initialServerResponseProcessing(serverResponse, error: error)
completion?(apiResult: result)
}
}
// Must have server lock.
internal func setupInboundTransfer(filesToTransfer: [SMServerFile], completion:((apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
var serverParams = userParams!
var fileTransferServerParam = [AnyObject]()
for serverFile in filesToTransfer {
let serverFileDict = serverFile.dictionary
fileTransferServerParam.append(serverFileDict)
}
serverParams[SMServerConstants.filesToTransferFromCloudStorageKey] = fileTransferServerParam
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationSetupInboundTransfers)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: serverParams) { (serverResponse:[String:AnyObject]?, requestError:NSError?) in
let result = self.initialServerResponseProcessing(serverResponse, error: requestError)
completion?(apiResult: result)
}
}
// Must have server lock or operationId.
internal func startInboundTransfer(completion:((serverOperationId:String?, apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationStartInboundTransfer)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: userParams!) { (serverResponse:[String:AnyObject]?, requestError:NSError?) in
var result = self.initialServerResponseProcessing(serverResponse, error: requestError)
let serverOperationId:String? = serverResponse?[SMServerConstants.resultOperationIdKey] as? String
Log.msg("\(serverOpURL); OperationId: \(serverOperationId)")
if (nil == result.error && nil == serverOperationId) {
result.error = Error.Create("No server operationId obtained")
}
completion?(serverOperationId: serverOperationId, apiResult:result)
}
}
internal func inboundTransferRecovery(
completion:((serverOperationId:String?, apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
Log.msg("parameters: \(userParams)")
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationInboundTransferRecovery)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: userParams!) { (serverResponse:[String:AnyObject]?, error:NSError?) in
var result = self.initialServerResponseProcessing(serverResponse, error: error)
let serverOperationId:String? = serverResponse?[SMServerConstants.resultOperationIdKey] as? String
Log.msg("\(serverOpURL); OperationId: \(serverOperationId)")
if (nil == result.error && nil == serverOperationId) {
result.error = Error.Create("No server operationId obtained")
}
completion?(serverOperationId:serverOperationId, apiResult: result)
}
}
// Aside from testing, we're only using this method inside of this class. Use downloadFiles() for non-testing.
// File will be downloaded to fileToDownload.localURL (which is required). (No other SMServerFile attributes are required, except, of course for the uuid).
internal func downloadFile(fileToDownload: SMServerFile, completion:((apiResult:SMServerAPIResult)->(Void))?) {
Assert.If(fileToDownload.localURL == nil, thenPrintThisString: "Didn't give localURL with file")
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
var serverParams = userParams!
let serverFileDict = fileToDownload.dictionary
serverParams[SMServerConstants.downloadFileAttributes] = serverFileDict
Log.msg("parameters: \(serverParams)")
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationDownloadFile)!
SMServerNetworking.session.downloadFileFrom(serverOpURL, fileToDownload: fileToDownload.localURL!, withParameters: serverParams) { (serverResponse, error) in
let result = self.initialServerResponseProcessing(serverResponse, error: error)
completion?(apiResult: result)
}
}
// Recursive multiple file download implementation. If there are no files in the filesToDownload parameter array, this doesn't call the server, and has no effect but to give a SMServerAPIResult callback.
internal func downloadFiles(filesToDownload: [SMServerFile], completion:((apiResult:SMServerAPIResult)->(Void))?) {
if filesToDownload.count >= 1 {
self.downloadFilesAux(filesToDownload, completion: completion)
}
else {
Log.warning("No files to download")
completion?(apiResult: SMServerAPIResult(returnCode: nil, error: nil))
}
}
// Assumes we've already validated that there is at least one file to download.
// TODO: If we get a failure download an individual file, retry some MAX number of times.
private func downloadFilesAux(filesToDownload: [SMServerFile], completion:((apiResult:SMServerAPIResult)->(Void))?) {
if filesToDownload.count >= 1 {
let serverFile = filesToDownload[0]
Log.msg("Downloading file: \(serverFile.localURL)")
self.downloadFile(serverFile) { downloadResult in
if (nil == downloadResult.error) {
// I'm going to remove the downloaded file from the server immediately after a successful download. Partly, this is so I don't have to push the call to this SMServerAPI method higher up; partly this is an optimization-- so that we can release temporary file storage on the server more quickly.
self.removeDownloadFile(serverFile) { removeResult in
if removeResult.error == nil {
// 3/26/16; Wait until after the file is removed before reporting the download event. This is because internally, in smServerAPIFileDownloaded, we're removing the file from our list of files to download-- and we want to make sure the file gets removed from the server.
self.downloadDelegate?.smServerAPIFileDownloaded(serverFile)
let remainingFiles = Array(filesToDownload[1..<filesToDownload.count])
self.downloadFilesAux(remainingFiles, completion: completion)
}
else {
completion?(apiResult: removeResult)
}
}
}
else {
completion?(apiResult: downloadResult)
}
}
}
else {
// The base-case of the recursion: All has completed normally, will have nil parameters for completion.
completion?(apiResult: SMServerAPIResult(returnCode: nil, error: nil))
}
}
// Remove the temporary downloadable file from the server. (Doesn't remove the info from the file index).
// I'm not going to expose this method outside of this class-- we'll just do this removal internally, after a download.
private func removeDownloadFile(fileToRemove: SMServerFile, completion:((apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
var serverParams = userParams!
let serverFileDict = fileToRemove.dictionary
serverParams[SMServerConstants.downloadFileAttributes] = serverFileDict
Log.msg("parameters: \(serverParams)")
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationRemoveDownloadFile)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: serverParams) { (serverResponse, error) in
let result = self.initialServerResponseProcessing(serverResponse, error: error)
completion?(apiResult: result)
}
}
// Previously, I had this marked as "private". However, it was convenient to add extensions for additional ServerAPI functionality. This method is not intended for callers outside of the SMServerAPI.
internal func initialServerResponseProcessing(serverResponse:[String:AnyObject]?, error:NSError?) -> SMServerAPIResult {
if let rc = serverResponse?[SMServerConstants.resultCodeKey] as? Int {
if error != nil {
return SMServerAPIResult(returnCode: rc, error: error)
}
switch (rc) {
case SMServerConstants.rcOK:
return SMServerAPIResult(returnCode: rc, error: nil)
default:
var message = "Return code value \(rc): "
switch(rc) {
// 12/12/15; This is a failure of the immediate operation, but in general doesn't necessarily represent an error. E.g., we'll be here if the user already existed on the system when attempting to create a user.
case SMServerConstants.rcStaleUserSecurityInfo:
// In the case of Google API creds, I believe this will kick off a network request to refresh the creds. We might get a second request to refresh quickly following on this (i.e., a second rcStaleUserSecurityInfo from the server) -- because of our recovery attempt. BUT-- we do exponential fallback with the recovery, so perhaps our delays will be enough to let the refresh occur first.
self.userDelegate.refreshUserCredentials()
case SMServerConstants.rcOperationFailed:
message += "Operation failed"
case SMServerConstants.rcUndefinedOperation:
message += "Undefined operation"
default:
message += "Other reason for non-\(SMServerConstants.rcOK) valued return code"
}
Log.msg(message)
return SMServerAPIResult(returnCode: rc, error: Error.Create("An error occurred when doing server operation."))
}
}
else {
return SMServerAPIResult(returnCode: SMServerConstants.rcInternalError, error: Error.Create("Bad return code value: \(serverResponse?[SMServerConstants.resultCodeKey])"))
}
}
}
| gpl-3.0 | b96c1e454f77f84baccb55048e3dbcbb | 47.410501 | 405 | 0.648417 | 5.196362 | false | false | false | false |
gservera/ScheduleKit | ScheduleKit/Views/SCKTextField.swift | 1 | 3696 | /*
* SCKTextField.swift
* ScheduleKit
*
* Created: Guillem Servera on 3/10/2016.
* Copyright: © 2014-2019 Guillem Servera (https://github.com/gservera)
*
* 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 Cocoa
private final class SCKTextFieldCell: NSTextFieldCell {
/// A flag property to track whether the text field is selected or being
/// edited.
private var editingOrSelected = false
fileprivate override func drawingRect(forBounds rect: NSRect) -> NSRect {
var rect = super.drawingRect(forBounds: rect)
if !editingOrSelected {
let size = cellSize(forBounds: rect)
let deltaHeight = rect.height - size.height
if deltaHeight > 0.0 {
rect.size.height -= deltaHeight
rect.origin.y = deltaHeight / 2.0
}
}
return rect
}
override func select(withFrame rect: NSRect, in controlView: NSView,
editor textObj: NSText, delegate: Any?,
start selStart: Int, length selLength: Int) {
let newRect = drawingRect(forBounds: rect)
editingOrSelected = true
super.select(withFrame: newRect, in: controlView, editor: textObj,
delegate: delegate, start: selStart, length: selLength)
editingOrSelected = false
}
override func edit(withFrame rect: NSRect, in controlView: NSView,
editor textObj: NSText, delegate: Any?, event: NSEvent?) {
let newRect = drawingRect(forBounds: rect)
editingOrSelected = true
super.edit(withFrame: newRect, in: controlView, editor: textObj,
delegate: delegate, event: event)
editingOrSelected = false
}
}
/// This class provides a custom NSTextField whose cell renders its string value
/// vertically centered when the actual text is not selected and/or being edited.
internal final class SCKTextField: NSTextField {
override class var cellClass: AnyClass? {
get {
return SCKTextFieldCell.self
}
set {
super.cellClass = newValue
}
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setUpDefaultProperties()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setUpDefaultProperties()
}
/// Sets up the text field default properties.
private func setUpDefaultProperties() {
drawsBackground = false
isEditable = false
isBezeled = false
alignment = .center
font = .systemFont(ofSize: 12.0)
}
}
| mit | eb33f017460f8c510fc1f10e746c4be2 | 36.323232 | 81 | 0.659811 | 4.636136 | false | false | false | false |
apple/swift-corelibs-foundation | Darwin/Foundation-swiftoverlay/NSTextCheckingResult.swift | 1 | 1259 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
//===----------------------------------------------------------------------===//
// TextChecking
//===----------------------------------------------------------------------===//
extension NSTextCheckingResult.CheckingType {
public static var allSystemTypes : NSTextCheckingResult.CheckingType {
return NSTextCheckingResult.CheckingType(rawValue: 0xffffffff)
}
public static var allCustomTypes : NSTextCheckingResult.CheckingType {
return NSTextCheckingResult.CheckingType(rawValue: 0xffffffff << 32)
}
public static var allTypes : NSTextCheckingResult.CheckingType {
return NSTextCheckingResult.CheckingType(rawValue: UInt64.max)
}
}
| apache-2.0 | 5b136dedc360b39895cd7b0af4f73e4f | 39.612903 | 80 | 0.555997 | 6.423469 | false | false | false | false |
apple/swift-corelibs-foundation | Sources/Foundation/NSRange.swift | 1 | 13298 | // 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
//
#if DEPLOYMENT_RUNTIME_SWIFT
@_implementationOnly import CoreFoundation
public struct _NSRange {
public var location: Int
public var length: Int
public init() {
location = 0
length = 0
}
public init(location: Int, length: Int) {
self.location = location
self.length = length
}
}
public typealias NSRange = _NSRange
public typealias NSRangePointer = UnsafeMutablePointer<NSRange>
public func NSMakeRange(_ loc: Int, _ len: Int) -> NSRange {
return NSRange(location: loc, length: len)
}
public func NSMaxRange(_ range: NSRange) -> Int {
return range.location + range.length
}
public func NSLocationInRange(_ loc: Int, _ range: NSRange) -> Bool {
return !(loc < range.location) && (loc - range.location) < range.length
}
public func NSEqualRanges(_ range1: NSRange, _ range2: NSRange) -> Bool {
return range1.location == range2.location && range1.length == range2.length
}
public func NSUnionRange(_ range1: NSRange, _ range2: NSRange) -> NSRange {
let end1 = range1.location + range1.length
let end2 = range2.location + range2.length
let maxend: Int
if end1 > end2 {
maxend = end1
} else {
maxend = end2
}
let minloc: Int
if range1.location < range2.location {
minloc = range1.location
} else {
minloc = range2.location
}
return NSRange(location: minloc, length: maxend - minloc)
}
public func NSIntersectionRange(_ range1: NSRange, _ range2: NSRange) -> NSRange {
let end1 = range1.location + range1.length
let end2 = range2.location + range2.length
let minend: Int
if end1 < end2 {
minend = end1
} else {
minend = end2
}
if range2.location <= range1.location && range1.location < end2 {
return NSRange(location: range1.location, length: minend - range1.location)
} else if range1.location <= range2.location && range2.location < end1 {
return NSRange(location: range2.location, length: minend - range2.location)
}
return NSRange(location: 0, length: 0)
}
public func NSStringFromRange(_ range: NSRange) -> String {
return "{\(range.location), \(range.length)}"
}
public func NSRangeFromString(_ aString: String) -> NSRange {
let emptyRange = NSRange(location: 0, length: 0)
if aString.isEmpty {
// fail early if the string is empty
return emptyRange
}
let scanner = Scanner(string: aString)
let digitSet = CharacterSet.decimalDigits
let _ = scanner.scanUpToCharacters(from: digitSet)
if scanner.isAtEnd {
// fail early if there are no decimal digits
return emptyRange
}
guard let location = scanner.scanInt() else {
return emptyRange
}
let partialRange = NSRange(location: location, length: 0)
if scanner.isAtEnd {
// return early if there are no more characters after the first int in the string
return partialRange
}
let _ = scanner.scanUpToCharacters(from: digitSet)
if scanner.isAtEnd {
// return early if there are no integer characters after the first int in the string
return partialRange
}
guard let length = scanner.scanInt() else {
return partialRange
}
return NSRange(location: location, length: length)
}
#else
@_exported import Foundation // Clang module
#endif
extension NSRange : Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(location)
hasher.combine(length)
}
public static func==(_ lhs: NSRange, _ rhs: NSRange) -> Bool {
return lhs.location == rhs.location && lhs.length == rhs.length
}
}
extension NSRange : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String { return "{\(location), \(length)}" }
public var debugDescription: String {
guard location != NSNotFound else {
return "{NSNotFound, \(length)}"
}
return "{\(location), \(length)}"
}
}
extension NSRange {
public init?(_ string: String) {
var savedLocation = 0
if string.isEmpty {
// fail early if the string is empty
return nil
}
let scanner = Scanner(string: string)
let digitSet = CharacterSet.decimalDigits
let _ = scanner.scanUpToCharacters(from: digitSet)
if scanner.isAtEnd {
// fail early if there are no decimal digits
return nil
}
var location = 0
savedLocation = scanner.scanLocation
guard scanner.scanInt(&location) else {
return nil
}
if scanner.isAtEnd {
// return early if there are no more characters after the first int in the string
return nil
}
if scanner.scanString(".") != nil {
scanner.scanLocation = savedLocation
var double = 0.0
guard scanner.scanDouble(&double) else {
return nil
}
guard let integral = Int(exactly: double) else {
return nil
}
location = integral
}
let _ = scanner.scanUpToCharacters(from: digitSet)
if scanner.isAtEnd {
// return early if there are no integer characters after the first int in the string
return nil
}
var length = 0
savedLocation = scanner.scanLocation
guard scanner.scanInt(&length) else {
return nil
}
if !scanner.isAtEnd {
if scanner.scanString(".") != nil {
scanner.scanLocation = savedLocation
var double = 0.0
guard scanner.scanDouble(&double) else {
return nil
}
guard let integral = Int(exactly: double) else {
return nil
}
length = integral
}
}
self.location = location
self.length = length
}
}
extension NSRange {
public var lowerBound: Int { return location }
public var upperBound: Int { return location + length }
public func contains(_ index: Int) -> Bool { return (!(index < location) && (index - location) < length) }
public mutating func formUnion(_ other: NSRange) {
self = union(other)
}
public func union(_ other: NSRange) -> NSRange {
let end1 = location + length
let end2 = other.location + other.length
let maxend = (end1 < end2) ? end2 : end1
let minloc = location < other.location ? location : other.location
return NSRange(location: minloc, length: maxend - minloc)
}
public func intersection(_ other: NSRange) -> NSRange? {
let end1 = location + length
let end2 = other.location + other.length
let minend = (end1 < end2) ? end1 : end2
if other.location <= location && location < end2 {
return NSRange(location: location, length: minend - location)
} else if location <= other.location && other.location < end1 {
return NSRange(location: other.location, length: minend - other.location);
}
return nil
}
}
//===----------------------------------------------------------------------===//
// Ranges
//===----------------------------------------------------------------------===//
extension NSRange {
public init<R: RangeExpression>(_ region: R)
where R.Bound: FixedWidthInteger {
let r = region.relative(to: 0..<R.Bound.max)
location = numericCast(r.lowerBound)
length = numericCast(r.count)
}
public init<R: RangeExpression, S: StringProtocol>(_ region: R, in target: S)
where R.Bound == S.Index {
let r = region.relative(to: target)
self.init(target._toUTF16Offsets(r))
}
@available(swift, deprecated: 4, renamed: "Range.init(_:)")
public func toRange() -> Range<Int>? {
if location == NSNotFound { return nil }
return location..<(location+length)
}
}
extension Range where Bound: BinaryInteger {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (numericCast(range.lowerBound), numericCast(range.upperBound)))
}
}
// This additional overload will mean Range.init(_:) defaults to Range<Int> when
// no additional type context is provided:
extension Range where Bound == Int {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (range.lowerBound, range.upperBound))
}
}
extension Range where Bound == String.Index {
public init?(_ range: NSRange, in string: String) {
let u = string.utf16
guard range.location != NSNotFound,
let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex),
let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex),
let lowerBound = String.Index(start, within: string),
let upperBound = String.Index(end, within: string)
else { return nil }
self = lowerBound..<upperBound
}
}
extension NSRange : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: ["location": location, "length": length])
}
}
extension NSRange : CustomPlaygroundDisplayConvertible {
public var playgroundDescription: Any {
return (Int64(location), Int64(length))
}
}
extension NSRange : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let location = try container.decode(Int.self)
let length = try container.decode(Int.self)
self.init(location: location, length: length)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(self.location)
try container.encode(self.length)
}
}
#if DEPLOYMENT_RUNTIME_SWIFT
extension NSRange {
internal init(_ range: CFRange) {
location = range.location == kCFNotFound ? NSNotFound : range.location
length = range.length
}
}
extension CFRange {
internal init(_ range: NSRange) {
let _location = range.location == NSNotFound ? kCFNotFound : range.location
self.init(location: _location, length: range.length)
}
}
extension NSRange {
public init(_ x: Range<Int>) {
location = x.lowerBound
length = x.count
}
}
extension NSRange: NSSpecialValueCoding {
init(bytes: UnsafeRawPointer) {
self.location = bytes.load(as: Int.self)
self.length = bytes.load(fromByteOffset: MemoryLayout<Int>.stride, as: Int.self)
}
init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if let location = aDecoder.decodeObject(of: NSNumber.self, forKey: "NS.rangeval.location") {
self.location = location.intValue
} else {
self.location = 0
}
if let length = aDecoder.decodeObject(of: NSNumber.self, forKey: "NS.rangeval.length") {
self.length = length.intValue
} else {
self.length = 0
}
}
func encodeWithCoder(_ aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(NSNumber(value: self.location), forKey: "NS.rangeval.location")
aCoder.encode(NSNumber(value: self.length), forKey: "NS.rangeval.length")
}
static func objCType() -> String {
#if arch(i386) || arch(arm) || arch(wasm32)
return "{_NSRange=II}"
#elseif arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
return "{_NSRange=QQ}"
#else
#error("This architecture isn't known. Add it to the 32-bit or 64-bit line.")
#endif
}
func getValue(_ value: UnsafeMutableRawPointer) {
value.initializeMemory(as: NSRange.self, repeating: self, count: 1)
}
func isEqual(_ aValue: Any) -> Bool {
if let other = aValue as? NSRange {
return other.location == self.location && other.length == self.length
} else {
return false
}
}
}
extension NSValue {
public convenience init(range: NSRange) {
self.init()
self._concreteValue = NSSpecialValue(range)
}
public var rangeValue: NSRange {
let specialValue = self._concreteValue as! NSSpecialValue
return specialValue._value as! NSRange
}
}
#endif
| apache-2.0 | 5e1c39fbcadf837376dfa358aa127b73 | 31.043373 | 110 | 0.607836 | 4.507797 | false | false | false | false |
nathawes/swift | test/Driver/Dependencies/fail-with-bad-deps-fine.swift | 1 | 3087 | /// main ==> depends-on-main | bad ==> depends-on-bad
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: Handled main.swift
// CHECK-FIRST: Handled bad.swift
// CHECK-FIRST: Handled depends-on-main.swift
// CHECK-FIRST: Handled depends-on-bad.swift
// Reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/*.swiftdeps %t
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-NONE %s
// CHECK-NONE-NOT: Handled
// Reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/*.swiftdeps %t
// RUN: touch -t 201401240006 %t/bad.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-BUILD-ALL %s
// CHECK-BUILD-ALL-NOT: warning
// CHECK-BUILD-ALL: Handled bad.swift
// CHECK-BUILD-ALL-DAG: Handled main.swift
// CHECK-BUILD-ALL-DAG: Handled depends-on-main.swift
// CHECK-BUILD-ALL-DAG: Handled depends-on-bad.swift
// Reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/*.swiftdeps %t
// RUN: touch -t 201401240007 %t/bad.swift %t/main.swift
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-WITH-FAIL %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps
// CHECK-WITH-FAIL: Handled main.swift
// CHECK-WITH-FAIL-NOT: Handled depends
// CHECK-WITH-FAIL: Handled bad.swift
// CHECK-WITH-FAIL-NOT: Handled depends
// CHECK-RECORD-DAG: "./bad.swift": !private [
// CHECK-RECORD-DAG: "./main.swift": [
// CHECK-RECORD-DAG: "./depends-on-main.swift": !private [
// CHECK-RECORD-DAG: "./depends-on-bad.swift": [
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental ./bad.swift ./main.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-BUILD-ALL %s
| apache-2.0 | aae53aff9196927993bda8d468abb7f3 | 60.74 | 338 | 0.708779 | 2.988383 | false | false | false | false |
nazarcybulskij/scituner | SciTuner/MicSource.swift | 3 | 2870 | //
// MicSource.swift
// oscituner
//
// Created by Denis Kreshikhin on 28.12.14.
// Copyright (c) 2014 Denis Kreshikhin. All rights reserved.
//
// https://developer.apple.com/library/ios/documentation/MusicAudio/Conceptual/AudioQueueProgrammingGuide/AQRecord/RecordingAudio.html#//apple_ref/doc/uid/TP40005343-CH4-SW24
import Foundation
import AVFoundation
class MicSource{
var aqData = AQRecorderState_create()
var sleep: Bool = true
var onData: (() -> ()) = { () -> () in
}
var frequency: Double = 0
var frequency1: Double = 400.625565
var frequency2: Double = 0.05
var frequencyDeviation: Double = 50.0
var discreteFrequency: Double = 44100
var t: Double = 0
var sample = [Double](count: 2205, repeatedValue: 0)
var preview = [Double](count: Int(PREVIEW_LENGTH), repeatedValue: 0)
let sampleRate: Double
let sampleCount: Int
init(sampleRate: Double, sampleCount: Int) {
self.sampleRate = sampleRate
self.sampleCount = sampleCount
}
func activate(){
if !sleep {
return
}
var err: NSError?;
var session = AVAudioSession.sharedInstance()
session.setPreferredSampleRate(44100, error: nil)
session.setPreferredInputNumberOfChannels(1, error: nil)
session.setPreferredOutputNumberOfChannels(1, error: nil)
if !session.setActive(true, error: &err) {
NSLog("can't activate session %@ ", err!)
}
if !session.setCategory(AVAudioSessionCategoryRecord, error: &err) {
NSLog("It can't set category, because %@ ", err!)
}
if !session.setMode(AVAudioSessionModeMeasurement, error: &err) {
NSLog("It can't set mode, because %@ ", err!)
}
AQRecorderState_init(aqData, sampleRate, size_t(sampleCount))
self.discreteFrequency = Double(sampleRate)
sample = [Double](count: sampleCount, repeatedValue: 0)
var interval = Double(sample.count) / discreteFrequency
let timer = NSTimer(timeInterval: interval, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
sleep = false;
}
func inactivate(){
if sleep {
return
}
AQRecorderState_deinit(aqData);
sleep = true;
}
deinit{
AQRecorderState_destroy(aqData);
}
@objc func update(){
if(sleep) {
return
}
AQRecorderState_get_samples(self.aqData, &sample, size_t(sample.count))
AQRecorderState_get_preview(self.aqData, &preview, size_t(preview.count))
onData()
}
}
| mit | 3836377ab4aa61d80ac12e14827d8f0c | 27.989899 | 174 | 0.602787 | 4.355083 | false | false | false | false |
wangyun-hero/sinaweibo-with-swift | sinaweibo/Classes/View/Home/View/WYStatusToolBar.swift | 1 | 3390 | //
// WYStatusToolBar.swift
// sinaweibo
//
// Created by 王云 on 16/9/3.
// Copyright © 2016年 王云. All rights reserved.
//
import UIKit
class WYStatusToolBar: UIView {
var retweetButton: UIButton!
var commentButton: UIButton!
var unlikeButton: UIButton!
var statusViewModel : WYStatusViewModel? {
didSet {
// 设置三个按钮的数据
retweetButton.setTitle(statusViewModel?.reposts_count, for: UIControlState.normal)
commentButton.setTitle(statusViewModel?.comments_count, for: UIControlState.normal)
unlikeButton.setTitle(statusViewModel?.attitudes_count, for: UIControlState.normal)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI () {
//添加三个按钮
retweetButton = addChildButton(imageName: "timeline_icon_retweet", defaultTitle: "转发")
commentButton = addChildButton(imageName: "timeline_icon_comment", defaultTitle: "评论")
unlikeButton = addChildButton(imageName: "timeline_icon_unlike", defaultTitle: "赞")
//添加两条线
let sp1 = UIImageView(image: #imageLiteral(resourceName: "timeline_card_bottom_line"))
let sp2 = UIImageView(image: #imageLiteral(resourceName: "timeline_card_bottom_line"))
addSubview(sp1);addSubview(sp2)
//约束
retweetButton.snp_makeConstraints { (make) -> Void in
make.left.top.bottom.equalTo(self)
make.width.equalTo(commentButton.snp_width)
}
commentButton.snp_makeConstraints { (make) in
make.left.equalTo(retweetButton.snp_right)
make.top.bottom.equalTo(retweetButton)
make.width.equalTo(unlikeButton.snp_width)
}
unlikeButton.snp_makeConstraints { (make) in
make.right.top.bottom.equalTo(self)
make.left.equalTo(commentButton.snp_right)
make.width.equalTo(retweetButton.snp_width)
}
sp1.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(retweetButton.snp_right)
make.centerY.equalTo(retweetButton)
}
sp2.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(commentButton.snp_right)
make.centerY.equalTo(commentButton)
}
}
func addChildButton (imageName:String,defaultTitle:String) -> UIButton {
//创建btn
let btn = UIButton()
// 设置背景图片
btn.setBackgroundImage(UIImage(named:"timeline_card_bottom_background"), for: .normal)
btn.setBackgroundImage(UIImage(named:"timeline_card_bottom_background_highlighted"), for: .highlighted)
//设置左边显示的图标
btn.setImage(UIImage(named:imageName), for: .normal)
//设置标题
btn.setTitle(defaultTitle, for: .normal)
//设置颜色
btn.setTitleColor(UIColor.darkGray, for: .normal)
//设置字号
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//添加到视图上
addSubview(btn)
return btn
}
}
| mit | c53b649ba7488dd5f006a204c7731eb8 | 30 | 111 | 0.612596 | 4.440655 | false | false | false | false |
rubnsbarbosa/swift | startPlayground.playground/Contents.swift | 1 | 7273 | //: Playground - noun: a place where people can play
import UIKit
// Constantes
let name = "Rubens"
let pi = 3.1415927
// Because name is a constant, you can`t give a new value after assigning it.
// For example, the following code won`t compile.
//name = "Barbosa"
print(name)
print("Pi: \(pi)")
// Variables
var age = 25
print(age)
// Because age is a variable, you can assign a new value in later lines of code.
// The following code compiles with no erros.
age = 26
print(age) // This code would print 26 to the console.
// You can assign constants and variables from other constants and variables.
let dafaultScore = 10
var playerOne = dafaultScore
var playerTwo = dafaultScore
print(playerOne)
print(playerTwo)
playerOne = 20
print(playerOne)
// Type Definition, and it defines the properties and functions of a Person type
struct Person {
// You can see there are two String values, firstName and lastName.
// These are called properties, which store information about the person.
let firstName: String
let lastName: String
var age: Int
// You also see sayHello(), which is a function and defines an action for the person.
func sayHello() {
print("Hello there! My name is \(firstName) \(lastName) is \(age) years old.")
}
}
// Whenever you create a new variable, you`re creating an instance of a type. Consider the following code.
let personOne = Person(firstName: "Rubens", lastName: "Barbosa", age: 26)
let personTwo = Person(firstName: "Gabriel", lastName: "Barbosa", age: 20)
print(personOne)
print(personOne.firstName)
print(personOne.lastName)
print(personOne.age)
// This code creates two instances of the Person type.
// One instance represents a Person named Rubens, and the other instance represents a person named Gabriel
personOne.sayHello()
personTwo.sayHello()
/*
Here are a few of the most common types in Swift.
Int -> represents whole numbers, of integers.
Double -> represents numbers requiring decimal points.
Bool -> represents true or false values.
String -> represents text.
*/
// Type inference: specify the type of value when you declare a constant or variable.
let cityName: String = "San Francisco"
let number: Double = 3
print(cityName)
print(number)
var x: Int
x = 10
print(x)
// When you write you own type definition.
struct Car {
var make: String
var model: String
var year: Int
}
// Basic arithmetic: you can use the +,-,* and / operators to perform basic math functionality.
var opponentScore = 3 * 5
var myScore = 100 / 4
print(opponentScore)
print(myScore)
var totalScore = opponentScore + myScore
print(totalScore) // totalScore has a value of 40
totalScore += 3 // totalScore has a value of 43
print(totalScore)
totalScore -= 5 // totalScore has a value of 38
print(totalScore)
totalScore *= 2 // totalScore has a value of 76
print(totalScore)
totalScore /= 2
print(totalScore) // totalScore has a value of 38
let k: Double = 51
let y: Double = 4
let z = k / y // z has a value of 12.75
print(z)
// IF-ELSE STATEMENTS
let temperature = 100
if temperature >= 100 {
print("The water is boiling.")
} else {
print("The water is not boiling.")
}
// Console output: The water is boiling.
var finishPosition = 2
if finishPosition == 1 {
print("Congratulations, you won the gold medal!")
} else if finishPosition == 2 {
print("You came in second place, you won a silver medal!")
} else {
print("You did not win a gold or silver medal")
}
// Console output: You came in second place, you won a silver medal!
// Boolean values
let num = 1000
let isSmallNumber = num < 10
print(isSmallNumber) // Console output: false
var isSnowing = false
if !isSnowing {
print("It is not snowing.")
}
// Console outout: It is not snowing.
// logical and operator, represented by &&
let temp = 70
if temp >= 65 && temp <= 75 {
print("The temperature is just right.")
} else if temp < 65 {
print("It is too cold.")
} else {
print("It is too hot.")
}
// Console outout: The temperature is just right.
// logical or operator, represented by ||
var isPluggedIn = false
var hasBatteryPower = true
if isPluggedIn || hasBatteryPower {
print("You can use your laptop.")
} else {
print("=O")
}
// Console outout: You can use your laptop.
// Switch statement
let numberOfWheels = 2
switch numberOfWheels {
case 1:
print("Unicycle")
case 2:
print("Bicycle")
case 3:
print("Tricycle")
case 4:
print("Quadcycle")
default:
print("That`s a lot of wheels!")
}
// Console outout: Bicycle
// Ternary operator
var largest: Int
let a = 15
let b = 4
if a > b {
largest = a
} else {
largest = b
}
// You can read it as: "if a > b, assign a to the largest constant; otherwise, assign b."
// In this case, a is greater than b, so it`s assigned to largest.
largest = a > b ? a : b
var myString = ""
if myString.isEmpty {
print("The string is empty")
}
// Console outout: The string is empty
let r = "r" // 'r' is a String
let f: Character = "f" // 'f' is a Character
// Concatenation and interpolation
let str1 = "Hello"
let str2 = ", world!"
let concatString = str1 + str2 // "Hello, world!"
let m = 4
let n = 5
print("If a is \(m) and b is \(n), then a + b equals \(m+n) ")
// Console output: If a is 4 and b is 5, then a + b equals 9
let nome = "Johnny Appleseed"
if nome.lowercased() == "joHnnY aPPleseeD".lowercased() {
print("The two name are equal.")
}
// Console output: The two name are equal.
let myName = "Rubens Santos Barbosa"
let count = myName.characters.count
print(count) // Console output: 21
let newPassword = "12345"
if newPassword.characters.count < 8 {
print("This password is too short. Password should have at least eight characters.")
} // Console output: This password is too short. Password should have at least eight characters.
// Functions
func displayPi() {
print("3.1415926535")
}
displayPi() // Console output: 3.1415926535
func triple(value: Int) {
let result = value * 3
print("If you multiply \(value) by 3, you'll get \(result)")
}
triple(value: 3) // Console output: If you multiply 3 by 3, you'll get 9
func multiply(firstNum: Int, secondNum: Int) {
let result = firstNum * secondNum
print("The result is \(result)")
}
multiply(firstNum: 10, secondNum: 5) // Console output: The result is 50
func sayHello(firstNome: String) {
print("Hi, \(firstNome)!")
}
sayHello(firstNome: "Rubens") // Console output: Hi, Rubens!
func sayHelloo(to person: String, and anotherPerson: String) {
print("Hello \(person) and \(anotherPerson)")
}
sayHelloo(to: "Rubens", and: "Gabriel") // Console output: Hello Rubens and Gabriel
func sayHellooo(_ person: String, _ anotherPerson: String) {
print("Hello \(person) and \(anotherPerson)")
}
sayHellooo("Rubens", "Gabriel") // Console output: Hello Rubens and Gabriel
func multiplyReturn(fNum: Int, sNum: Int) -> Int {
let res = fNum * sNum
return res
}
let myResult = multiplyReturn(fNum: 5, sNum: 5)
print("5 * 5 is \(myResult)") // Console output: 5 * 5 is 25
struct Whoiam {
var n: String
func hi() {
print("Hi, there! My name is \(n)")
}
}
let whoiam = Whoiam(n: "Rubens")
whoiam.hi()
// Console output: Hi, there! My name is Rubens
| mit | 37c7316d75e4f08dddf4d8a972cfcd6e | 23.324415 | 106 | 0.688437 | 3.51183 | false | false | false | false |
zhxnlai/AsyncTask | Tests/Helper.swift | 1 | 805 | //
// Helper.swift
// AsyncTask
//
// Created by Zhixuan Lai on 6/10/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
extension CollectionType {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
extension MutableCollectionType where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in 0..<count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
| mit | e604618e3eedb9bb25e7a42f17965f0d | 24.125 | 66 | 0.590796 | 3.980198 | false | false | false | false |
gnachman/iTerm2 | sources/ParsedSSHArguments.swift | 2 | 5824 | //
// ParsedSSHArguments.swift
// iTerm2SharedARC
//
// Created by George Nachman on 5/12/22.
//
import Foundation
import FileProviderService
struct ParsedSSHArguments: Codable, CustomDebugStringConvertible {
let hostname: String
let username: String?
let port: Int?
private(set) var paramArgs = ParamArgs()
private(set) var commandArgs = [String]()
var debugDescription: String {
return "recognized params: \(paramArgs.debugDescription); username=\(String(describing: username)); hostname=\(hostname); port=\(String(describing: port)); command=\(commandArgs.joined(separator: ", "))"
}
struct ParamArgs: Codable, OptionSet, CustomDebugStringConvertible {
var rawValue: Set<OptionValue>
enum Option: String, Codable {
case loginName = "l"
case port = "p"
}
struct OptionValue: Codable, Equatable, Hashable {
let option: Option
let value: String
}
init?(_ option: String, value: String) {
guard let opt = Option(rawValue: option) else {
return nil
}
rawValue = Set([OptionValue(option: opt, value: value)])
}
init() {
rawValue = Set<OptionValue>()
}
init(rawValue: Set<OptionValue>) {
self.rawValue = rawValue
}
typealias RawValue = Set<OptionValue>
mutating func formUnion(_ other: __owned ParsedSSHArguments.ParamArgs) {
rawValue.formUnion(other.rawValue)
}
mutating func formIntersection(_ other: ParsedSSHArguments.ParamArgs) {
rawValue.formIntersection(other.rawValue)
}
mutating func formSymmetricDifference(_ other: __owned ParsedSSHArguments.ParamArgs) {
rawValue.formSymmetricDifference(other.rawValue)
}
func hasOption(_ option: Option) -> Bool {
return rawValue.contains { ov in
ov.option == option
}
}
func value(for option: Option) -> String? {
return rawValue.first { ov in
ov.option == option
}?.value
}
var debugDescription: String {
return rawValue.map { "-\($0.option.rawValue) \($0.value)" }.sorted().joined(separator: " ")
}
}
var identity: SSHIdentity {
return SSHIdentity(hostname, username: username, port: port ?? 22)
}
init(_ string: String, booleanArgs boolArgsString: String) {
let booleanArgs = Set(Array<String.Element>(boolArgsString).map { String($0) })
guard let args = (string as NSString).componentsInShellCommand() else {
hostname = ""
username = nil
port = nil
return
}
var destination: String? = nil
var optionsAllowed = true
var preferredUser: String? = nil
var preferredPort: Int? = nil
var i = 0
while i < args.count {
defer { i += 1 }
let arg = args[i]
if destination != nil && !arg.hasPrefix("-") {
// ssh localhost /bin/bash
// ^^^^^^^^^
// parsing this arg. After this point arguments are to /bin/bash, not to ssh client.
// Note that in "ssh localhost -t /bin/bash", "-t" is an argument to the ssh client.
optionsAllowed = false
}
if optionsAllowed && arg.hasPrefix("-") {
if arg == "--" {
optionsAllowed = false
continue
}
let splitArg = Array(arg)
if splitArg.count == 1 {
// Invalid argument of "-"
continue
}
if splitArg.dropFirst().contains(where: { booleanArgs.contains(String($0)) }) {
// Is boolean arg, ignore.
continue
}
if Array(arg).count != 2 {
// All unrecognized single-letter args I guess
continue
}
i += 1
if i >= args.count {
// Missing param. Just ignore it.
continue
}
guard let paramArg = ParamArgs(String(arg.dropFirst()), value: args[i]) else {
continue
}
paramArgs.formUnion(paramArg)
continue
}
if destination == nil {
if let url = URL(string: arg), url.scheme == "ssh" {
if let user = url.user, let host = url.host {
preferredUser = user
destination = host
} else if let host = url.host {
destination = host
}
if !paramArgs.hasOption(.port), let urlPort = url.port {
preferredPort = urlPort
}
}
destination = arg
continue
}
commandArgs.append(arg)
}
// ssh's behavior seems to be to glue arguments together with spaces and reparse them.
// ["ssh", "example.com", "cat", "file with space"] executes ["cat", "file", "with", "space"]
// ["ssh", "example.com", "cat", "'file with space"'] executes ["cat", "file with space"]
commandArgs = (commandArgs.joined(separator: " ") as NSString).componentsInShellCommand()
hostname = destination ?? ""
username = preferredUser ?? paramArgs.value(for: .loginName)
port = preferredPort ?? paramArgs.value(for: .port).map { Int($0) } ?? 22
}
}
| gpl-2.0 | 4812e04a7c3016780c71f46b17a3c0e6 | 34.084337 | 211 | 0.513049 | 4.994854 | false | false | false | false |
remlostime/one | one/one/Models/NotificationConstant.swift | 1 | 510 | //
// NotificationConstant.swift
// one
//
// Created by Kai Chen on 1/26/17.
// Copyright © 2017 Kai Chen. All rights reserved.
//
import Foundation
enum Notifications: String {
case modelName = "Notification"
case sender = "sender"
case receiver = "receiver"
case action = "action"
case postUUID = "post_uuid"
case seen = "seen"
}
enum NotificationsAction: String {
case like = "like"
case comment = "comment"
case follow = "follow"
case mention = "mention"
}
| gpl-3.0 | c2c511699f41a2695d5570671c1ca5c5 | 19.36 | 51 | 0.646365 | 3.635714 | false | false | false | false |
P0ed/FireTek | Source/SpaceEngine/Fabrics/UnitFactory.swift | 1 | 4307 | import PowerCore
import Fx
import SpriteKit
enum UnitFactory {
@discardableResult
static func createShip(world: World, position: Point, team: Team) -> Entity {
let entity = world.entityManager.create()
let sprite = SpriteFactory.createShipSprite(entity, at: position)
let hp = HPComponent(maxHP: 80, armor: 40)
let physics = shipPhysics(sprite.sprite)
let primary = WeaponComponent(
type: .blaster,
damage: 12,
velocity: 340,
cooldown: 1.2,
perShotCooldown: 0.18,
roundsPerShot: 3,
maxAmmo: 60
)
let secondary = WeaponComponent(
type: .blaster,
damage: 36,
velocity: 260,
cooldown: 0.9,
perShotCooldown: 0,
roundsPerShot: 1,
maxAmmo: 20
)
let stats = ShipStats(speed: 36)
let ship = ShipComponent(
sprite: world.sprites.sharedIndexAt § world.sprites.add(component: sprite, to: entity),
physics: world.physics.sharedIndexAt § world.physics.add(component: physics, to: entity),
hp: world.hp.sharedIndexAt § world.hp.add(component: hp, to: entity),
input: world.shipInput.sharedIndexAt § world.shipInput.add(component: .empty, to: entity),
stats: world.shipStats.sharedIndexAt § world.shipStats.add(component: stats, to: entity),
primaryWpn: world.primaryWpn.sharedIndexAt § world.primaryWpn.add(component: primary, to: entity),
secondaryWpn: world.secondaryWpn.sharedIndexAt § world.secondaryWpn.add(component: secondary, to: entity)
)
let mapItem = MapItem(
type: team == .blue ? .ally : .enemy,
node: sprite.sprite
)
world.ships.add(component: ship, to: entity)
world.team.add(component: team, to: entity)
world.targets.add(component: .none, to: entity)
world.mapItems.add(component: mapItem, to: entity)
world.loot.add(component: LootComponent(crystal: .orange, count: 3), to: entity)
return entity
}
// @discardableResult
// static func createAIPlayer(world: World, position: Point) -> Entity {
// let entity = createTank(world: world, position: position, team: .red)
// let vehicle = world.vehicles.sharedIndexAt § world.vehicles.indexOf(entity)!
//
// let ai = VehicleAIComponent(vehicle: vehicle, state: .hold(Point(x: 0, y: 0)), target: nil)
// world.vehicleAI.add(component: ai, to: entity)
//
// return entity
// }
static func shipPhysics(_ sprite: SKSpriteNode) -> PhysicsComponent {
let body = SKPhysicsBody(rectangleOf: sprite.size)
body.mass = 40
body.angularDamping = 1
body.categoryBitMask = 0x1
sprite.physicsBody = body
return PhysicsComponent(body: body)
}
@discardableResult
static func createBuilding(world: World, position: Point) -> Entity {
let entity = world.entityManager.create()
let sprite = SpriteFactory.createBuildingSprite(entity, at: position)
let hp = HPComponent(maxHP: 40)
let building = BuildingComponent(
sprite: world.sprites.sharedIndexAt § world.sprites.add(component: sprite, to: entity),
hp: world.hp.sharedIndexAt § world.hp.add(component: hp, to: entity)
)
world.buildings.add(component: building, to: entity)
let physics = buildingPhysics(sprite.sprite)
world.physics.add(component: physics, to: entity)
world.loot.add(component: LootComponent(crystal: .blue, count: 1), to: entity)
return entity
}
static func buildingPhysics(_ sprite: SKSpriteNode) -> PhysicsComponent {
let body = SKPhysicsBody(rectangleOf: sprite.size)
body.isDynamic = false
body.categoryBitMask = 0x1
sprite.physicsBody = body
return PhysicsComponent(body: body)
}
@discardableResult
static func addCrystal(world: World, crystal: Crystal, at position: CGPoint, moveBy offset: CGVector) -> Entity {
let entity = world.entityManager.create()
let sprite = SpriteFactory.createCrystal(entity: entity, at: position, crystal: crystal)
let body = SKPhysicsBody(rectangleOf: sprite.sprite.size)
body.categoryBitMask = 0x1 << 2
body.collisionBitMask = 0x1
body.contactTestBitMask = 0x1
sprite.sprite.physicsBody = body
sprite.sprite.run(.group([
.repeatForever(.rotate(byAngle: 1, duration: 0.6)),
.move(by: offset, duration: 0.6)
]))
world.sprites.add(component: sprite, to: entity)
world.lifetime.add(component: LifetimeComponent(lifetime: 600), to: entity)
world.crystals.add(component: CrystalComponent(crystal: crystal), to: entity)
return entity
}
}
| mit | a1419ff62328544f3f7e757c3bede2c0 | 30.595588 | 114 | 0.725157 | 3.282659 | false | false | false | false |
IvanVorobei/Sparrow | sparrow/share/SPShare.swift | 1 | 2657 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public struct SPShare {
public struct Native {
static func share(text: String? = nil, fileNames: [String] = [], complection: ((_ isSharing: Bool)->())? = nil, sourceView: UIView, on viewController: UIViewController) {
var shareData: [Any] = []
if text != nil {
shareData.append(text!)
}
for file in fileNames {
let path = Bundle.main.path(forResource: file, ofType: "")
if path != nil {
let fileData = URL.init(fileURLWithPath: path!)
shareData.append(fileData)
}
}
let shareViewController = UIActivityViewController(activityItems: shareData, applicationActivities: nil)
shareViewController.completionWithItemsHandler = {(activityType: UIActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) in
if !completed {
complection?(false)
return
}
complection?(true)
}
shareViewController.modalPresentationStyle = .popover
shareViewController.popoverPresentationController?.sourceView = sourceView
shareViewController.popoverPresentationController?.sourceRect = sourceView.bounds
viewController.present(shareViewController, animated: true, completion: nil)
}
}
}
| mit | bed20648f9bd45346bfc21364b8a9a91 | 44.793103 | 178 | 0.650979 | 5.387424 | false | false | false | false |
mssun/passforios | passKit/Helpers/DefaultsKeys.swift | 1 | 3699 | //
// DefaultsKeys.swift
// passKit
//
// Created by Mingshen Sun on 21/1/2017.
// Copyright © 2017 Bob Sun. All rights reserved.
//
import Foundation
import SwiftyUserDefaults
// Workaround for Xcode 13: https://github.com/sunshinejr/SwiftyUserDefaults/issues/285
public extension DefaultsSerializable where Self: Codable {
typealias Bridge = DefaultsCodableBridge<Self>
typealias ArrayBridge = DefaultsCodableBridge<[Self]>
}
public extension DefaultsSerializable where Self: RawRepresentable {
typealias Bridge = DefaultsRawRepresentableBridge<Self>
typealias ArrayBridge = DefaultsRawRepresentableArrayBridge<[Self]>
}
public var Defaults = DefaultsAdapter(defaults: UserDefaults(suiteName: Globals.groupIdentifier)!, keyStore: DefaultsKeys())
public enum KeySource: String, DefaultsSerializable {
case url, armor, file, itunes
}
public enum GitAuthenticationMethod: String, DefaultsSerializable {
case password, key
}
extension SearchBarScope: DefaultsSerializable {}
extension PasswordGenerator: DefaultsSerializable {}
public extension DefaultsKeys {
var pgpKeySource: DefaultsKey<KeySource?> { .init("pgpKeySource") }
var pgpPublicKeyURL: DefaultsKey<URL?> { .init("pgpPublicKeyURL") }
var pgpPrivateKeyURL: DefaultsKey<URL?> { .init("pgpPrivateKeyURL") }
var isYubiKeyEnabled: DefaultsKey<Bool> { .init("isYubiKeyEnabled", defaultValue: false) }
// Keep them for legacy reasons.
var pgpPublicKeyArmor: DefaultsKey<String?> { .init("pgpPublicKeyArmor") }
var pgpPrivateKeyArmor: DefaultsKey<String?> { .init("pgpPrivateKeyArmor") }
var gitSSHPrivateKeyArmor: DefaultsKey<String?> { .init("gitSSHPrivateKeyArmor") }
var passcodeKey: DefaultsKey<String?> { .init("passcodeKey") }
var gitURL: DefaultsKey<URL> { .init("gitURL", defaultValue: URL(string: "https://")!) }
var gitAuthenticationMethod: DefaultsKey<GitAuthenticationMethod> { .init("gitAuthenticationMethod", defaultValue: GitAuthenticationMethod.password) }
var gitUsername: DefaultsKey<String> { .init("gitUsername", defaultValue: "git") }
var gitBranchName: DefaultsKey<String> { .init("gitBranchName", defaultValue: "master") }
var gitSSHPrivateKeyURL: DefaultsKey<URL?> { .init("gitSSHPrivateKeyURL") }
var gitSSHKeySource: DefaultsKey<KeySource?> { .init("gitSSHKeySource") }
var gitSignatureName: DefaultsKey<String?> { .init("gitSignatureName") }
var gitSignatureEmail: DefaultsKey<String?> { .init("gitSignatureEmail") }
var lastSyncedTime: DefaultsKey<Date?> { .init("lastSyncedTime") }
var isHideUnknownOn: DefaultsKey<Bool> { .init("isHideUnknownOn", defaultValue: false) }
var isHideOTPOn: DefaultsKey<Bool> { .init("isHideOTPOn", defaultValue: false) }
var isRememberPGPPassphraseOn: DefaultsKey<Bool> { .init("isRememberPGPPassphraseOn", defaultValue: false) }
var isRememberGitCredentialPassphraseOn: DefaultsKey<Bool> { .init("isRememberGitCredentialPassphraseOn", defaultValue: false) }
var isEnableGPGIDOn: DefaultsKey<Bool> { .init("isEnableGPGIDOn", defaultValue: false) }
var isShowFolderOn: DefaultsKey<Bool> { .init("isShowFolderOn", defaultValue: true) }
var isHidePasswordImagesOn: DefaultsKey<Bool> { .init("isHidePasswordImagesOn", defaultValue: false) }
var searchDefault: DefaultsKey<SearchBarScope?> { .init("searchDefault", defaultValue: .all) }
var passwordGenerator: DefaultsKey<PasswordGenerator> { .init("passwordGenerator", defaultValue: PasswordGenerator()) }
var encryptInArmored: DefaultsKey<Bool> { .init("encryptInArmored", defaultValue: false) }
var autoCopyOTP: DefaultsKey<Bool> { .init("autoCopyOTP", defaultValue: false) }
}
| mit | 04cb1e85f59b14238d4d8d3a5afe747f | 49.657534 | 154 | 0.754732 | 4.187995 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/Integration/ConversationTests+LegalHold.swift | 1 | 10755 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import WireSyncEngine
class ConversationTests_LegalHold: ConversationTestsBase {
func testThatItInsertsLegalHoldSystemMessage_WhenDiscoveringLegalHoldClientOnSending() {
// given
XCTAssertTrue(login())
let conversation = self.conversation(for: selfToUser1Conversation)
mockTransportSession.performRemoteChanges { (session) in
session.registerClient(for: self.user1, label: "Legal Hold", type: "legalhold", deviceClass: "legalhold")
}
// when
userSession?.perform {
try! conversation?.appendText(content: "Hello")
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
let secondToLastMessage = conversation?.lastMessages()[1] as? ZMSystemMessage
XCTAssertEqual(secondToLastMessage?.systemMessageType, .legalHoldEnabled)
XCTAssertEqual(conversation?.legalHoldStatus, .pendingApproval)
}
func testThatItInsertsLegalHoldSystemMessage_WhenLegalHoldClientIsReportedAsDeletedOnSending() {
// given
XCTAssertTrue(login())
let conversation = self.conversation(for: selfToUser1Conversation)
var legalHoldClient: MockUserClient!
mockTransportSession.performRemoteChanges { (session) in
legalHoldClient = session.registerClient(for: self.user1, label: "Legal Hold", type: "legalhold", deviceClass: "legalhold")
}
userSession?.perform {
try! conversation?.appendText(content: "Hello")
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
XCTAssertEqual(conversation?.legalHoldStatus, .pendingApproval)
conversation?.acknowledgePrivacyWarning(withResendIntent: true)
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
XCTAssertEqual(conversation?.legalHoldStatus, .enabled)
mockTransportSession.performRemoteChanges { (session) in
session.deleteUserClient(withIdentifier: legalHoldClient.identifier!, for: self.user1)
}
// when
userSession?.perform {
try! conversation?.appendText(content: "Hello")
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
let lastMessage = conversation?.lastMessage as? ZMSystemMessage
XCTAssertEqual(lastMessage?.systemMessageType, .legalHoldDisabled)
XCTAssertEqual(conversation?.legalHoldStatus, .disabled)
}
func testThatItInsertsLegalHoldSystemMessage_WhenUserUnderLegalHoldIsJoiningConversation() {
// given
XCTAssertTrue(login())
let legalHoldUser = self.user(for: user1)!
let groupConversation = self.conversation(for: self.groupConversation)
mockTransportSession.performRemoteChanges { (session) in
session.registerClient(for: self.user1, label: "Legal Hold", type: "legalhold", deviceClass: "legalhold")
}
legalHoldUser.fetchUserClients()
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// when
groupConversation?.addParticipants([legalHoldUser], completion: { _ in })
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
let lastMessage = groupConversation?.lastMessage as? ZMSystemMessage
XCTAssertEqual(lastMessage?.systemMessageType, .legalHoldEnabled)
XCTAssertEqual(groupConversation?.legalHoldStatus, .pendingApproval)
}
func testThatItInsertsLegalHoldSystemMessage_WhenUserUnderLegalHoldIsLeavingConversation() {
// given
XCTAssertTrue(login())
let legalHoldUser = self.user(for: user1)!
let groupConversation = self.conversation(for: self.groupConversation)
mockTransportSession.performRemoteChanges { (session) in
session.registerClient(for: self.user1, label: "Legal Hold", type: "legalhold", deviceClass: "legalhold")
}
legalHoldUser.fetchUserClients()
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
groupConversation?.addParticipants([legalHoldUser], completion: { _ in })
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
XCTAssertEqual(groupConversation?.legalHoldStatus, .pendingApproval)
// when
groupConversation?.removeParticipant(legalHoldUser, completion: {_ in })
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
let lastMessage = groupConversation?.lastMessage as? ZMSystemMessage
XCTAssertEqual(lastMessage?.systemMessageType, .legalHoldDisabled)
XCTAssertEqual(groupConversation?.legalHoldStatus, .disabled)
}
// MARK: Legal hold status flag
func testThatItUpdatesLegalHoldStatus_WhenReceivingLegalHoldStatusFlagEnabled() {
// given
XCTAssertTrue(login())
let selfUserClient = self.selfUser.clients.anyObject() as! MockUserClient
let otherUserClient = user1.clients.anyObject() as! MockUserClient
let conversation = self.conversation(for: selfToUser1Conversation)
mockTransportSession.performRemoteChanges { (session) in
session.registerClient(for: self.user1, label: "Legal Hold", type: "legalhold", deviceClass: "legalhold")
}
// when
mockTransportSession.performRemoteChanges { (_) in
var genericMessage = GenericMessage(content: Text(content: "Hello"))
genericMessage.setLegalHoldStatus(.enabled)
do {
self.selfToUser1Conversation.encryptAndInsertData(from: otherUserClient, to: selfUserClient, data: try genericMessage.serializedData())
} catch {
XCTFail("Error in adding data: \(error)")
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
XCTAssertEqual(conversation?.legalHoldStatus, .pendingApproval)
}
func testThatItUpdatesLegalHoldStatus_WhenReceivingLegalHoldStatusFlagDisabled() {
// given
XCTAssertTrue(login())
let legalHoldUser = self.user(for: user1)!
let selfUserClient = self.selfUser.clients.anyObject() as! MockUserClient
let otherUserClient = user1.clients.anyObject() as! MockUserClient
var legalHoldClient: MockUserClient!
let conversation = self.conversation(for: selfToUser1Conversation)
mockTransportSession.performRemoteChanges { (session) in
legalHoldClient = session.registerClient(for: self.user1, label: "Legal Hold", type: "legalhold", deviceClass: "legalhold")
}
legalHoldUser.fetchUserClients()
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
XCTAssertEqual(conversation?.legalHoldStatus, .pendingApproval)
// when
mockTransportSession.performRemoteChanges { (session) in
session.deleteUserClient(withIdentifier: legalHoldClient.identifier!, for: self.user1)
var genericMessage = GenericMessage(content: Text(content: "Hello"))
genericMessage.setLegalHoldStatus(.disabled)
do {
self.selfToUser1Conversation.encryptAndInsertData(from: otherUserClient, to: selfUserClient, data: try genericMessage.serializedData())
} catch {
XCTFail("Error in adding data: \(error)")
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
XCTAssertEqual(conversation?.legalHoldStatus, .disabled)
}
func testThatItRepairsAnIncorrectLegalHoldStatus_AfterReceivingLegalHoldStatusFlagEnabled() {
// given
XCTAssertTrue(login())
let selfUserClient = self.selfUser.clients.anyObject() as! MockUserClient
let otherUserClient = user1.clients.anyObject() as! MockUserClient
let conversation = self.conversation(for: selfToUser1Conversation)
// when
mockTransportSession.performRemoteChanges { (_) in
var genericMessage = GenericMessage(content: Text(content: "Hello"))
genericMessage.setLegalHoldStatus(.enabled)
do {
self.selfToUser1Conversation.encryptAndInsertData(from: otherUserClient, to: selfUserClient, data: try genericMessage.serializedData())
} catch {
XCTFail("Error in adding data: \(error)")
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
XCTAssertEqual(conversation?.legalHoldStatus, .disabled)
}
func testThatItRepairsAnIncorrectLegalHoldStatus_AfterReceivingLegalHoldStatusFlagDisabled() {
// given
XCTAssertTrue(login())
let selfUserClient = self.selfUser.clients.anyObject() as! MockUserClient
let otherUserClient = user1.clients.anyObject() as! MockUserClient
let conversation = self.conversation(for: selfToUser1Conversation)
mockTransportSession.performRemoteChanges { (session) in
session.registerClient(for: self.user1, label: "Legal Hold", type: "legalhold", deviceClass: "legalhold")
}
userSession?.perform {
try! conversation!.appendText(content: "This is the best group!")
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
XCTAssertEqual(conversation?.legalHoldStatus, .pendingApproval)
// when
mockTransportSession.performRemoteChanges { (_) in
var genericMessage = GenericMessage(content: Text(content: "Hello"))
genericMessage.setLegalHoldStatus(.disabled)
do {
self.selfToUser1Conversation.encryptAndInsertData(from: otherUserClient, to: selfUserClient, data: try genericMessage.serializedData())
} catch {
XCTFail("Error in adding data: \(error)")
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
XCTAssertEqual(conversation?.legalHoldStatus, .pendingApproval)
}
}
| gpl-3.0 | d40ab430c35ba18a732e78a198b5461f | 41.678571 | 151 | 0.690563 | 5.426337 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Widgets/PhotonActionSheet/ToggleSwitch.swift | 2 | 1144 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import UIKit
struct ToggleSwitch {
let mainView: UIImageView = {
let background = UIImageView(image: UIImage.templateImageNamed(ImageIdentifiers.customSwitchBackground))
background.contentMode = .scaleAspectFit
return background
}()
private let foreground = UIImageView()
init() {
foreground.autoresizingMask = [.flexibleWidth, .flexibleHeight]
foreground.contentMode = .scaleAspectFit
foreground.frame = mainView.frame
mainView.isAccessibilityElement = true
mainView.addSubview(foreground)
setOn(false)
}
func setOn(_ on: Bool) {
foreground.image = on ? UIImage(named: ImageIdentifiers.customSwitchOn) : UIImage(named: ImageIdentifiers.customSwitchOff)
mainView.accessibilityIdentifier = on ? "enabled" : "disabled"
mainView.tintColor = on ? UIColor.theme.general.controlTint : UIColor.theme.general.switchToggle }
}
| mpl-2.0 | 8c448467d3cdba0d61269417e97c8e2d | 38.448276 | 130 | 0.70542 | 4.827004 | false | false | false | false |
FelixSFD/FDRatingView | Shared/Star.swift | 1 | 2450 | //
// Star.swift
// FDRatingView
//
// Created by Felix Deil on 11.05.16.
// Copyright © 2016 Felix Deil. All rights reserved.
//
//import UIKit
import QuartzCore
import CoreGraphics
/**
Struct to generate paths for stars
- author: Felix Deil, [Silviu Pop](https://www.weheartswift.com/bezier-paths-gesture-recognizers/)
*/
internal struct Star {
internal var pointsOnStar: Int = 5
/**
Returns the path for a star
- author: [Silviu Pop](https://www.weheartswift.com/bezier-paths-gesture-recognizers/)
- copyright: Silviu Pop
*/
private func starPathInRect(_ rect: CGRect) -> FDBezierPath {
let path = FDBezierPath()
let starExtrusion: CGFloat = rect.width*0.19
let center = CGPoint(x: rect.width / 2.0, y: rect.height / 2.0)
var angle: CGFloat = -CGFloat(M_PI / 2.0)
let angleIncrement = CGFloat(M_PI * 2.0 / Double(pointsOnStar))
let radius = rect.width / 2.0
var firstPoint = true
for _ in 1...pointsOnStar {
let point = pointFrom(angle, radius: radius, offset: center)
let nextPoint = pointFrom(angle + angleIncrement, radius: radius, offset: center)
let midPoint = pointFrom(angle + angleIncrement / 2.0, radius: starExtrusion, offset: center)
if firstPoint {
firstPoint = false
path.move(to: point)
}
path.addLine(to: midPoint)
path.addLine(to: nextPoint)
angle += angleIncrement
}
path.close()
return path
}
/**
The `CGPath` of the star in `rect`
- parameter rect: The square, that should contain the star
*/
internal func CGPathInRect(_ rect: CGRect) -> CGPath {
return starPathInRect(rect).cgPath
}
/**
The `UIBezierPath` of the star in `rect`
- parameter rect: The square, that should contain the star
*/
internal func pathInRect(_ rect: CGRect) -> FDBezierPath {
return starPathInRect(rect)
}
private func pointFrom(_ angle: CGFloat, radius: CGFloat, offset: CGPoint) -> CGPoint {
return CGPoint(x: radius * cos(angle) + offset.x, y: radius * sin(angle) + offset.y)
}
internal init() {
}
}
| apache-2.0 | d8e372e4edc4546e1d726e95cd966d7e | 25.912088 | 105 | 0.564312 | 4.266551 | false | false | false | false |
neonichu/ECoXiS | ECoXiS/Model.swift | 1 | 13080 | // TODO: add deep copying
public enum XMLNodeType {
case Element, Text, Comment, ProcessingInstruction
}
public protocol XMLNode: Printable {
var nodeType: XMLNodeType { get }
}
public func == (left: XMLNode, right: XMLNode) -> Bool {
if left.nodeType != right.nodeType {
return false
}
switch left.nodeType {
case .Element:
return (left as! XMLElement) != right as! XMLElement
case .Text:
return (left as! XMLText) != right as! XMLText
case .Comment:
return (left as! XMLComment) != right as! XMLComment
case .ProcessingInstruction:
return left as! XMLProcessingInstruction
!= right as! XMLProcessingInstruction
}
}
public func != (left: XMLNode, right: XMLNode) -> Bool {
return !(left == right)
}
public func == (left: [XMLNode], right: [XMLNode]) -> Bool {
if left.count != right.count {
return false
}
for (leftNode, rightNode) in Zip2(left, right) {
if leftNode != rightNode {
return false
}
}
return true
}
public protocol XMLMiscNode: XMLNode {}
public func == (left: XMLMiscNode, right: XMLMiscNode) -> Bool {
return left as XMLNode == right as XMLNode
}
public func != (left: XMLMiscNode, right: XMLMiscNode) -> Bool {
return (left as XMLNode) != right as XMLNode
}
public func == (left: [XMLMiscNode], right: [XMLMiscNode]) -> Bool {
if left.count != right.count {
return false
}
for (leftNode, rightNode) in Zip2(left, right) {
if leftNode != rightNode {
return false
}
}
return true
}
public func += (inout left: [XMLNode], right: [XMLMiscNode]) {
for node in right {
left.append(node)
}
}
public func == (left: String, right: XMLText) -> Bool {
return left == right.content
}
public func == (left: XMLText, right: String) -> Bool {
return left.content == right
}
public enum XMLNameSettingResult {
case InvalidName, ModifiedName, ValidName
}
public class XMLAttributes: SequenceType, Equatable {
private var _attributes = [String: String]()
public var count: Int { return _attributes.count }
// MARK: BUG: making "attributes" unnamed yields compiler error
init(attributes: [String: String] = [:]) {
update(attributes)
}
public func set(name: String, _ value: String?) -> XMLNameSettingResult {
if let _name = XMLUtilities.enforceName(name) {
if !_name.isEmpty {
_attributes[_name] = value
return _name == name ? .ValidName : .ModifiedName
}
}
return .InvalidName
}
public func contains(name: String) -> Bool {
return _attributes[name] != nil
}
public func update(attributes: [String: String]) {
for (name, value) in attributes {
set(name, value)
}
}
public func generate() -> GeneratorOf<(String, String)> {
return GeneratorOf(_attributes.generate())
}
public subscript(name: String) -> String? {
get {
return _attributes[name]
}
set {
set(name, newValue)
}
}
class func createString(var attributeGenerator:
GeneratorOf<(String, String)>) -> String {
var result = ""
while let (name, value) = attributeGenerator.next() {
var escapedValue = XMLUtilities.escape(value, .EscapeQuot)
result += " \(name)=\"\(escapedValue)\""
}
return result
}
func toString() -> String {
return XMLAttributes.createString(self.generate())
}
func equals(other: XMLAttributes) -> Bool {
return self._attributes == other._attributes
}
}
public func == (left: XMLAttributes, right: XMLAttributes) -> Bool {
return left.equals(right)
}
public class XMLElement: XMLNode, Equatable {
public let nodeType = XMLNodeType.Element
private var _name: String?
public var name: String? {
get { return _name }
set {
if let name = newValue {
_name = XMLUtilities.enforceName(name)
}
else {
_name = nil
}
}
}
public let attributes: XMLAttributes
public var children: [XMLNode]
public var description:String {
if let n = name {
return XMLElement.createString(n,
attributesString: attributes.toString(),
childrenString: XMLElement.createChildrenString(children))
}
return ""
}
public init(_ name: String, attributes: [String: String] = [:],
children: [XMLNode] = []) {
self.attributes = XMLAttributes(attributes: attributes)
self.children = children
self.name = name
}
public subscript(name: String) -> String? {
get {
return attributes[name]
}
set {
attributes[name] = newValue
}
}
public subscript(index: Int) -> XMLNode? {
get {
if index < children.count {
return children[index]
}
return nil
}
set {
if let node = newValue {
if index == children.count {
children.append(node)
}
else {
children[index] = node
}
}
else {
children.removeAtIndex(index)
}
}
}
class func createChildrenString(children: [XMLNode]) -> String {
var childrenString = ""
for child in children {
childrenString += child.description
}
return childrenString
}
class func createString(name: String, attributesString: String = "",
childrenString: String = "") -> String {
var result = "<\(name)\(attributesString)"
if childrenString.isEmpty {
result += "/>"
}
else {
result += ">\(childrenString)</\(name)>"
}
return result
}
}
public func == (left: XMLElement, right: XMLElement) -> Bool {
if left.name != right.name || left.attributes != right.attributes {
return false
}
return left.children == right.children
}
public class XMLDocumentTypeDeclaration: Equatable {
private var _systemID: String?
private var _publicID: String?
private var _useQuotForSystemID = false
public var useQuotForSystemID: Bool { return _useQuotForSystemID }
public var systemID: String? {
get { return _systemID }
set {
(_useQuotForSystemID, _systemID) =
XMLUtilities.enforceDoctypeSystemID(newValue)
}
}
public var publicID: String? {
get { return _publicID }
set {
_publicID = XMLUtilities.enforceDoctypePublicID(newValue)
}
}
public init(publicID: String? = nil, systemID: String? = nil) {
self.publicID = publicID
self.systemID = systemID
}
public func toString(name: String) -> String {
var result = "<!DOCTYPE \(name)"
if let sID = systemID {
if let pID = publicID {
result += " PUBLIC \"\(pID)\" "
}
else {
result += " SYSTEM "
}
if useQuotForSystemID {
result += "\"\(sID)\""
}
else {
result += "'\(sID)'"
}
}
result += ">"
return result
}
}
public func == (left: XMLDocumentTypeDeclaration,
right: XMLDocumentTypeDeclaration) -> Bool {
return left.publicID == right.publicID && left.systemID == right.systemID
}
public class XMLDocument: SequenceType, Equatable {
public var omitXMLDeclaration: Bool
public var doctype: XMLDocumentTypeDeclaration?
public var beforeElement: [XMLMiscNode]
public var element: XMLElement
public var afterElement: [XMLMiscNode]
public var count: Int {
return beforeElement.count + 1 + afterElement.count
}
public init(_ element: XMLElement, beforeElement: [XMLMiscNode] = [],
afterElement: [XMLMiscNode] = [],
omitXMLDeclaration:Bool = false,
doctype: XMLDocumentTypeDeclaration? = nil) {
self.beforeElement = beforeElement
self.element = element
self.afterElement = afterElement
self.omitXMLDeclaration = omitXMLDeclaration
self.doctype = doctype
}
public func generate() -> GeneratorOf<XMLNode> {
var nodes = [XMLNode]()
nodes += beforeElement
nodes.append(element)
nodes += afterElement
return GeneratorOf(nodes.generate())
}
class func createString(#omitXMLDeclaration: Bool,
encoding: String? = nil,
doctypeString: String?,
childrenString: String) -> String {
var result = ""
if !omitXMLDeclaration {
result += "<?xml version=\"1.0\""
if let e = encoding {
result += " encoding=\"\(e)\""
}
result += "?>"
}
if let dtString = doctypeString {
result += dtString
}
result += childrenString
return result
}
public func toString(encoding: String? = nil) -> String {
if element.name == nil {
return ""
}
var doctypeString: String?
if let dt = doctype {
if let n = element.name {
doctypeString = dt.toString(n)
}
}
var childrenString = ""
for child in self {
childrenString += child.description
}
return XMLDocument.createString(omitXMLDeclaration: omitXMLDeclaration,
encoding: encoding, doctypeString: doctypeString,
childrenString: childrenString)
}
}
public func == (left: XMLDocument, right: XMLDocument) -> Bool {
return left.omitXMLDeclaration == right.omitXMLDeclaration
&& left.doctype == right.doctype
&& left.beforeElement == right.beforeElement
&& left.element == right.element
&& left.afterElement == right.afterElement
}
public class XMLText: XMLNode, Equatable {
public let nodeType = XMLNodeType.Text
public var content: String
public var description: String {
return XMLText.createString(content)
}
public init(_ content: String) {
self.content = content
}
class func createString(content: String) -> String {
return XMLUtilities.escape(content)
}
}
public func == (left: XMLText, right: XMLText) -> Bool {
return left.content == right.content
}
/**
Represents a XML comment node.
Note that a value assigned to the property/initialization parameter `content` is
stripped of invalid character combinations: a dash ("-") may not appear at
the beginning or the end and in between only single dashes may appear.
*/
public class XMLComment: XMLMiscNode, Equatable {
public let nodeType = XMLNodeType.Comment
private var _content: String?
public var content: String? {
get { return _content }
set { _content = XMLUtilities.enforceCommentContent(newValue) }
}
public var description: String {
if let c = content {
return XMLComment.createString(c)
}
return ""
}
public init(_ content: String) {
self.content = content
}
class func createString(content: String) -> String {
return "<!--\(content)-->"
}
}
public func == (left: XMLComment, right: XMLComment) -> Bool {
return left.content == right.content
}
public class XMLProcessingInstruction: XMLMiscNode, Equatable {
public let nodeType = XMLNodeType.ProcessingInstruction
private var _target: String?
public var target: String? {
get { return _target }
set {
_target = XMLUtilities.enforceProcessingInstructionTarget(newValue)
}
}
private var _value: String?
public var value: String? {
get { return _value }
set {
_value = XMLUtilities.enforceProcessingInstructionValue(newValue)
}
}
public var description: String {
if let t = target {
return XMLProcessingInstruction.createString(t, value: value)
}
return ""
}
public init(_ target: String, _ value: String? = nil) {
self.target = target
self.value = value
}
class func createString(target: String, value: String?) -> String {
var result = ""
result += "<?\(target)"
if let v = value {
result += " \(v)"
}
result += "?>"
return result
}
}
public func == (left: XMLProcessingInstruction,
right: XMLProcessingInstruction) -> Bool {
return left.target == right.target && left.value == right.value
}
| mit | 0732965431e9bb10c5242f1373c12db7 | 24.057471 | 80 | 0.573089 | 4.570231 | false | false | false | false |
colourful987/JustMakeGame-FlappyBird | Code/L08/FlappyBird-End/FlappyBird/GameViewController.swift | 10 | 1911 | //
// GameViewController.swift
// FlappyBird
//
// Created by pmst on 15/10/4.
// Copyright (c) 2015年 pmst. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// 1.对view进行父类向子类的变形,结果是一个可选类型 因此需要解包
if let skView = self.view as? SKView{
// 倘若skView中没有场景Scene,需要重新创建创建一个
if skView.scene == nil{
/*== 创建场景代码 ==*/
// 2.获得高宽比例
let aspectRatio = skView.bounds.size.height / skView.bounds.size.width
// 3.new一个场景实例 这里注意场景的width始终为320 至于高是通过width * aspectRatio获得
let scene = GameScene(size:CGSizeMake(320, 320 * aspectRatio))
// 4.设置一些调试参数
skView.showsFPS = true // 显示帧数
skView.showsNodeCount = true // 显示当前场景下节点个数
skView.showsPhysics = true // 显示物理体
skView.ignoresSiblingOrder = true // 忽略节点添加顺序
// 5.设置场景呈现模式
scene.scaleMode = .AspectFill
// 6.呈现场景
skView.presentScene(scene)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | ece7538e03345ff85c559f90dbf8ed07 | 27.964912 | 86 | 0.527559 | 4.63764 | false | false | false | false |
HTWDD/htwcampus | HTWDD/Components/Exams/Main/Views/ExamsCell.swift | 1 | 5489 | //
// ExamsCell.swift
// HTWDD
//
// Created by Benjamin Herzog on 06.11.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import UIKit
struct ExamsViewModel: ViewModel {
let title: String
let type: Exam.ExamType
let branch: String
let examiner: String
let room: String
let day: String
let time: String
init(model: Exam) {
self.title = model.title
self.type = model.type
self.branch = model.branch == "" ? "-" : model.branch
self.examiner = model.examiner
self.day = model.day
self.time = Loca.Exams.Cell.time(model.start, model.end)
if model.rooms.isEmpty {
self.room = Loca.Schedule.noRoom
} else if model.rooms.count == 1 {
self.room = model.rooms.first ?? Loca.Schedule.noRoom
} else {
self.room = model.rooms.joined(separator: ", ")
}
}
}
class ExamsCell: FlatCollectionViewCell, Cell {
enum Const {
static let margin: CGFloat = 12
static let innerMargin: CGFloat = 5
}
private let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 18, weight: .medium)
label.textColor = UIColor.htw.textHeadline
return label
}()
private let timeLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
label.textColor = UIColor.htw.textHeadline
return label
}()
private let examinerLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
label.textColor = UIColor.htw.mediumGrey
return label
}()
private let branchLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
label.textColor = UIColor.htw.mediumGrey
return label
}()
private let typeBadge: BadgeLabel = {
let badge = BadgeLabel()
badge.textColor = UIColor.htw.textHeadline
badge.backgroundColor = UIColor(hex: 0xE8E8E8)
badge.font = .systemFont(ofSize: 13, weight: .semibold)
return badge
}()
private let roomBadge: BadgeLabel = {
let badge = BadgeLabel()
badge.textColor = UIColor.htw.textHeadline
badge.backgroundColor = UIColor(hex: 0xCFCFCF)
badge.font = .systemFont(ofSize: 13, weight: .semibold)
return badge
}()
override func initialSetup() {
super.initialSetup()
self.contentView.add(self.titleLabel,
self.timeLabel,
self.branchLabel,
self.examinerLabel,
self.typeBadge,
self.roomBadge) { v in
v.translatesAutoresizingMaskIntoConstraints = false
}
NSLayoutConstraint.activate([
self.titleLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: Const.margin),
self.titleLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -Const.margin),
self.titleLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: Const.margin),
self.timeLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: Const.margin),
self.timeLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -Const.margin),
self.timeLabel.topAnchor.constraint(equalTo: self.titleLabel.bottomAnchor, constant: Const.innerMargin),
self.branchLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: Const.margin),
self.branchLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -Const.margin),
self.branchLabel.topAnchor.constraint(equalTo: self.timeLabel.bottomAnchor, constant: 0),
self.examinerLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: Const.margin),
self.examinerLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -Const.margin),
self.examinerLabel.topAnchor.constraint(equalTo: self.branchLabel.bottomAnchor, constant: 0),
self.typeBadge.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: Const.margin),
self.typeBadge.topAnchor.constraint(equalTo: self.examinerLabel.bottomAnchor, constant: Const.innerMargin),
self.roomBadge.leadingAnchor.constraint(equalTo: self.typeBadge.trailingAnchor, constant: Const.innerMargin),
self.roomBadge.topAnchor.constraint(equalTo: self.examinerLabel.bottomAnchor, constant: Const.innerMargin)
])
}
func update(viewModel: ExamsViewModel) {
self.titleLabel.text = viewModel.title
self.branchLabel.text = Loca.Exams.branch(viewModel.branch)
self.examinerLabel.text = Loca.Exams.examiner(viewModel.examiner)
self.typeBadge.text = viewModel.type.displayName
self.roomBadge.text = viewModel.room
let time = NSMutableAttributedString()
time.append(NSAttributedString(string: viewModel.day,
attributes: [.font: UIFont.systemFont(ofSize: 15, weight: .bold)]))
time.append(NSAttributedString(string: " "))
time.append(NSAttributedString(string: viewModel.time,
attributes: [.font: UIFont.systemFont(ofSize: 15, weight: .medium)]))
self.timeLabel.attributedText = time
}
}
| mit | 8df6dac126bccbaaa024a2676c7fcf34 | 37.111111 | 121 | 0.675656 | 4.198929 | false | false | false | false |
danthorpe/YapDatabaseExtensions | Tests/YapDatabaseExtensionsTests.swift | 1 | 9706 | //
// YapDatabaseExtensionsTests.swift
// YapDatabaseExtensionsTests
//
// Created by Daniel Thorpe on 10/06/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import XCTest
import ValueCoding
import YapDatabase
@testable import YapDatabaseExtensions
class YapDatabaseExtensionsTests: XCTestCase {
func test_ViewRegistration_NotRegisteredInEmptyDatabase() {
let db = YapDB.testDatabase()
let fetch: YapDB.Fetch = products()
XCTAssertFalse(fetch.isRegisteredInDatabase(db), "Extension should not be registered in fresh database.")
}
func test_ViewRegistration_RegistersCorrectly() {
let db = YapDB.testDatabase()
let fetch: YapDB.Fetch = products()
fetch.registerInDatabase(db)
XCTAssertTrue(fetch.isRegisteredInDatabase(db), "Extension should be registered in database.")
}
func test_AfterRegistration_ViewIsAccessible() {
let db = YapDB.testDatabase()
let fetch: YapDB.Fetch = products()
fetch.registerInDatabase(db)
db.newConnection().read { transaction in
XCTAssertNotNil(transaction.ext(fetch.name) as? YapDatabaseViewTransaction, "The view should be accessible inside a read transaction.")
}
}
func test_YapDBIndex_EncodingAndDecoding() {
let index = YapDB.Index(collection: "Foo", key: "Bar")
let _index = YapDB.Index.decode(index.encoded)
XCTAssertTrue(_index != nil, "Unarchived archive should not be nil")
XCTAssertEqual(index, _index!, "Unarchived archive should equal the original.")
}
}
class PersistableTests: XCTestCase {
func test__indexes_from_keys() {
let keys = [ "beatle-1", "beatle-2", "beatle-3", "beatle-4", "beatle-2" ]
let indexes = Person.indexesWithKeys(keys)
XCTAssertEqual(indexes.count, 4)
}
}
class YapDatabaseReadTransactionTests: ReadWriteBaseTests {
func test__keys_in_collection_returns_empty_with_empty_db() {
let db = YapDB.testDatabase()
let keys = db.makeNewConnection().read { $0.keysInCollection(Employee.collection) }
XCTAssertNotNil(keys)
XCTAssertTrue(keys.isEmpty)
}
func test__keys_in_collection_returns_all_keys_when_non_empty_db() {
let db = YapDB.testDatabase()
writeItemsToDatabase(db)
let keys = db.makeNewConnection().read { $0.keysInCollection(Employee.collection) }
XCTAssertNotNil(keys)
XCTAssertEqual(keys.sort(), items.map { $0.key }.sort())
}
func test__read_at_index_returns_nil_with_empty_db() {
let db = YapDB.testDatabase()
let object = db.makeNewConnection().read { $0.readAtIndex(self.index) }
XCTAssertNil(object)
}
func test__read_at_index_returns_object_when_non_empty_db() {
let db = YapDB.testDatabase()
writeItemsToDatabase(db)
let object = db.makeNewConnection().read { $0.readAtIndex(self.index) }
XCTAssertNotNil(object as? Employee)
XCTAssertEqual((object as! Employee).identifier, item.identifier)
}
func test__read_metadata_at_index_returns_nil_with_empty_db() {
let db = YapDB.testDatabase()
let metadata = db.makeNewConnection().read { $0.readMetadataAtIndex(self.index) }
XCTAssertNil(metadata)
}
func test__read_metadata_at_index_returns_object_when_non_empty_db() {
let db = YapDB.testDatabase()
writeItemsToDatabase(db)
let metadata = db.makeNewConnection().read { $0.readMetadataAtIndex(self.index) }
XCTAssertNotNil(metadata as? NSDate)
}
}
class YapDatabaseReadWriteTransactionTests: ReadWriteBaseTests {
func test__write_at_index_without_metadata() {
let db = YapDB.testDatabase()
db.makeNewConnection().readWriteWithBlock { transaction in
transaction.writeAtIndex(self.index, object: self.item)
}
let written = Employee.read(db).atIndex(index)
XCTAssertNotNil(written)
XCTAssertNil(written!.metadata)
XCTAssertEqual(written!.identifier, item.identifier)
}
func test__write_at_index_with_metadata() {
let db = YapDB.testDatabase()
db.makeNewConnection().readWriteWithBlock { transaction in
transaction.writeAtIndex(self.index, object: self.item, metadata: self.item.metadata)
}
let written = Employee.read(db).atIndex(index)
XCTAssertNotNil(written)
XCTAssertNotNil(written!.metadata)
XCTAssertEqual(written!.identifier, item.identifier)
}
func test__remove_at_indexes() {
let db = YapDB.testDatabase()
db.makeNewConnection().write(items)
XCTAssertNotNil(Employee.read(db).atIndex(index))
db.makeNewConnection().readWriteWithBlock { transaction in
transaction.removeAtIndexes(self.indexes)
}
XCTAssertNil(Employee.read(db).atIndex(index))
}
}
class YapDatabaseConnectionTests: ReadWriteBaseTests {
var dispatchQueue: dispatch_queue_t!
var operationQueue: NSOperationQueue!
override func setUp() {
super.setUp()
dispatchQueue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)
operationQueue = NSOperationQueue()
}
func test__async_read() {
let db = YapDB.testDatabase()
let expectation = expectationWithDescription("Test: \(#function)")
db.makeNewConnection().write(item)
XCTAssertNotNil(Employee.read(db).atIndex(index))
var received: Employee? = .None
db.newConnection().asyncRead({ transaction -> Employee? in
return transaction.readAtIndex(self.index) as? Employee
}, queue: dispatchQueue) { (result: Employee?) in
received = result
expectation.fulfill()
}
waitForExpectationsWithTimeout(3.0, handler: nil)
XCTAssertNotNil(received)
}
func test__async_write() {
let db = YapDB.testDatabase()
let expectation = expectationWithDescription("Test: \(#function)")
var written: Employee? = .None
db.makeNewConnection().asyncWrite({ transaction -> Employee? in
transaction.writeAtIndex(self.index, object: self.item, metadata: self.item.metadata)
return self.item
}, queue: dispatchQueue) { (result: Employee?) in
written = result
expectation.fulfill()
}
waitForExpectationsWithTimeout(3.0, handler: nil)
XCTAssertNotNil(written)
XCTAssertNotNil(Employee.read(db).atIndex(index))
}
func test__writeBlockOperation() {
let db = YapDB.testDatabase()
let expectation = expectationWithDescription("Test: \(#function)")
var didExecuteWithTransaction = false
let operation = db.makeNewConnection().writeBlockOperation { transaction in
didExecuteWithTransaction = true
}
operation.completionBlock = { expectation.fulfill() }
operationQueue.addOperation(operation)
waitForExpectationsWithTimeout(3.0, handler: nil)
XCTAssertTrue(operation.finished)
XCTAssertTrue(didExecuteWithTransaction)
}
}
class ValueCodingTests: XCTestCase {
var item: Product!
var index: YapDB.Index!
var key: String!
var items: [Product]!
var indexes: [YapDB.Index]!
var keys: [String]!
override func setUp() {
super.setUp()
createPersistables()
index = item.index
key = item.key
indexes = items.map { $0.index }
keys = items.map { $0.key }
}
override func tearDown() {
item = nil
index = nil
key = nil
items = nil
indexes = nil
keys = nil
super.tearDown()
}
func createPersistables() {
item = Product(
metadata: Product.Metadata(categoryIdentifier: 1),
identifier: "vodka-123",
name: "Belvidere",
barcode: .UPCA(1, 2, 3, 4)
)
items = [
item,
Product(
metadata: Product.Metadata(categoryIdentifier: 2),
identifier: "gin-123",
name: "Boxer Gin",
barcode: .UPCA(5, 10, 15, 20)
),
Product(
metadata: Product.Metadata(categoryIdentifier: 3),
identifier: "rum-123",
name: "Mount Gay Rum",
barcode: .UPCA(12, 24, 39, 48)
),
Product(
metadata: Product.Metadata(categoryIdentifier: 2),
identifier: "gin-234",
name: "Monkey 47",
barcode: .UPCA(31, 62, 93, 124)
)
]
}
func test__index_is_hashable() {
let byHashes: [YapDB.Index: Product] = items.reduce(Dictionary<YapDB.Index, Product>()) { (dictionary, product) in
var dictionary = dictionary
dictionary.updateValue(product, forKey: product.index)
return dictionary
}
XCTAssertEqual(byHashes.count, items.count)
}
func test__index_is_codable() {
let db = YapDB.testDatabase()
db.makeNewConnection().readWriteWithBlock { transaction in
transaction.setObject(self.index.encoded, forKey: "test-index", inCollection: "test-index-collection")
}
let unarchived = YapDB.Index.decode(db.makeNewConnection().read { $0.objectForKey("test-index", inCollection: "test-index-collection") })
XCTAssertNotNil(unarchived)
XCTAssertEqual(unarchived!, index)
}
func test__index_for_persistable() {
XCTAssertEqual(indexForPersistable(item), index)
}
}
| mit | 4ed2c7f0036a2443cec35ff57dbe5bf6 | 32.468966 | 147 | 0.632701 | 4.423883 | false | true | false | false |
chrishulbert/gondola-appletv | Gondola TVOS/ViewControllers/TVSeasonEpisodesViewController.swift | 1 | 6582 | //
// TVSeasonEpisodesViewController.swift
// Gondola TVOS
//
// Created by Chris on 12/02/2017.
// Copyright © 2017 Chris Hulbert. All rights reserved.
//
// This shows the details of a season and the list of episodes to choose from.
import UIKit
class TVSeasonEpisodesViewController: UIViewController {
let show: TVShowMetadata
let season: TVSeasonMetadata
let backdrop: UIImage?
init(show: TVShowMetadata, season: TVSeasonMetadata, backdrop: UIImage?) {
self.show = show
self.season = season
self.backdrop = backdrop
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var rootView = TVSeasonEpisodesView()
override func loadView() {
view = rootView
}
override func viewDidLoad() {
super.viewDidLoad()
rootView.collection.register(PictureCell.self, forCellWithReuseIdentifier: "cell")
rootView.collection.dataSource = self
rootView.collection.delegate = self
rootView.title.text = season.name
rootView.overview.text = season.overview
rootView.background.image = backdrop
}
}
extension TVSeasonEpisodesViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return season.episodes.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let episode = season.episodes[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PictureCell
cell.label.text = String(episode.episode) + ": " + episode.name
cell.image.image = nil
cell.imageAspectRatio = 9/16
// TODO use a reusable image view? Or some helper that checks for stale?
cell.imagePath = episode.image
ServiceHelpers.imageRequest(path: episode.image) { result in
DispatchQueue.main.async {
if cell.imagePath == episode.image { // Cell hasn't been recycled?
switch result {
case .success(let image):
cell.image.image = image
case .failure(let error):
NSLog("error: \(error)")
// TODO show sad cloud image.
}
}
}
}
return cell
}
}
extension TVSeasonEpisodesViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? PictureCell
let episode = season.episodes[indexPath.item]
let vc = TVEpisodeViewController(episode: episode,
show: show,
season: season,
episodeImage: cell?.image.image,
backdrop: rootView.background.image)
navigationController?.pushViewController(vc, animated: true)
}
}
class TVSeasonEpisodesView: UIView {
let background = UIImageView()
let dim = UIView()
let title = UILabel()
let overview = UILabel()
let collection: UICollectionView
let layout = UICollectionViewFlowLayout()
init() {
// TODO have a layout helper.
layout.scrollDirection = .vertical
let itemHeight = PictureCell.height(forWidth: K.itemWidth, imageAspectRatio: 9/16)
layout.itemSize = CGSize(width: K.itemWidth, height: itemHeight)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: LayoutHelpers.vertMargins, left: LayoutHelpers.sideMargins, bottom: LayoutHelpers.vertMargins, right: LayoutHelpers.sideMargins)
collection = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: layout)
collection.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
super.init(frame: CGRect.zero)
background.contentMode = .scaleAspectFill
addSubview(background)
dim.backgroundColor = UIColor(white: 0, alpha: 0.7)
addSubview(dim)
title.textColor = UIColor.white
title.font = UIFont.systemFont(ofSize: 60, weight: .thin)
addSubview(title)
overview.textColor = UIColor.white
overview.font = UIFont.systemFont(ofSize: 30, weight: .light)
overview.numberOfLines = 0
addSubview(overview)
addSubview(collection)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = bounds.width
let h = bounds.height
background.frame = bounds
let collectionWidth = K.itemWidth + 2*LayoutHelpers.sideMargins
collection.frame = CGRect(x: w - collectionWidth, y: 0, width: collectionWidth, height: h)
dim.frame = CGRect(x: 0, y: 0, width: w - collectionWidth, height: h)
let textWidth = w - collectionWidth - 2*LayoutHelpers.sideMargins
title.frame = CGRect(x: LayoutHelpers.sideMargins,
y: LayoutHelpers.vertMargins,
width: textWidth,
height: ceil(title.font.lineHeight))
let overviewTop = title.frame.maxY + 40
let overviewBottom = h - LayoutHelpers.vertMargins
let overviewWidth = textWidth
let maxOverviewHeight = overviewBottom - overviewTop
let textOverviewHeight = ceil(overview.sizeThatFits(CGSize(width: overviewWidth, height: 999)).height)
let overviewHeight = min(textOverviewHeight, maxOverviewHeight)
overview.frame = CGRect(x: LayoutHelpers.sideMargins,
y: overviewTop,
width: overviewWidth,
height: overviewHeight)
}
struct K {
static let itemWidth: CGFloat = round(UIScreen.main.bounds.width/4)
}
}
| mit | 049e248e64f2f51b8eb2fdb1addb27ae | 35.359116 | 176 | 0.608266 | 5.218874 | false | false | false | false |
bbheck/BHToastSwift | Pod/Classes/BHToast.swift | 1 | 12298 | //
// BHToast.swift
// Pods
//
// Created by Bruno Hecktheuer on 1/11/16.
//
//
import UIKit
/// The BHToast class defines a custom UIView with a message.
@available(iOS 8.0, *)
public class BHToast: UIView {
// MARK: - Properties
/// The parent UIView that shows the BHToast.
private let view: UIView
/// The display message.
public var message: String
/// The display imageView
public var imageView: UIImageView?
/// The BHToastOptions
private let options: BHToastOptions
/// The BHToast width (fixed 300.0).
private let width: CGFloat = 300.0
/// The UILabel message
internal let messageLabel = UILabel()
/// The timer that hide the BHToast.
private var timer = NSTimer()
// MARK: - Init methods
/**
Custom init method.
Create an instance of BHToast to attach in an UIView.
You should set a message and can add an image view to display.
- parameter view: The UIView that shows the BHToast.
- parameter message: The display message.
- parameter imageView: The display image view.
- parameter options: The BHToastOptions instance.
*/
public init(view: UIView? = nil,
message: String = "",
imageView: UIImageView? = nil,
options: BHToastOptions = BHToastOptions()) {
self.view = view ?? BHToastUtils.topViewController.view
self.message = message
self.imageView = imageView
self.options = options
super.init(frame: CGRectZero)
setupViewProperties()
}
@available(*, unavailable, message="required init is unavailable")
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Setup methods
/**
Configures view constraints and calls the other setup methods.
*/
private func setupProperties() {
addWidthConstraintToElement(self, rule: "\(width)")
addHeightConstraintToElement(self, rule: ">=\(options.minHeight)")
addHeightConstraintToElement(self, rule: "<=\(options.maxHeight)")
addConstraintFrom( // Align Center X
view, fromAttribute: .CenterX,
to: self, toAttribute: .CenterX
)
setupViewPosition()
setupLayerProperties()
if let _ = imageView {
setupImageView()
}
setupMessageLabel()
}
private func setupViewPosition() {
switch options.position {
case .Bottom:
addConstraintFrom( // Bottom Margin
view, fromAttribute: .Bottom,
to: self, toAttribute: .Bottom,
value: options.margin
)
case .Middle:
addConstraintFrom( // Align Center Y
view, fromAttribute: .CenterY,
to: self, toAttribute: .CenterY
)
case .Top:
addConstraintFrom( // Top Margin
self, fromAttribute: .Top,
to: view, toAttribute: .Top,
value: options.margin
)
}
}
/**
Sets the view properties.
*/
private func setupViewProperties() {
tag = BHToastViewTag
alpha = 0.0
backgroundColor = options.backgroundColor
translatesAutoresizingMaskIntoConstraints = false
}
/**
Sets the layer properties.
*/
private func setupLayerProperties() {
layer.borderWidth = options.borderWidth
layer.borderColor = options.borderColor.CGColor
layer.cornerRadius = options.cornerRadius
layer.masksToBounds = true
}
/**
Sets the UIImageView properties.
*/
private func setupImageView() {
addSubview(imageView!)
imageView!.translatesAutoresizingMaskIntoConstraints = false
addConstraintFrom( // Align Center Y
self, fromAttribute: .CenterY,
to: imageView!, toAttribute: .CenterY
)
if options.imagePosition == .Left {
addConstraintFrom( // Left Margin
imageView!, fromAttribute: .Left,
to: self, toAttribute: .Left,
value: options.contentInsets.left
)
} else {
addConstraintFrom( // Right Margin
self, fromAttribute: .Right,
to: imageView!, toAttribute: .Right,
value: options.contentInsets.right
)
}
addHeightConstraintToElement(
imageView!,
rule: "\(options.minHeight - ((options.contentInsets.top + options.contentInsets.bottom) / 2))"
)
addConstraintFrom( // Ratio Constraint
imageView!, fromAttribute: .Height,
to: imageView!, toAttribute: .Width,
multiplier: imageView!.frame.height / imageView!.frame.width
)
}
/**
Sets the message label properties.
*/
private func setupMessageLabel() {
messageLabel.font = options.messageFont
messageLabel.numberOfLines = 0
messageLabel.text = message
messageLabel.textAlignment = options.messageAlignment
messageLabel.textColor = options.messageColor
addSubview(messageLabel)
messageLabel.translatesAutoresizingMaskIntoConstraints = false
addConstraintFrom( // Top Margin
messageLabel, fromAttribute: .Top,
to: self, toAttribute: .Top,
value: options.contentInsets.top
)
addConstraintFrom( // Bottom Margin
self, fromAttribute: .Bottom,
to: messageLabel, toAttribute: .Bottom,
value: options.contentInsets.bottom
)
if imageView == nil {
addConstraintFrom( // Left Margin
messageLabel, fromAttribute: .Left,
to: self, toAttribute: .Left,
value: options.contentInsets.left
)
addConstraintFrom( // Right Margin
self, fromAttribute: .Right,
to: messageLabel, toAttribute: .Right,
value: options.contentInsets.right
)
} else {
addConstraintFrom( // Left Margin
messageLabel,
fromAttribute: .Left,
to: options.imagePosition == .Left ? imageView! : self,
toAttribute: options.imagePosition == .Left ? .Right : .Left,
value: options.contentInsets.left
)
addConstraintFrom( // Right Margin
options.imagePosition == .Right ? imageView! : self,
fromAttribute: options.imagePosition == .Right ? .Left : .Right,
to: messageLabel,
toAttribute: .Right,
value: options.contentInsets.right
)
}
}
// MARK: - Scheduled method
/**
Starts the timer that hide the BHToast.
*/
private func scheduledHideEvent() {
timer = NSTimer.scheduledTimerWithTimeInterval(
options.duration, target: self,
selector: "hide", userInfo: nil,
repeats: false
)
}
// MARK: - Private show method
/**
Shows the view with animation.
*/
private func showWithAnimation() {
view.addSubview(self)
setupProperties()
UIView.animateWithDuration(
options.animationDuration,
animations: { () -> Void in
self.alpha = 1.0
}, completion: { (finish) -> Void in
self.scheduledHideEvent()
}
)
}
// MARK: - Private hide method
/**
Hides the view with animation.
- parameter showAgain: The flag that checks if is necessary to show again the view.
*/
private func hideWithAnimation(completionHandler completionHandler: () -> Void = {}) {
UIView.animateWithDuration(
options.animationDuration,
animations: { () -> Void in
self.alpha = 0.0
}, completion: { (finish) -> Void in
self.removeFromSuperview()
self.timer.invalidate()
completionHandler()
}
)
}
// MARK: - Public methods
/**
Hides the BHToast with fade animation.
*/
public func hide() {
hideWithAnimation()
}
/**
Shows the BHToast with animation.
* If BHToast has already been added to parent view, dismiss the BHToast to show again.
* If some BHToast with BHToastViewTag already exists in parent view, dismiss it to show the new BHToast.
* Otherwise, just show the BHToast with fade animation.
*/
public func show() {
if isDescendantOfView(view) {
hideWithAnimation(completionHandler: { () -> Void in
self.showWithAnimation()
})
} else if let _view = view.viewWithTag(BHToastViewTag) as? BHToast {
_view.hideWithAnimation(completionHandler: { () -> Void in
self.showWithAnimation()
})
} else {
showWithAnimation()
}
}
// MARK: - Constraint methods
/**
Generic method to add a constraint.
- parameter: from: The "from" AnyObject.
- parameter: fromAttribute: The "from" NSLayoutAttribute.
- parameter: relatedBy: The NSLayoutRelation (default: .Equal)
- parameter: to: The "to" AnyObject.
- parameter: toAttribute: The "to" NSLayoutAttribute.
- parameter: multiplier: The multiplier to change the value (default: 1.0)
- parameter: value: The value set in the constraint (default: 0.0).
- parameter: priority: The constraint priority (default: 1000).
*/
private func addConstraintFrom(from: AnyObject,
fromAttribute: NSLayoutAttribute,
relatedBy: NSLayoutRelation = .Equal,
to: AnyObject,
toAttribute: NSLayoutAttribute,
multiplier: CGFloat = 1.0,
value: CGFloat = 0.0,
priority: UILayoutPriority = 1000) {
let constraint = NSLayoutConstraint(
item: from,
attribute: fromAttribute,
relatedBy: relatedBy,
toItem: to,
attribute: toAttribute,
multiplier: multiplier,
constant: value
)
constraint.priority = priority
view.addConstraint(constraint)
}
/**
Add height constraint.
- parameter element: AnyObject
- parameter rule: String (examples: "<=200", ">300", "200")
*/
private func addHeightConstraintToElement(element: AnyObject, rule: String) {
element.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:[element(\(rule))]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: [
"element": element
]
)
)
}
/**
Add width constraint
- parameter element: AnyObject
- parameter rule: String (examples: "<=200", ">300", "200")
*/
private func addWidthConstraintToElement(element: AnyObject, rule: String) {
element.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:[element(\(rule))]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: [
"element": element
]
)
)
}
}
| mit | 56de8f28860f784c1d14e747c0fb8db4 | 29.745 | 109 | 0.540657 | 5.527191 | false | false | false | false |
kshin/JetUnbox | Source/SignalProducer+Unbox.swift | 1 | 1070 | //
// SignalProducer+Unbox.swift
// Jet
//
// Created by Ivan Lisovyi on 4/23/17.
// Copyright © 2017 Ivan Lisovyi. All rights reserved.
//
import Foundation
import Jet
import ReactiveSwift
import Alamofire
import Unbox
public extension SignalProducer where Value == Response, Error == JetError {
@discardableResult
public func unboxObject<T: Unboxable>(queue: DispatchQueue? = nil, keyPath: String? = nil, options: JSONSerialization.ReadingOptions = .allowFragments) -> SignalProducer<T, JetError> {
return response(queue: queue,
responseSerializer: DataRequest.unboxObjectResponseSerializer(options: options, keyPath: keyPath))
}
@discardableResult
public func unboxArray<T: Unboxable>(queue: DispatchQueue? = nil, keyPath: String? = nil, options: JSONSerialization.ReadingOptions = .allowFragments) -> SignalProducer<[T], JetError> {
return response(queue: queue,
responseSerializer: DataRequest.unboxArrayResponseSerializer(options: options, keyPath: keyPath))
}
}
| mit | eeeb744304aaf34cbd4a4e46ccb27b57 | 37.178571 | 189 | 0.713751 | 4.668122 | false | false | false | false |
fedepo/phoneid_iOS | Pod/Classes/ui/views/controls/VerifyCodeControl.swift | 2 | 10720 | //
// VerifyCodeControl.swift
//
// phoneid_iOS
//
// Copyright 2015 phone.id - 73 knots, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class VerifyCodeControl: PhoneIdBaseView {
fileprivate(set) var placeholderView: UIView!
fileprivate(set) var codeText: NumericTextField!
fileprivate(set) var placeholderLabel: UILabel!
fileprivate(set) var activityIndicator: UIActivityIndicatorView!
fileprivate(set) var backButton: UIButton!
fileprivate(set) var statusImage: UIImageView!
var verificationCodeDidCahnge: ((_ code:String) -> Void)?
var requestVoiceCall: (() -> Void)?
var backButtonTapped: (() -> Void)?
let maxVerificationCodeLength = 6
fileprivate var timer: Timer!
override func setupSubviews() {
super.setupSubviews()
codeText = {
let codeText = NumericTextField(maxLength: maxVerificationCodeLength)
codeText.keyboardType = .numberPad
codeText.addTarget(self, action: #selector(VerifyCodeControl.textFieldDidChange(_:)), for: .editingChanged)
codeText.backgroundColor = UIColor.clear
return codeText
}()
placeholderLabel = {
let placeholderLabel = UILabel()
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: "______")
placeholderLabel.attributedText = applyCodeFieldStyle(attributedString)
return placeholderLabel
}()
activityIndicator = {
activityIndicator = UIActivityIndicatorView()
activityIndicator.activityIndicatorViewStyle = .whiteLarge
return activityIndicator
}()
statusImage = UIImageView()
placeholderView = {
let placeholderView = UIView()
placeholderView.layer.cornerRadius = 5
return placeholderView
}()
backButton = {
let backButton = UIButton()
let backButtonImage = UIImage(namedInPhoneId: "compact-back")?.withRenderingMode(.alwaysTemplate)
backButton.setImage(backButtonImage, for: UIControlState())
backButton.addTarget(self, action: #selector(VerifyCodeControl.backTapped(_:)), for: .touchUpInside)
backButton.tintColor = colorScheme.inputCodeBackbuttonNormal
return backButton
}()
let subviews: [UIView] = [placeholderView, placeholderLabel, codeText, activityIndicator, backButton, statusImage]
for (_, element) in subviews.enumerated() {
element.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(element)
}
}
deinit {
timer?.invalidate()
timer = nil
}
override func setupLayout() {
super.setupLayout()
var c: [NSLayoutConstraint] = []
c.append(NSLayoutConstraint(item: placeholderView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: placeholderView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: placeholderView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: placeholderView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: placeholderLabel, attribute: .centerX, relatedBy: .equal, toItem: placeholderView, attribute: .centerX, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: placeholderLabel, attribute: .centerY, relatedBy: .equal, toItem: placeholderView, attribute: .centerY, multiplier: 1, constant: 5))
c.append(NSLayoutConstraint(item: backButton, attribute: .centerY, relatedBy: .equal, toItem: placeholderView, attribute: .centerY, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: backButton, attribute: .left, relatedBy: .equal, toItem: placeholderView, attribute: .left, multiplier: 1, constant: 18))
c.append(NSLayoutConstraint(item: backButton, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: codeText, attribute: .centerX, relatedBy: .equal, toItem: placeholderLabel, attribute: .centerX, multiplier: 1, constant: 2))
c.append(NSLayoutConstraint(item: codeText, attribute: .centerY, relatedBy: .equal, toItem: placeholderView, attribute: .centerY, multiplier: 1, constant: -2))
c.append(NSLayoutConstraint(item: codeText, attribute: .width, relatedBy: .equal, toItem: placeholderLabel, attribute: .width, multiplier: 1, constant: 5))
c.append(NSLayoutConstraint(item: activityIndicator, attribute: .centerY, relatedBy: .equal, toItem: placeholderView, attribute: .centerY, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: activityIndicator, attribute: .right, relatedBy: .equal, toItem: placeholderView, attribute: .right, multiplier: 1, constant: -5))
c.append(NSLayoutConstraint(item: statusImage, attribute: .centerX, relatedBy: .equal, toItem: activityIndicator, attribute: .centerX, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: statusImage, attribute: .centerY, relatedBy: .equal, toItem: activityIndicator, attribute: .centerY, multiplier: 1, constant: 0))
self.addConstraints(c)
}
override func localizeAndApplyColorScheme() {
super.localizeAndApplyColorScheme()
placeholderView.backgroundColor = colorScheme.inputCodeBackground
codeText.textColor = colorScheme.inputCodeText
codeText.accessibilityLabel = localizedString("accessibility.verification.input");
backButton.accessibilityLabel = localizedString("accessibility.button.title.back");
placeholderLabel.textColor = colorScheme.inputCodePlaceholder
activityIndicator.color = colorScheme.activityIndicatorCode
self.needsUpdateConstraints()
}
fileprivate func applyCodeFieldStyle(_ input: NSAttributedString) -> NSAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(attributedString: input)
let range: NSRange = NSMakeRange(0, attributedString.length)
attributedString.addAttribute(NSAttributedStringKey.kern, value: 8, range: range)
if (attributedString.length > 2) {
let range: NSRange = NSMakeRange(2, 1)
attributedString.addAttribute(NSAttributedStringKey.kern, value: 24, range: range)
}
attributedString.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "Menlo", size: 22)!, range: range)
return attributedString
}
@objc func textFieldDidChange(_ textField: UITextField) {
textField.attributedText = applyCodeFieldStyle(textField.attributedText!)
if (textField.text!.utf16.count == maxVerificationCodeLength) {
activityIndicator.startAnimating()
backButtonEnable(false)
} else {
activityIndicator.stopAnimating()
phoneIdService.abortCall()
statusImage.isHidden = true
backButtonEnable(true)
}
self.verificationCodeDidCahnge?(textField.text!)
}
@objc func backTapped(_ sender: UIButton) {
backButtonTapped?()
}
func indicateVerificationFail() {
activityIndicator.stopAnimating()
statusImage.image = UIImage(namedInPhoneId: "icon-ko")?.withRenderingMode(.alwaysTemplate)
statusImage.tintColor = colorScheme.fail
statusImage.isHidden = false
backButtonEnable(true)
}
func backButtonEnable(_ value: Bool) {
backButton.isEnabled = value
backButton.tintColor = value ? colorScheme.inputCodeBackbuttonNormal : colorScheme.inputCodeBackbuttonDisabled
}
func indicateVerificationSuccess(_ completion: (() -> Void)?) {
activityIndicator.stopAnimating()
statusImage.image = UIImage(namedInPhoneId: "icon-ok")?.withRenderingMode(.alwaysTemplate)
statusImage.tintColor = colorScheme.success;
statusImage.isHidden = false
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: [], animations: {
() -> Void in
self.statusImage.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
}) {
(_) -> Void in
self.statusImage.transform = CGAffineTransform(scaleX: 1, y: 1)
completion?()
}
}
func reset() {
codeText.text = ""
codeText.inputAccessoryView = nil
codeText.reloadInputViews()
textFieldDidChange(codeText)
timer?.invalidate()
}
@discardableResult
override func resignFirstResponder() -> Bool {
return codeText.resignFirstResponder()
}
@discardableResult
override func becomeFirstResponder() -> Bool {
return codeText.becomeFirstResponder()
}
func setupHintTimer() {
timer?.invalidate()
let fireDate = Date(timeIntervalSinceNow: 30)
timer = Timer(fireAt: fireDate, interval: 0, target: self, selector: #selector(VerifyCodeControl.timerFired), userInfo: nil, repeats: false)
RunLoop.main.add(timer!, forMode: RunLoopMode.defaultRunLoopMode)
}
@objc func timerFired() {
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
let callMeButton = UIBarButtonItem(title: localizedString("button.title.call.me"), style: .plain, target: self, action: #selector(VerifyCodeControl.callMeButtonTapped))
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolBar.items = [space, callMeButton]
codeText.resignFirstResponder()
codeText.inputAccessoryView = toolBar
codeText.becomeFirstResponder()
}
@objc func callMeButtonTapped() {
requestVoiceCall?()
}
}
| apache-2.0 | eca8c9709f70d5772bad787aaee72184 | 41.039216 | 176 | 0.689272 | 5.056604 | false | false | false | false |
naturaln0va/RAScrollablePickerView | ColorPickerExample/ViewController.swift | 1 | 2017 | //
// Created by Ryan Ackermann on 7/10/15.
// Copyright (c) 2015 Ryan Ackermann. All rights reserved.
//
import UIKit
class ViewController: UIViewController, RAScrollablePickerViewDelegate {
@IBOutlet weak var colorPreView: UIView!
@IBOutlet weak var huePicker: RAScrollablePickerView!
@IBOutlet weak var saturationPicker: RAScrollablePickerView!
@IBOutlet weak var brightnessPicker: RAScrollablePickerView!
override func viewDidLoad() {
super.viewDidLoad()
let colors: [UIColor] = [.systemBlue, .systemOrange, .systemYellow]
let startColor = colors.randomElement() ?? .systemPink
huePicker.delegate = self
huePicker.set(color: startColor)
saturationPicker.delegate = self
saturationPicker.type = .saturation
saturationPicker.hueValueForPreview = huePicker.value
saturationPicker.set(color: startColor)
brightnessPicker.delegate = self
brightnessPicker.type = .brightness
brightnessPicker.hueValueForPreview = huePicker.value
brightnessPicker.set(color: startColor)
colorPreView.backgroundColor = UIColor(hue: huePicker.value, saturation: saturationPicker.value, brightness: brightnessPicker.value, alpha: 1)
}
func valueChanged(_ value: CGFloat, type: PickerType) {
switch type {
case .hue:
colorPreView.backgroundColor = UIColor(hue: value, saturation: saturationPicker.value, brightness: brightnessPicker.value, alpha: 1)
saturationPicker.hueValueForPreview = value
brightnessPicker.hueValueForPreview = value
case .saturation:
colorPreView.backgroundColor = UIColor(hue: huePicker.value, saturation: value, brightness: brightnessPicker.value, alpha: 1)
case .brightness:
colorPreView.backgroundColor = UIColor(hue: huePicker.value, saturation: saturationPicker.value, brightness: value, alpha: 1)
}
}
}
| apache-2.0 | 5c4ceecdda38f7632ec6405f875d5dae | 39.34 | 150 | 0.69063 | 4.802381 | false | false | false | false |
jasnig/DouYuTVMutate | DouYuTVMutate/DouYuTV/Profile/Controller/ProfileController.swift | 1 | 4968 |
//
// ProfileController.swift
// DouYuTVMutate
//
// Created by ZeroJ on 16/7/19.
// Copyright © 2016年 ZeroJ. All rights reserved.
//
import UIKit
class ProfileController: BaseViewController {
var delegator: CommonTableViewDelegator!
lazy var profileHeadView: ProfileHeadView = {
let profileHeadView = ProfileHeadView.LoadProfileHeadViewFormLib()
profileHeadView.didTapImageViewHandler = {[weak self] imageView in
guard let `self` = self else { return }
/// 弹出图片浏览器
let photoModel = PhotoModel(localImage: imageView.image, sourceImageView: nil)
let photoBrowser = PhotoBrowser(photoModels: [photoModel])
photoBrowser.hideToolBar = true
photoBrowser.show(inVc: self, beginPage: 0)
}
return profileHeadView
}()
var headView = UIView(frame: CGRect(x: 0, y: 0, width: Constant.screenWidth, height: 360))
lazy var tableView: UITableView = {
let tableView = UITableView(frame: CGRectZero, style: .Plain)
return tableView
}()
var data: [CommonTableSectionData] = [] {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "个人中心"
view.addSubview(tableView)
headView.addSubview(profileHeadView)
tableView.tableHeaderView = headView
setupData()
delegator = CommonTableViewDelegator(tableView: tableView, data: {[unowned self] () -> [CommonTableSectionData] in
return self.data
})
tableView.delegate = delegator
tableView.dataSource = delegator
}
deinit {
print("xiaohui--------")
}
func setupData() {
let row1Data = TypedCellDataModel(name: "开播提示", iconName: "1")
let row2Data = TypedCellDataModel(name: "票务查询", iconName: "1")
let row3Data = TypedCellDataModel(name: "设置选项", iconName: "1")
let row4Data = TypedCellDataModel(name: "手游中心", iconName: "1", detailValue: "玩游戏领鱼丸")
let row1 = CellBuilder<TitleWithLeftImageCell>(dataModel: row1Data, cellDidClickAction: {
UsefulPickerView.showDatePicker(row1Data.name, doneAction: { (selectedDate) in
EasyHUD.showHUD("提示时间是---\(selectedDate)", autoHide: true, afterTime: 1.0)
})
})
let row2 = CellBuilder<TitleWithLeftImageCell>(dataModel: row2Data, cellDidClickAction: {
UsefulPickerView.showSingleColPicker(row2Data.name, data: ["是", "否"], defaultSelectedIndex: 0, doneAction: { (selectedIndex, selectedValue) in
EasyHUD.showHUD("选择了---\(selectedValue)", autoHide: true, afterTime: 1.0)
})
})
let row3 = CellBuilder<TitleWithLeftImageCell>(dataModel: row3Data, cellDidClickAction: {[unowned self] in
self.showViewController(SettingController(), sender: nil)
})
let row4 = CellBuilder<TitleWithLeftImageAndDetailCell>(dataModel: row4Data, cellHeight: 50, cellDidClickAction: {[unowned self] in
self.showViewController(TestController(), sender: nil)
})
let section1 = CommonTableSectionData(headerTitle: nil, footerTitle: nil, headerHeight: 10, footerHeight: nil, rows: [row1, row2, row3])
let section2 = CommonTableSectionData(headerTitle: nil, footerTitle: nil, headerHeight: 10, footerHeight: 10, rows: [row4])
data = [section1, section2]
}
override func addConstraints() {
super.addConstraints()
tableView.snp_makeConstraints { (make) in
make.leading.equalTo(view)
make.top.equalTo(view)
make.trailing.equalTo(view)
make.bottom.equalTo(view)
}
profileHeadView.snp_makeConstraints { (make) in
make.leading.equalTo(headView)
make.top.equalTo(headView)
make.trailing.equalTo(headView)
make.bottom.equalTo(headView)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ProfileController: UITableViewDataSource, UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: nil)
cell.textLabel?.text = "ceshi"
return cell
}
}
| mit | 0dcc2e1f863f5afbb603be045252e55f | 33.118881 | 154 | 0.623898 | 4.727713 | false | false | false | false |
nickfrey/knightsapp | Newman Knights/WebViewController.swift | 1 | 2982 | //
// WebViewController.swift
// Newman Knights
//
// Created by Nick Frey on 12/20/15.
// Copyright © 2015 Nick Frey. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: FetchedViewController, WKNavigationDelegate {
fileprivate let initialURL: URL?
fileprivate var hasLoaded: Bool = false
fileprivate(set) weak var webView: WKWebView?
init(URL: URL?) {
self.initialURL = URL
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(sharePressed))
let webView = WKWebView()
webView.isHidden = true
webView.navigationDelegate = self
self.view.addSubview(webView)
self.view.sendSubview(toBack: webView)
self.webView = webView
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.webView?.frame = self.view.bounds
}
override func viewDidLoad() {
super.viewDidLoad()
self.fetch()
}
// MARK: Sharing
func sharableURL() -> URL? {
return self.initialURL
}
@objc func sharePressed() {
guard let sharableURL = self.sharableURL()
else { return }
let viewController = UIActivityViewController(activityItems: [sharableURL], applicationActivities: nil)
viewController.modalPresentationStyle = .popover
viewController.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
viewController.popoverPresentationController?.permittedArrowDirections = .up
self.present(viewController, animated: true, completion: nil)
}
// MARK: Fetched View Controller
override func fetch() {
super.fetch()
if let initialURL = self.initialURL {
self.webView?.load(URLRequest(url: initialURL))
}
}
override func fetchFinished(_ error: Error?) {
super.fetchFinished(error)
if !self.hasLoaded {
if error == nil {
self.hasLoaded = true
self.webView?.isHidden = false
} else {
self.webView?.isHidden = true
}
}
}
// MARK: WKNavigationDelegate
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation) {
self.fetchFinished(nil)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
self.fetchFinished(error)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation, withError error: Error) {
self.fetchFinished(error)
}
}
| mit | 13b5911fe9579bed78d91a75ea184a12 | 29.111111 | 141 | 0.629319 | 5.113208 | false | false | false | false |
iOS-mamu/SS | P/Library/Eureka/EurekaTests/ImageRowTests.swift | 1 | 3373 | //
// ImageRowTests.swift
// Eureka
//
// Created by Florian Fittschen on 13/01/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import XCTest
@testable import Eureka
class ImageRowTests: XCTestCase {
var formVC = FormViewController()
var availableSources: ImageRowSourceTypes {
var result: ImageRowSourceTypes = []
if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
result.insert(ImageRowSourceTypes.PhotoLibrary)
}
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
result.insert(ImageRowSourceTypes.Camera)
}
if UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
result.insert(ImageRowSourceTypes.SavedPhotosAlbum)
}
return result
}
override func setUp() {
super.setUp()
let form = Form()
form +++ Section()
<<< ImageRow("DefaultImageRow") {
$0.title = $0.tag
// Default sourceTypes == .All
}
<<< ImageRow("SingleSourceImageRow") { (row: ImageRow) in
row.title = row.tag
row.sourceTypes = .Camera
}
<<< ImageRow("TwoSourcesImageRow") { (row: ImageRow) in
row.title = row.tag
row.sourceTypes = [.SavedPhotosAlbum, .PhotoLibrary]
}
formVC.form = form
// load the view to test the cells
formVC.view.frame = CGRect(x: 0, y: 0, width: 375, height: 3000)
formVC.tableView?.frame = formVC.view.frame
}
override func tearDown() {
super.tearDown()
}
func testEmptyImageRowSourceTypes() {
let result = ImageRowSourceTypes()
XCTAssertTrue(result.isEmpty)
XCTAssertFalse(result.contains(.PhotoLibrary))
XCTAssertFalse(result.contains(.Camera))
XCTAssertFalse(result.contains(.SavedPhotosAlbum))
}
func testImagePickerControllerSourceTypeRawValue() {
XCTAssert(UIImagePickerControllerSourceType.PhotoLibrary.rawValue == ImageRowSourceTypes.PhotoLibrary.imagePickerControllerSourceTypeRawValue)
XCTAssert(UIImagePickerControllerSourceType.Camera.rawValue == ImageRowSourceTypes.Camera.imagePickerControllerSourceTypeRawValue)
XCTAssert(UIImagePickerControllerSourceType.SavedPhotosAlbum.rawValue == ImageRowSourceTypes.SavedPhotosAlbum.imagePickerControllerSourceTypeRawValue)
}
func testImageRow() {
guard let defaultImageRow = formVC.form.rowByTag("DefaultImageRow") as? ImageRow else {
XCTFail()
return
}
guard let singleSourceImageRow = formVC.form.rowByTag("SingleSourceImageRow") as? ImageRow else {
XCTFail()
return
}
guard let twoSourcesImageRow = formVC.form.rowByTag("TwoSourcesImageRow") as? ImageRow else {
XCTFail()
return
}
XCTAssert(defaultImageRow.sourceTypes == ImageRowSourceTypes.All)
XCTAssert(singleSourceImageRow.sourceTypes == ImageRowSourceTypes.Camera)
XCTAssert(twoSourcesImageRow.sourceTypes == ImageRowSourceTypes([ImageRowSourceTypes.SavedPhotosAlbum, ImageRowSourceTypes.PhotoLibrary]))
}
}
| mit | 6b75b6daea836ed80e11ba696b8b08e3 | 33.408163 | 158 | 0.638197 | 5.773973 | false | true | false | false |
luanlzsn/pos | pos/Classes/Ant/AntDefault.swift | 1 | 1426 | //
// LeomanDefault.swift
// MoFan
//
// Created by luan on 2016/12/8.
// Copyright © 2016年 luan. All rights reserved.
//
import Foundation
import UIKit
import SDWebImage
import YYCategories
func AntLog<N>(message:N,fileName:String = #file,methodName:String = #function,lineNumber:Int = #line){
#if DEBUG
print("类\(fileName as NSString)的\(methodName)方法第\(lineNumber)行:\(message)");
#endif
}
let kWindow = UIApplication.shared.keyWindow
let kScreenBounds = UIScreen.main.bounds
let kScreenWidth = kScreenBounds.width
let kScreenHeight = kScreenBounds.height
let MainColor = Common.colorWithHexString(colorStr: "80D3CB")
let LeomanManager = AntSingleton.sharedInstance
let kIphone4 = kScreenHeight == 480
let kIpad = UIDevice.current.userInterfaceIdiom == .pad
let kAppDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
let kAppVersion_URL = "http://itunes.apple.com/lookup?id=1107512125"//获取版本信息
let kAppDownloadURL = "https://itunes.apple.com/cn/app/id1107512125"//下载地址
let kUserName = "kUserName"
let kPassWord = "kPassWord"
let kAddShopCartSuccess = "kAddShopCartSuccess"
struct Platform {
static let isSimulator: Bool = {
var isSim = false
#if arch(i386) || arch(x86_64)
isSim = true
#endif
return isSim
}()
}
typealias ConfirmBlock = (_ value: Any) ->()
typealias CancelBlock = () ->()
| mit | aa14d0d4ac1a98bbe90f67fc00309dcb | 26.82 | 103 | 0.718907 | 3.631854 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/PhotoLibrary/View/PhotoLibraryAlbumsTableView.swift | 1 | 5449 | import UIKit
final class PhotoLibraryAlbumsTableView: UIView, UITableViewDataSource, UITableViewDelegate {
// MARK: - Subviews
private let topSeparator = UIView()
private let tableView = UITableView(frame: .zero, style: .plain)
// MARK: - Data
private var cellDataList = [PhotoLibraryAlbumCellData]()
private var selectedAlbumId: String?
private let cellId = "AlbumCell"
private var cellLabelFont: UIFont?
private var cellBackgroundColor: UIColor?
private var cellDefaultLabelColor: UIColor?
private var cellSelectedLabelColor: UIColor?
private let separatorHeight: CGFloat = 1
private let minInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: .zero)
topSeparator.backgroundColor = UIColor.RGB(red: 215, green: 215, blue: 215)
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .none
tableView.rowHeight = 60
tableView.alwaysBounceVertical = false
tableView.register(PhotoLibraryAlbumsTableViewCell.self, forCellReuseIdentifier: cellId)
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
}
addSubview(tableView)
addSubview(topSeparator)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - PhotoLibraryAlbumsTableView
func setCellDataList(_ cellDataList: [PhotoLibraryAlbumCellData], completion: @escaping () -> ()) {
self.cellDataList = cellDataList
tableView.reloadData()
// AI-7770: table view's size can be calculated incorrectly right after reloadData
DispatchQueue.main.async(execute: completion)
}
func selectAlbum(withId id: String) {
let indexPathsToReload = [selectedAlbumId, id].compactMap { albumId in
cellDataList.firstIndex(where: { $0.identifier == albumId }).flatMap { IndexPath(row: $0, section: 0) }
}
selectedAlbumId = id
tableView.reloadRows(at: indexPathsToReload, with: .fade)
}
func setTableViewBackgroundColor(_ color: UIColor) {
tableView.backgroundColor = color
}
func setCellLabelFont(_ font: UIFont) {
cellLabelFont = font
}
func setCellBackgroundColor(_ color: UIColor) {
cellBackgroundColor = color
}
func setTopSeparatorColor(_ color: UIColor) {
topSeparator.backgroundColor = color
}
func setCellDefaultLabelColor(_ color: UIColor) {
cellDefaultLabelColor = color
}
func setCellSelectedLabelColor(_ color: UIColor) {
cellSelectedLabelColor = color
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellDataList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? PhotoLibraryAlbumsTableViewCell else {
return UITableViewCell()
}
let cellData = cellDataList[indexPath.row]
cell.setCellData(cellData)
cell.isSelected = (cellData.identifier == selectedAlbumId)
if let cellLabelFont = cellLabelFont {
cell.setLabelFont(cellLabelFont)
}
if let cellBackgroundColor = cellBackgroundColor {
cell.backgroundColor = cellBackgroundColor
}
if let cellDefaultLabelColor = cellDefaultLabelColor {
cell.setDefaultLabelColor(cellDefaultLabelColor)
}
if let cellSelectedLabelColor = cellSelectedLabelColor {
cell.setSelectedLabelColor(cellSelectedLabelColor)
}
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cellData = cellDataList[indexPath.row]
cellData.onSelect()
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - UIView
override func sizeThatFits(_ size: CGSize) -> CGSize {
let tableViewSize = tableView.sizeThatFits(size)
let tableVerticalInsets = minInsets.top + minInsets.bottom
return CGSize(
width: tableViewSize.width,
height: min(size.height, tableViewSize.height + separatorHeight + tableVerticalInsets)
)
}
override func layoutSubviews() {
super.layoutSubviews()
topSeparator.layout(
left: bounds.left,
right: bounds.right,
top: bounds.top,
height: separatorHeight
)
tableView.layout(
left: bounds.left,
right: bounds.right,
top: topSeparator.bottom,
bottom: bounds.bottom
)
tableView.contentInset = UIEdgeInsets(
top: minInsets.top,
left: minInsets.left,
bottom: max(minInsets.bottom, paparazzoSafeAreaInsets.bottom),
right: minInsets.right
)
}
}
| mit | eed4a4bfac06d0617e45f1f9841b539b | 31.434524 | 137 | 0.626537 | 5.39505 | false | false | false | false |
kongtomorrow/ProjectEuler-Swift | ProjectEuler/p9.swift | 1 | 961 | //
// p9.swift
// ProjectEuler
//
// Created by Ken Ferry on 8/7/14.
// Copyright (c) 2014 Understudy. All rights reserved.
//
import Foundation
extension Problems {
func p9() -> Int {
/*
Special Pythagorean triplet
Problem 9
Published on 25 January 2002 at 06:00 pm [Server Time]
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a**2 + b**2 = c**2
For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
*/
let sum = 1000
for a in 1...sum-2 {
for b in 1...a {
let c = sum - (a + b)
if a*a + b*b == c*c {
(a,b,c)*** // (375, 200, 425)
return (a*b*c) // 31875000
}
}
}
return 0
}
} | mit | 4d4260ba105fb4fdbca18e93c4f2f1f5 | 24.315789 | 86 | 0.454735 | 3.612782 | false | false | false | false |
ArtisOracle/libSwiftCal | libSwiftCal/ExceptionDate.swift | 1 | 3557 | //
// ExceptionDate.swift
// libSwiftCal
//
// Created by Stefan Arambasich on 2/25/15.
//
// Copyright (c) 2015 Stefan Arambasich. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/**
DATE-TIME exception for recurring events, to-dos, journal entries, or time zone definitions.
*/
public class ExceptionDate: ReminderProperty {
/// The value of the date to exclude
var date = [NSDate]()
/// The value of the datetime to exclude
var dateTime = [NSDate]()
/// The preferred means of accessing the date array elements
public var value: [NSDate] {
get {
if self.date.count > 0 {
return self.date
}
return self.dateTime
} set {
if self.date.count > 0 {
self.date = newValue
} else {
self.dateTime = newValue
}
}
}
public required init() {
super.init()
}
private func isEmpty() -> Bool {
return self.key == nil || self.value.count == 0
}
// MARK: - iCalendarSerializable
public override func serializeToiCal() -> String {
if self.isEmpty() { return String.Empty }
var result = String(kEXDATE)
if self.parameters.count > 0 {
result += kSEMICOLON
result += self.serializeParameters()
}
result += kCOLON
if self.date.count > 0 {
for d in self.date {
if d !== self.date.first { result += kCOMMA }
result += d.toString(dateFormat: DateFormats.ISO8601Date)
}
} else if self.dateTime.count > 0 {
for d in self.dateTime {
if d !== self.dateTime.first { result += kCOMMA }
result += d.toString(timezone: NSTimeZone(forSecondsFromGMT: 0))
}
}
result.foldiCalendarString()
result += kCRLF
return result
}
// MARK: - NSCoding
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Serializable
public required init(dictionary: [String : AnyObject]) {
super.init(dictionary: dictionary)
}
public override var serializationKeys: [String] {
get {
return super.serializationKeys + [kDATE, kDATE_TIME]
}
}
}
| mit | 629c647bcba92f33e628820255963ab4 | 30.758929 | 96 | 0.593478 | 4.583763 | false | false | false | false |
mbeloded/discountsPublic | discounts/Classes/UI/DiscountView/DiscountView.swift | 1 | 1245 | //
// DiscountView.swift
// discounts
//
// Created by Michael Bielodied on 9/10/14.
// Copyright (c) 2014 Michael Bielodied. All rights reserved.
//
import Foundation
import UIKit
import RSBarcodes_Swift
import AVFoundation
class DiscountView: UIView {
@IBOutlet weak private var codeImageView: UIImageView!
@IBOutlet weak private var productImageLogoView: UIImageView!
@IBOutlet weak private var productNameLabel: UILabel!
func generateCode(_ productIndex:Int)
{
let companyObject:CompanyObject = DiscountsManager.sharedInstance.discountsCategoryArrayData[productIndex]
productNameLabel.text = companyObject.companyName
productImageLogoView.image = UIImage(named: companyObject.imageName)
let codeImage:UIImage = RSCode128Generator(codeTable: .a).generateCode(companyObject.discountCode, machineReadableCodeObjectType: AVMetadataObjectTypeCode128Code)!
codeImageView.image = codeImage
codeImageView.center = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
codeImageView.frame = CGRect(x: codeImageView.frame.origin.x, y: codeImageView.frame.origin.y, width: codeImage.size.width, height: codeImage.size.height)
}
}
| gpl-3.0 | 179722bea9c772cdb7174f0d52cdc563 | 36.727273 | 171 | 0.747791 | 4.399293 | false | false | false | false |
justin999/gitap | gitap/User.swift | 1 | 1873 | //
// User.swift
// gitap
//
// Created by Koichi Sato on 1/5/17.
// Copyright © 2017 Koichi Sato. All rights reserved.
//
import Foundation
/*
"user": {
"login": "octocat",
"id": 1,
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_id": "",
"url": "https://api.github.com/users/octocat",
"html_url": "https://github.com/octocat",
"followers_url": "https://api.github.com/users/octocat/followers",
"following_url": "https://api.github.com/users/octocat/following{/other_user}",
"gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
"organizations_url": "https://api.github.com/users/octocat/orgs",
"repos_url": "https://api.github.com/users/octocat/repos",
"events_url": "https://api.github.com/users/octocat/events{/privacy}",
"received_events_url": "https://api.github.com/users/octocat/received_events",
"type": "User",
"site_admin": false
},
*/
struct User: JSONDecodable {
let id: Int
let loginName: String
init(json: Any) throws {
guard let dictionary = json as? [String : Any] else {
throw JSONDecodeError.invalidFormat(json: json)
}
do {
self.id = try Utils.getValue(from: dictionary, with: "id")
self.loginName = try Utils.getValue(from: dictionary, with: "login")
} catch {
throw error
}
}
}
struct ApiResponseData: JSONDecodable {
let responseString: String
init(json: Any) throws {
guard let dataString = json as? String else {
throw JSONDecodeError.invalidFormat(json: json)
}
self.responseString = dataString
}
}
| mit | 50cba7574751d905f06bbbd4a0c9c935 | 30.728814 | 83 | 0.619124 | 3.59309 | false | false | false | false |
openhab/openhab.ios | openHABWatch Extension/openHABWatch Extension/Model/ObservableOpenHABDataObject.swift | 1 | 2445 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import Combine
import Foundation
import OpenHABCore
final class ObservableOpenHABDataObject: DataObject, ObservableObject {
static let shared = ObservableOpenHABDataObject()
var openHABVersion: Int = 2
let objectWillChange = PassthroughSubject<Void, Never>()
let objectRefreshed = PassthroughSubject<Void, Never>()
@UserDefaultsBacked(key: "rootUrl", defaultValue: "")
var openHABRootUrl: String {
willSet {
objectWillChange.send()
}
}
@UserDefaultsBacked(key: "localUrl", defaultValue: "")
var localUrl: String {
willSet {
objectWillChange.send()
}
}
@UserDefaultsBacked(key: "remoteUrl", defaultValue: "")
var remoteUrl: String {
willSet {
objectWillChange.send()
}
}
@UserDefaultsBacked(key: "sitemapName", defaultValue: "")
var sitemapName: String {
willSet {
objectWillChange.send()
}
}
@UserDefaultsBacked(key: "username", defaultValue: "")
var openHABUsername: String {
willSet {
objectWillChange.send()
}
}
@UserDefaultsBacked(key: "password", defaultValue: "")
var openHABPassword: String {
willSet {
objectWillChange.send()
}
}
@UserDefaultsBacked(key: "ignoreSSL", defaultValue: true)
var ignoreSSL: Bool {
willSet {
objectWillChange.send()
NetworkConnection.shared.serverCertificateManager.ignoreSSL = newValue
}
}
@UserDefaultsBacked(key: "alwaysSendCreds", defaultValue: false)
var openHABAlwaysSendCreds: Bool {
willSet {
objectWillChange.send()
}
}
@UserDefaultsBacked(key: "haveReceivedAppContext", defaultValue: false)
var haveReceivedAppContext: Bool {
didSet {
objectRefreshed.send()
}
}
}
extension ObservableOpenHABDataObject {
convenience init(openHABRootUrl: String) {
self.init()
self.openHABRootUrl = openHABRootUrl
}
}
| epl-1.0 | 99649edd910727a210038f87b6a7877e | 25.010638 | 82 | 0.640082 | 4.666031 | false | false | false | false |
jacobwhite/firefox-ios | Client/Frontend/Accessors/NewTabAccessors.swift | 10 | 2394 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
/// Accessors to find what a new tab should do when created without a URL.
struct NewTabAccessors {
static let PrefKey = PrefsKeys.KeyNewTab
static let Default = NewTabPage.topSites
static func getNewTabPage(_ prefs: Prefs) -> NewTabPage {
guard let raw = prefs.stringForKey(PrefKey) else {
return Default
}
let option = NewTabPage(rawValue: raw) ?? Default
// Check if the user has chosen to open a homepage, but no homepage is set,
// then use the default.
if option == .homePage && HomePageAccessors.getHomePage(prefs) == nil {
return Default
}
return option
}
}
/// Enum to encode what should happen when the user opens a new tab without a URL.
enum NewTabPage: String {
case blankPage = "Blank"
case homePage = "HomePage"
case topSites = "TopSites"
case bookmarks = "Bookmarks"
case history = "History"
case readingList = "ReadingList"
var settingTitle: String {
switch self {
case .blankPage:
return Strings.SettingsNewTabBlankPage
case .homePage:
return Strings.SettingsNewTabHomePage
case .topSites:
return Strings.SettingsNewTabTopSites
case .bookmarks:
return Strings.SettingsNewTabBookmarks
case .history:
return Strings.SettingsNewTabHistory
case .readingList:
return Strings.SettingsNewTabReadingList
}
}
var homePanelType: HomePanelType? {
switch self {
case .topSites:
return HomePanelType.topSites
case .bookmarks:
return HomePanelType.bookmarks
case .history:
return HomePanelType.history
case .readingList:
return HomePanelType.readingList
default:
return nil
}
}
var url: URL? {
guard let homePanel = self.homePanelType else {
return nil
}
return homePanel.localhostURL as URL
}
static let allValues = [blankPage, topSites, bookmarks, history, readingList, homePage]
}
| mpl-2.0 | 8b2fa29bd48d9fc21558b4e375541a29 | 30.090909 | 91 | 0.633668 | 4.966805 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.