repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
urbn/URBNSwiftyConvenience | refs/heads/master | Sources/URBNSwiftyConvenience/DateConvenience.swift | mit | 1 | //
// DateConvenience.swift
// Pods
//
// Created by Jason Grandelli on 11/14/16.
//
//
import Foundation
public extension Date {
// MARK: Units
static func monthSymbols() -> [String] {
return DateFormatter().monthSymbols
}
static func monthSymbol(month: Int) -> String? {
guard month < monthSymbols().count else { return nil }
return monthSymbols()[month]
}
func components(inTimeZone timeZone: TimeZone = TimeZone.autoupdatingCurrent) -> DateComponents {
return Calendar.autoupdatingCurrent.dateComponents(in: timeZone, from: self)
}
// MARK: Date Creation
func dateByAdding(years: Int? = nil, months: Int? = nil, weeks: Int? = nil, days:Int? = nil, hours: Int? = nil, minutes: Int? = nil, seconds: Int? = nil) -> Date? {
let components = DateComponents(year: years, month: months, day: days, hour: hours, minute: minutes, second: seconds)
return Calendar.autoupdatingCurrent.date(byAdding: components, to: self)
}
static func dateFrom(year: Int, month: Int, day: Int, hour: Int? = nil, minute: Int? = nil, second: Int? = nil) -> Date? {
let components = DateComponents(year: year, month: month, day: day, hour: hour, minute: minute, second: second)
return Calendar.autoupdatingCurrent.date(from: components)
}
static func dateFromString(_ string: String, format: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.date(from: string)
}
// MARK: Display
func string(withFormat format: String, localized: Bool = true) -> String? {
let formatter = DateFormatter()
var dateFormat = format
if localized {
guard let localeFormat = DateFormatter.dateFormat(fromTemplate: format, options: 0, locale: Locale.autoupdatingCurrent) else {
return nil
}
dateFormat = localeFormat
}
formatter.dateFormat = dateFormat
return formatter.string(from: self)
}
}
// Stupid Tech debt
@objc public class DateCompat: NSObject {
@objc public static func dateByAddingYears(_ years: Int, toDate date: Date?) -> Date? {
return date?.dateByAdding(years: years)
}
@objc public static func dayOfMothForDate(_ date: Date?) -> Int {
return date?.components().day ?? 0
}
@objc public static func yearForDate(_ date: Date?) -> Int {
return date?.components().year ?? 0
}
@objc public static func monthForDate(_ date: Date?) -> Int {
return date?.components().month ?? 0
}
@objc public static func dateFrom(year: Int, month: Int, day: Int) -> Date? {
return Date.dateFrom(year: year, month: month, day: day)
}
@objc public static func dateFrom(year: Int, month: Int, day: Int, hour: Int) -> Date? {
return Date.dateFrom(year: year, month: month, day: day, hour: hour)
}
@objc public static func monthSymbol(index: Int) -> String? {
return Date.monthSymbol(month: index)
}
@objc public static func stringFromDate(_ date: Date?, withFormat format: String, localized: Bool) -> String? {
return date?.string(withFormat: format, localized: localized)
}
}
| 8ddf813560a2987739957f54f2d0da8b | 32.959596 | 168 | 0.621059 | false | false | false | false |
moonrailgun/OpenCode | refs/heads/master | OpenCode/Classes/RepositoryDetail/View/RepoInfoView.swift | gpl-2.0 | 1 | //
// RepositoryInfoBlock.swift
// OpenCode
//
// Created by 陈亮 on 16-5-8.
// Copyright (c) 2016年 moonrailgun. All rights reserved.
//
import UIKit
class RepoInfoView: UIView {
var infoNameLabel:UILabel!
var infoValueLabel:UILabel!
init(frame: CGRect, name:String,value:Int) {
super.init(frame: frame)
self.backgroundColor = UIColor.whiteColor()
infoValueLabel = UILabel(frame: CGRect(x: 0, y: 2, width: frame.width, height: 20))
infoValueLabel.text = value.description
infoValueLabel.font = UIFont.systemFontOfSize(18)
infoValueLabel.textAlignment = .Center
infoNameLabel = UILabel(frame: CGRect(x: 0, y: 20, width: frame.width, height: 18))
infoNameLabel.text = name
infoNameLabel.font = UIFont.systemFontOfSize(14)
infoNameLabel.textAlignment = .Center
self.addSubview(infoNameLabel)
self.addSubview(infoValueLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setName(name:String){
self.infoNameLabel.text = name
}
func setValue(value:Int!){
self.infoValueLabel.text = String(value)
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| c5ae044c8166005787d1531a19d38d6c | 26.622642 | 91 | 0.641393 | false | false | false | false |
lanjing99/RxSwiftDemo | refs/heads/master | 09-combining-operators/challenge/Challenge1-Finished/RxSwift.playground/Contents.swift | mit | 1 | //: Please build the scheme 'RxSwiftPlayground' first
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
import RxSwift
example(of: "Challenge 1 - solution using zip") {
let source = Observable.of(1, 3, 5, 7, 9)
let scanObservable = source.scan(0, accumulator: +)
let observable = Observable.zip(source, scanObservable) { value, runningTotal in
(value, runningTotal)
}
observable.subscribe(onNext: { tuple in
print("Value = \(tuple.0) Running total = \(tuple.1)")
})
}
example(of: "Challenge 1 - solution using just scan and a tuple") {
let source = Observable.of(1, 3, 5, 7, 9)
let observable = source.scan((0,0)) { acc, current in
return (current, acc.1 + current)
}
observable.subscribe(onNext: { tuple in
print("Value = \(tuple.0) Running total = \(tuple.1)")
})
}
/*:
Copyright (c) 2014-2016 Razeware LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
| 313d2a6601905eaffc673e46cc8534a3 | 35.074074 | 82 | 0.735113 | false | false | false | false |
FredrikSjoberg/KFDataStructures | refs/heads/master | KFDataStructures/Swift/BinarySearchTree.swift | mit | 1 | //
// BinarySearchTree.swift
// KFDataStructures
//
// Created by Fredrik Sjöberg on 14/11/16.
// Copyright © 2016 Fredrik Sjoberg. All rights reserved.
//
import Foundation
//: Playground - noun: a place where people can play
import UIKit
public class BinarySearchTree<T: Comparable> {
fileprivate var root: BinarySearchNode<T>?
public init(value: T) {
self.root = BinarySearchNode(value: value)
}
}
extension BinarySearchTree: Sequence {
public func makeIterator() -> BinarySearchTreeInOrderIterator<T> {
return BinarySearchTreeInOrderIterator(tree: self)
}
}
/// Performance: O(h) extra memory required to store the stack, where h == height of tree
public struct BinarySearchTreeInOrderIterator<T: Comparable>: IteratorProtocol {
private var current: BinarySearchNode<T>?
private var stack: ContiguousArray<BinarySearchNode<T>>
init(tree: BinarySearchTree<T>) {
current = tree.root
stack = ContiguousArray()
}
mutating public func next() -> T? {
while current != nil {
stack.append(current!)
current = current?.left
}
guard !stack.isEmpty else { return nil }
current = stack.removeLast()
let result = current?.value
current = current?.right
return result
}
}
/*public enum BinarySearchTreeTraversalOrder {
//In-order (or depth-first): first look at the left child of a node, then at the node itself, and finally at its right child.
case inOrder
//Pre-order: first look at a node, then its left and right children.
case preOrder
//Post-order: first look at the left and right children and process the node itself last.
case postOrder
}*/
/// Find Items
extension BinarySearchTree {
/// Finds the "highest" node with specified value
/// Performance: O(h) where h is height of tree
public func contains(value: T) -> Bool {
guard let r = root else { return false }
let t = r.node(for: value)
return t != nil
}
/// Finds the minimum value
/// Performance: O(h)
public func min() -> T? {
return root?.min().value
}
/// Finds the maximum value
/// Performance: O(h)
public func max() -> T? {
return root?.max().value
}
/*public func traverse(order: BinarySearchTreeTraversalOrder, callback: (T) -> Void) {
root?.traverse(order: order, callback: callback)
}*/
}
/// Inserting items
extension BinarySearchTree {
public func insert(value: T) {
guard let root = root else {
self.root = BinarySearchNode(value: value)
return
}
root.insert(value: value)
}
}
/// Removing items
extension BinarySearchTree {
public func remove(value: T) {
guard let root = root else { return }
guard let present = root.node(for: value) else { return }
guard let replacement = present.remove() else { return }
if present === root {
self.root = replacement
}
}
}
/// Node
fileprivate class BinarySearchNode<T: Comparable> {
fileprivate(set) public var value: T
fileprivate(set) var parent: BinarySearchNode?
fileprivate(set) var left: BinarySearchNode?
fileprivate(set) var right: BinarySearchNode?
public init(value: T) {
self.value = value
}
}
/// Find items
extension BinarySearchNode {
fileprivate func min() -> BinarySearchNode {
return left?.min() ?? self
}
fileprivate func max() -> BinarySearchNode {
return right?.max() ?? self
}
fileprivate func node(for value: T) -> BinarySearchNode? {
if value < self.value {
return left?.node(for: value)
}
else if value > self.value {
return right?.node(for: value)
}
else {
return self
}
}
fileprivate var isLeftChild: Bool {
return parent?.left === self
}
fileprivate var isRightChild: Bool {
return parent?.right === self
}
/*fileprivate func traverse(order: BinarySearchTreeTraversalOrder, callback: (T) -> Void) {
switch order {
case .inOrder:
traverse(inOrder: callback)
case .preOrder:
traverse(preOrder: callback)
case .postOrder:
traverse(postOrder: callback)
}
}
fileprivate func traverse(inOrder callback: (T) -> Void) {
left?.traverse(inOrder: callback)
callback(value)
right?.traverse(inOrder: callback)
}
fileprivate func traverse(preOrder callback: (T) -> Void) {
callback(value)
left?.traverse(preOrder: callback)
right?.traverse(preOrder: callback)
}
fileprivate func traverse(postOrder callback: (T) -> Void) {
left?.traverse(postOrder: callback)
right?.traverse(postOrder: callback)
callback(value)
}*/
}
/// Inserting items
extension BinarySearchNode {
fileprivate func insert(value: T) {
if value < self.value {
if let left = left {
left.insert(value: value)
} else {
left = BinarySearchNode(value: value)
left?.parent = self
}
} else {
if let right = right {
right.insert(value: value)
} else {
right = BinarySearchNode(value: value)
right?.parent = self
}
}
}
}
/// Deleting items
extension BinarySearchNode {
/// Returns the node that replaces the removed one (or nil if removed was leaf node)
fileprivate func remove() -> BinarySearchNode? {
let replacement = findReplacement()
if let parent = parent {
if isLeftChild {
parent.left = replacement
}
else {
parent.right = replacement
}
}
replacement?.parent = parent
parent = nil
left = nil
right = nil
return replacement
}
fileprivate func findReplacement() -> BinarySearchNode? {
if let left = left {
if let right = right {
// This node has two children. It must be replaced by the smallest
// child that is larger than this node's value, which is the leftmost
// descendent of the right child.
let successor = right.min()
// If this in-order successor has a right child of its own (it cannot
// have a left child by definition), then that must take its place.
let _ = successor.remove()
// Connect our left child with the new node.
successor.left = left
//left.parent = successor
// Connect our right child with the new node. If the right child does
// not have any left children of its own, then the in-order successor
// *is* the right child.
if right !== successor {
successor.right = right
//right.parent = successor
} else {
successor.right = nil
}
// And finally, connect the successor node to our parent.
return successor
}
else {
return left
}
}
else {
return right
}
}
}
| be3fedf642714af1ff08ab8f67ffcba2 | 27.372694 | 129 | 0.562622 | false | false | false | false |
ocadaruma/museswift | refs/heads/master | MuseSwift/Source/Render/SingleLineScore/SingleLineScore.swift | mit | 1 | import Foundation
@IBDesignable public class SingleLineScore: UIView {
public var layout: SingleLineScoreLayout = SingleLineScoreLayout.defaultLayout {
didSet {
setNeedsDisplay()
}
}
private var staffTop: CGFloat {
return (bounds.size.height - layout.staffHeight) / 2
}
private var staffInterval: CGFloat {
return layout.staffHeight / CGFloat(staffNum - 1)
}
/// score elemeents will be added to this view.
private var _canvas: UIView! = nil
public var canvas: UIView { return _canvas }
public func loadVoice(tuneHeader: TuneHeader, voiceHeader: VoiceHeader, voice: Voice, initialOffset: CGFloat = 0) -> Void {
if let c = _canvas { c.removeFromSuperview() }
_canvas = UIView(frame: bounds)
addSubview(canvas)
let renderer = SingleLineScoreRenderer(
unitDenominator: tuneHeader.unitNoteLength.denominator, layout: layout, bounds: bounds)
var noteUnitMap = [CGFloat:NoteUnit]()
var tieLocations = [CGFloat]()
var elementsInBeam: [(xOffset: CGFloat, element: BeamMember)] = []
var xOffset: CGFloat = initialOffset
var beamContinue = false
// render clef
let clef = renderer.createClef(xOffset, clef: voiceHeader.clef)
canvas.addSubview(clef)
xOffset += clef.frame.width
// render key signature
let keySignature = renderer.createKeySignature(xOffset, key: tuneHeader.key)
for k in keySignature { canvas.addSubview(k) }
xOffset = keySignature.map({$0.frame.maxX}).maxElement()!
// render meter
let meter = renderer.createMeter(xOffset, meter: tuneHeader.meter)
canvas.addSubview(meter)
xOffset += meter.frame.width
// render voice
for element in voice.elements {
beamContinue = false
switch element {
case let simple as Simple:
switch simple {
case .BarLine:
canvas.addSubview(
RectElement(frame:
CGRect(
x: xOffset - layout.barMarginRight,
y: staffTop,
width: layout.stemWidth,
height: layout.staffHeight)))
case .DoubleBarLine:
canvas.addSubview(
DoubleBarElement(frame:
CGRect(
x: xOffset - layout.barMarginRight,
y: staffTop,
width: layout.stemWidth * 3,
height: layout.staffHeight)))
case .Space: break
case .LineBreak: break
case .RepeatEnd: break //TODO
case .RepeatStart: break //TODO
case .Tie:
tieLocations.append(xOffset)
case .SlurEnd: break //TODO
case .SlurStart: break //TODO
case .End: break
}
case let note as Note:
switch calcDenominator(note.length.absoluteLength(renderer.unitDenominator)) {
case .Whole, .Half, .Quarter:
let unit = renderer.createNoteUnit(xOffset, note: note)
unit.renderToView(canvas)
noteUnitMap[unit.xOffset] = unit
default:
elementsInBeam.append((xOffset: xOffset, element: note))
beamContinue = true
}
xOffset += renderer.rendereredWidthForNoteLength(note.length)
case let chord as Chord:
switch calcDenominator(chord.length.absoluteLength(renderer.unitDenominator)) {
case .Whole, .Half, .Quarter:
let unit = renderer.createNoteUnit(xOffset, chord: chord)
unit.renderToView(canvas)
noteUnitMap[unit.xOffset] = unit
default:
elementsInBeam.append((xOffset: xOffset, element: chord))
beamContinue = true
}
xOffset += renderer.rendereredWidthForNoteLength(chord.length)
case let tuplet as Tuplet:
let tupletUnit = renderer.createTupletUnit(tuplet, xOffset: xOffset)
tupletUnit.renderToView(canvas)
for unit in tupletUnit.toNoteUnits() { noteUnitMap[unit.xOffset] = unit }
xOffset += tuplet.elements.map({renderer.rendereredWidthForNoteLength($0.length) * CGFloat(tuplet.ratio)}).sum()
case let rest as Rest:
renderer.createRestUnit(xOffset, rest: rest).renderToView(canvas)
xOffset += renderer.rendereredWidthForNoteLength(rest.length)
case let rest as MultiMeasureRest:
xOffset += renderer.rendereredWidthForNoteLength(NoteLength(numerator: rest.num, denominator: 1))
default: break
}
if !beamContinue && elementsInBeam.nonEmpty {
for beam in renderer.createBeamUnit(elementsInBeam) {
beam.renderToView(canvas)
for unit in beam.toNoteUnits() { noteUnitMap[unit.xOffset] = unit }
}
elementsInBeam = []
}
}
if elementsInBeam.nonEmpty {
for beam in renderer.createBeamUnit(elementsInBeam) {
beam.renderToView(canvas)
for unit in beam.toNoteUnits() { noteUnitMap[unit.xOffset] = unit }
}
}
let noteUnitLocations = noteUnitMap.keys.sort()
for x in tieLocations {
if let i = noteUnitLocations.indexOf(x) {
let start = noteUnitLocations.get(i - 1).flatMap({noteUnitMap[$0]})
let end = noteUnitMap[x]
renderer.createTie(start, end: end).foreach({self.canvas.addSubview($0)})
}
}
}
private func drawStaff() {
let width = bounds.size.width
let top = staffTop
let ctx = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(ctx, layout.staffLineWidth)
CGContextSetStrokeColorWithColor(ctx, UIColor.lightGrayColor().CGColor)
for i in 0..<staffNum {
let offset = staffInterval * CGFloat(i)
CGContextMoveToPoint(ctx, 0, top + offset)
CGContextAddLineToPoint(ctx, width, top + offset)
CGContextStrokePath(ctx)
}
}
public override func drawRect(rect: CGRect) {
drawStaff()
}
}
| 65eeed232db69a6e0c5786b6633152d3 | 31.655367 | 125 | 0.647924 | false | false | false | false |
devpunk/velvet_room | refs/heads/master | Source/View/Basic/VSliderBar.swift | mit | 1 | import UIKit
final class VSliderBar:UIView
{
private let kBorderWidth:CGFloat = 1
init()
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
isUserInteractionEnabled = false
let border:VBorder = VBorder(colour:UIColor(white:0, alpha:0.2))
let blur:VBlur = VBlur.light()
blur.alpha = 1
let colorStart:UIColor = UIColor(white:1, alpha:0.1)
let colorEnd:UIColor = UIColor.white
let viewGradient:VGradient = VGradient.horizontal(
colourLeft:colorStart,
colourRight:colorEnd)
addSubview(viewGradient)
addSubview(blur)
addSubview(border)
NSLayoutConstraint.equals(
view:viewGradient,
toView:self)
NSLayoutConstraint.equals(
view:blur,
toView:self)
NSLayoutConstraint.equalsVertical(
view:border,
toView:self)
NSLayoutConstraint.width(
view:border,
constant:kBorderWidth)
NSLayoutConstraint.rightToRight(
view:border,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
}
| a70b336b9c89042b620b7c22666c2985 | 24.388889 | 72 | 0.568198 | false | false | false | false |
leolanzinger/readory | refs/heads/master | Readory_test/ViewController.swift | mit | 1 | //
// ViewController.swift
// Created by Kyle Weiner on 10/17/14.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var playersLabel: UILabel!
@IBOutlet weak var lionPic: UIImageView!
@IBOutlet weak var parrotPic: UIImageView!
@IBOutlet weak var wolfPic: UIImageView!
@IBOutlet weak var foxPic: UIImageView!
@IBOutlet weak var lamaPic: UIImageView!
var selectedPlayers:Int!
var players:Int! = -1
override func viewDidLoad() {
super.viewDidLoad()
// set the number of players label only if
// number of players is set
if (players > 0) {
playersLabel.text = "YOU ARE PLAYING WITH " + String(players) + " PLAYER"
if (players > 1) {
playersLabel.text = playersLabel.text! + "S"
// show lion picture
lionPic.hidden = false
if (players > 2) {
// show parrot pic
parrotPic.hidden = false
if (players > 3) {
// show wolf pic
wolfPic.hidden = false
if (players > 4) {
// show fox pic
foxPic.hidden = false
}
}
}
}
}
}
@IBAction func onePlayer(sender: AnyObject) {
self.selectedPlayers = 1
performSegueWithIdentifier("confirmGame", sender: self)
}
@IBAction func twoPlayers(sender: AnyObject) {
self.selectedPlayers = 2
performSegueWithIdentifier("confirmGame", sender: self)
}
@IBAction func threePlayers(sender: AnyObject) {
self.selectedPlayers = 3
performSegueWithIdentifier("confirmGame", sender: self)
}
@IBAction func fourPlayers(sender: AnyObject) {
self.selectedPlayers = 4
performSegueWithIdentifier("confirmGame", sender: self)
}
@IBAction func fivePlayers(sender: AnyObject) {
self.selectedPlayers = 5
performSegueWithIdentifier("confirmGame", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "startGame") {
Game.init()
Game.swiftSharedInstance.setPlayers(self.players)
}
else if (segue.identifier == "confirmGame") {
let secondViewController = segue.destinationViewController as! ViewController
let plyrs = self.selectedPlayers as Int
secondViewController.players = plyrs
}
}
@IBAction func prepareForUnwind(segue: UIStoryboardSegue) {
}
} | f6b6c269886dd793b52985001f49d974 | 30.11236 | 89 | 0.561777 | false | false | false | false |
shadanan/mado | refs/heads/master | Mado/ExprEvaluate.swift | mit | 1 | //
// MadoExprEvaluate.swift
// Mado
//
// Created by Shad Sharma on 2/5/17.
// Copyright © 2017 Shad Sharma. All rights reserved.
//
import Antlr4
import Foundation
class Expr: MadoBaseVisitor<Double> {
let W: Double
let H: Double
let x: Double
let y: Double
let w: Double
let h: Double
var msg: String?
var error: ANTLRError? = nil
init(W: Double, H: Double, x: Double, y: Double, w: Double, h: Double) {
self.W = W
self.H = H
self.x = x
self.y = y
self.w = w
self.h = h
}
class MadoErrorListener: ANTLRErrorListener {
let expr: Expr
init(expr: Expr) {
self.expr = expr
}
func syntaxError<T : ATNSimulator>(_ recognizer: Recognizer<T>, _ offendingSymbol: AnyObject?, _ line: Int, _ charPositionInLine: Int, _ msg: String, _ e: AnyObject?) {
expr.error = ANTLRError.illegalArgument(msg: msg)
}
func reportAmbiguity(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, _ stopIndex: Int, _ exact: Bool, _ ambigAlts: BitSet, _ configs: ATNConfigSet) throws {
}
func reportContextSensitivity(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, _ stopIndex: Int, _ prediction: Int, _ configs: ATNConfigSet) throws {
}
func reportAttemptingFullContext(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, _ stopIndex: Int, _ conflictingAlts: BitSet?, _ configs: ATNConfigSet) throws {
}
}
override func visitNumber(_ ctx: MadoParser.NumberContext) -> Double {
return Double(ctx.getText())!
}
override func visitAtomNumberExpr(_ ctx: MadoParser.AtomNumberExprContext) -> Double {
return visitChildren(ctx)!
}
override func visitVariable(_ ctx: MadoParser.VariableContext) -> Double {
switch ctx.getText() {
case "W": return W
case "H": return H
case "x": return x
case "y": return y
case "w": return w
case "h": return h
default:
error = ANTLRError.illegalState(msg: "Invalid Variable: \(ctx.getText())")
return 0
}
}
override func visitAtomVariableExpr(_ ctx: MadoParser.AtomVariableExprContext) -> Double {
return visitChildren(ctx)!
}
override func visitOperatorExpr(_ ctx: MadoParser.OperatorExprContext) -> Double {
if let lop = visit(ctx.lop), let rop = visit(ctx.rop), let op = ctx.op.getText() {
switch op {
case "*": return lop * rop
case "/": return lop / rop
case "+": return lop + rop
case "-": return lop - rop
default:
error = ANTLRError.illegalState(msg: "Invalid Operator: \(op)")
}
}
return 0
}
override func visitMultiplyExpr(_ ctx: MadoParser.MultiplyExprContext) -> Double {
return visit(ctx.number()!)! * visit(ctx.variable()!)!
}
override func visitParenExpr(_ ctx: MadoParser.ParenExprContext) -> Double {
return visit(ctx.expr()!)!
}
static func evaluate(exprStr: String, W: Double, H: Double,
x: Double, y: Double, w: Double, h: Double) -> Double? {
do {
let lexer = MadoLexer(ANTLRInputStream(exprStr))
let parser = try MadoParser(CommonTokenStream(lexer))
parser.setErrorHandler(BailErrorStrategy())
let visitor = Expr(W: W, H: H, x: x, y: y, w: w, h: h)
lexer.addErrorListener(MadoErrorListener(expr: visitor))
let expr = try parser.expr()
if visitor.error != nil {
return nil
}
if let result = visitor.visit(expr) {
return result
}
} catch {}
return nil
}
}
| 6822b4eb3ca50077f5f5293087f54b0d | 31.04065 | 176 | 0.559503 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS/Sources/UserInterface/ConversationList/Container/ViewModel/ConversationListViewControllerViewModel.swift | gpl-3.0 | 1 | // 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 Foundation
import UserNotifications
import WireDataModel
import WireSyncEngine
import WireCommonComponents
typealias Completion = () -> Void
typealias ResultHandler = (_ succeeded: Bool) -> Void
protocol ConversationListContainerViewModelDelegate: AnyObject {
init(viewModel: ConversationListViewController.ViewModel)
func scrollViewDidScroll(scrollView: UIScrollView!)
func setState(_ state: ConversationListState,
animated: Bool,
completion: Completion?)
func showNoContactLabel(animated: Bool)
func hideNoContactLabel(animated: Bool)
func openChangeHandleViewController(with handle: String)
func showNewsletterSubscriptionDialogIfNeeded(completionHandler: @escaping ResultHandler)
func updateArchiveButtonVisibilityIfNeeded(showArchived: Bool)
func removeUsernameTakeover()
func showUsernameTakeover(suggestedHandle: String, name: String)
func showPermissionDeniedViewController()
@discardableResult
func selectOnListContentController(_ conversation: ZMConversation!, scrollTo message: ZMConversationMessage?, focusOnView focus: Bool, animated: Bool, completion: (() -> Void)?) -> Bool
var hasUsernameTakeoverViewController: Bool { get }
}
extension ConversationListViewController: ConversationListContainerViewModelDelegate {}
extension ConversationListViewController {
final class ViewModel: NSObject {
weak var viewController: ConversationListContainerViewModelDelegate? {
didSet {
guard viewController != nil else { return }
updateNoConversationVisibility(animated: false)
updateArchiveButtonVisibility()
showPushPermissionDeniedDialogIfNeeded()
}
}
let account: Account
let selfUser: SelfUserType
let conversationListType: ConversationListHelperType.Type
var selectedConversation: ZMConversation?
var userProfileObserverToken: Any?
fileprivate var initialSyncObserverToken: Any?
fileprivate var userObserverToken: Any?
/// observer tokens which are assigned when viewDidLoad
var allConversationsObserverToken: Any?
var connectionRequestsObserverToken: Any?
var actionsController: ConversationActionController?
init(account: Account,
selfUser: SelfUserType,
conversationListType: ConversationListHelperType.Type = ZMConversationList.self) {
self.account = account
self.selfUser = selfUser
self.conversationListType = conversationListType
}
}
}
extension ConversationListViewController.ViewModel {
func setupObservers() {
if let userSession = ZMUserSession.shared() {
userObserverToken = UserChangeInfo.add(observer: self, for: userSession.selfUser, in: userSession) as Any
initialSyncObserverToken = ZMUserSession.addInitialSyncCompletionObserver(self, userSession: userSession)
}
updateObserverTokensForActiveTeam()
}
func savePendingLastRead() {
ZMUserSession.shared()?.enqueue({
self.selectedConversation?.savePendingLastRead()
})
}
/// Select a conversation and move the focus to the conversation view.
///
/// - Parameters:
/// - conversation: the conversation to select
/// - message: scroll to this message
/// - focus: focus on the view or not
/// - animated: perform animation or not
/// - completion: the completion block
func select(conversation: ZMConversation,
scrollTo message: ZMConversationMessage? = nil,
focusOnView focus: Bool = false,
animated: Bool = false,
completion: Completion? = nil) {
selectedConversation = conversation
viewController?.setState(.conversationList, animated: animated) { [weak self] in
self?.viewController?.selectOnListContentController(self?.selectedConversation, scrollTo: message, focusOnView: focus, animated: animated, completion: completion)
}
}
fileprivate var userProfile: UserProfile? {
return ZMUserSession.shared()?.userProfile
}
func requestSuggestedHandlesIfNeeded() {
guard let session = ZMUserSession.shared(),
let userProfile = userProfile else { return }
if nil == session.selfUser.handle,
session.hasCompletedInitialSync == true,
session.isPendingHotFixChanges == false {
userProfileObserverToken = userProfile.add(observer: self)
userProfile.suggestHandles()
}
}
func setSuggested(handle: String) {
userProfile?.requestSettingHandle(handle: handle)
}
private var isComingFromRegistration: Bool {
return ZClientViewController.shared?.isComingFromRegistration ?? false
}
/// show PushPermissionDeniedDialog when necessary
///
/// - Returns: true if PushPermissionDeniedDialog is shown
@discardableResult
func showPushPermissionDeniedDialogIfNeeded() -> Bool {
// We only want to present the notification takeover when the user already has a handle
// and is not coming from the registration flow (where we alreday ask for permissions).
guard selfUser.handle != nil else { return false }
guard !isComingFromRegistration else { return false }
guard !AutomationHelper.sharedHelper.skipFirstLoginAlerts else { return false }
guard false == viewController?.hasUsernameTakeoverViewController else { return false }
guard Settings.shared.pushAlertHappenedMoreThan1DayBefore else { return false }
UNUserNotificationCenter.current().checkPushesDisabled({ [weak self] pushesDisabled in
DispatchQueue.main.async {
if pushesDisabled,
let weakSelf = self {
Settings.shared[.lastPushAlertDate] = Date()
weakSelf.viewController?.showPermissionDeniedViewController()
}
}
})
return true
}
}
extension ConversationListViewController.ViewModel: ZMInitialSyncCompletionObserver {
func initialSyncCompleted() {
requestSuggestedHandlesIfNeeded()
}
}
extension Settings {
var pushAlertHappenedMoreThan1DayBefore: Bool {
guard let date: Date = self[.lastPushAlertDate] else {
return true
}
return date.timeIntervalSinceNow < -86400
}
}
| 1b4368293fb0d22978a4671884533175 | 35.27 | 189 | 0.693548 | false | false | false | false |
LiLe2015/DouYuLive | refs/heads/master | DouYuLive/DouYuLive/Classes/Main/View/PageContentView.swift | mit | 1 | //
// PageContentView.swift
// DouYuLive
//
// Created by LiLe on 2016/11/10.
// Copyright © 2016年 LiLe. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate:class {
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int)
}
private let ContentCellID = "ContentCellID"
class PageContentView: UIView {
// MARK:- 定义属性
private var childVcs: [UIViewController]
private weak var parentViewController: UIViewController?
private var startOffsetX: CGFloat = 0
private var isForbidScrollDelegate: Bool = false
weak var delegate:PageContentViewDelegate?
// MARK:- 懒加载属性
private lazy var collectionView: UICollectionView = {[weak self] in
// 1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .Horizontal
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.pagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.scrollsToTop = false
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
// MARK:- 自定义构造函数
init(frame: CGRect, childVcs: [UIViewController], parentViewController: UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面
extension PageContentView {
private func setupUI() {
// 1.将所有的子控制器添加到父控制器中
for childVc in childVcs {
parentViewController?.addChildViewController(childVc)
}
// 2.添加UICollectionView,用于在cell中存放控制器的view
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK:- 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// 1.创建cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ContentCellID, forIndexPath: indexPath)
// 2.给Cell设置内容
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
// MARK:- 遵守UICollectionViewDelegate
extension PageContentView: UICollectionViewDelegate {
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(scrollView: UIScrollView) {
// 0.判断是否是点击事件
if isForbidScrollDelegate {
return
}
// 1.获取需要的数据
var progress: CGFloat = 0
var sourceIndex: Int = 0
var targetIndex: Int = 0
// 2.判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX { // 左滑
// 1.计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
// 2.计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
// 3.计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
// 4.如果完全滑过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
} else { // 右滑
// 1.计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
// 2.计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
// 3.计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
// 3.将progress/sourceIndex/targetIndex传递给titleView
delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
// MARK:- 对外暴露的方法
extension PageContentView {
func setCurrentIndex(currentIndex: Int) {
// 1.记录需要禁止执行代理方法
isForbidScrollDelegate = true
// 2.滚动到正确的位置
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
| d457e834a67336b867153f0f44c016df | 31.213018 | 130 | 0.639052 | false | false | false | false |
prebid/prebid-mobile-ios | refs/heads/master | InternalTestApp/PrebidMobileDemoRenderingUITests/UITests/XCTestCaseExt.swift | apache-2.0 | 1 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import XCTest
protocol Failable: ObjcFailable {
func failWithMessage(_ message: String, file: String, line: UInt, nothrow: Bool)
}
extension Failable {
func failWithMessage(_ message: String, file: String, line: UInt) {
failWithMessage(message, file: file, line: line, nothrow: false)
}
}
extension XCTestCase {
// MARK: - Helper methods (wait)
func waitForEnabled(element: XCUIElement, failElement: XCUIElement? = nil, waitSeconds: TimeInterval = 5, file: StaticString = #file, line: UInt = #line) {
let enabledPredicate = NSPredicate(format: "enabled == true")
var error: String = "Failed to find enabled element \(element) after \(waitSeconds) seconds"
if let failElement = failElement {
error += " or element \(failElement) became enabled earlier."
} else {
error += "."
}
waitFor(element: element, predicate: enabledPredicate, failElement: failElement, failPredicate: enabledPredicate, message: error, waitSeconds: waitSeconds, file: file, line: line)
}
func waitForHittable(element: XCUIElement, waitSeconds: TimeInterval = 5, file: StaticString = #file, line: UInt = #line) {
let existsPredicate = NSPredicate(format: "hittable == true")
let error = "Failed to find \(element) after \(waitSeconds) seconds."
waitFor(element: element, predicate: existsPredicate, message: error, waitSeconds: waitSeconds, file: file, line: line)
}
func waitForNotHittable(element: XCUIElement, waitSeconds: TimeInterval = 5, file: StaticString = #file, line: UInt = #line) {
let hittablePredicate = NSPredicate(format: "hittable == false")
let error = "Failed to find \(element) after \(waitSeconds) seconds."
waitFor(element: element, predicate: hittablePredicate, message: error, waitSeconds: waitSeconds, file: file, line: line)
}
func waitForExists(element: XCUIElement, waitSeconds: TimeInterval = 5, file: StaticString = #file, line: UInt = #line) {
let existsPredicate = NSPredicate(format: "exists == true")
let error = "Failed to find \(element) after \(waitSeconds) seconds."
waitFor(element: element, predicate: existsPredicate, message: error, waitSeconds: waitSeconds, file: file, line: line)
}
func waitForNotExist(element: XCUIElement, waitSeconds: TimeInterval = 5, file: StaticString = #file, line: UInt = #line) {
let predicate = NSPredicate(format: "exists != true")
let error = "Element \(element) failed to be hidden after \(waitSeconds) seconds."
waitFor(element: element, predicate: predicate, message: error, waitSeconds: waitSeconds, file: file, line: line)
}
func waitFor(element: XCUIElement, predicate: NSPredicate, message: String, waitSeconds: TimeInterval, file: StaticString, line: UInt) {
waitFor(element: element, predicate: predicate, failElement: nil, failPredicate: nil, message: message, waitSeconds: waitSeconds, file: file, line: line)
}
private func waitFor(element: XCUIElement, predicate: NSPredicate, failElement: XCUIElement?, failPredicate: NSPredicate?, message: String, waitSeconds: TimeInterval, file: StaticString, line: UInt) {
if let failElement = failElement, let failPredicate = failPredicate {
let finishPredicate = NSPredicate { [weak self] (obj, bindings) -> Bool in
guard let targets = obj as? [XCUIElement], targets.count == 2 else {
return false
}
let positiveOutcome = predicate.evaluate(with: targets[0])
let negativeOutcome = failPredicate.evaluate(with: targets[1])
if (negativeOutcome) {
self?.failHelper(message: "\(message) [early fail detection triggerred]", file: file, line: line, nothrow: true)
}
return positiveOutcome || negativeOutcome
}
let finishArgs = [element, failElement]
expectation(for: finishPredicate, evaluatedWith: finishArgs, handler: nil)
} else {
expectation(for: predicate, evaluatedWith: element, handler: nil)
}
waitForExpectations(timeout: waitSeconds) { [weak self] (error) -> Void in
if let error = error {
self?.failHelper(message: "\(message) [error: \(error.localizedDescription)]", file: file, line: line, nothrow: true)
}
}
guard predicate.evaluate(with: element) else {
failHelper(message: "\(message) [predicate returned false]", file: file, line: line)
return
}
if let failElement = failElement, let failPredicate = failPredicate {
guard failPredicate.evaluate(with: failElement) == false else {
failHelper(message: "\(message) [failPredicate returned true]", file: file, line: line)
return
}
}
}
// MARK: - Helper methods (navigation)
fileprivate func navigateToExample(app: XCUIApplication, title: String, file: StaticString = #file, line: UInt = #line) {
let listItem = app.tables.staticTexts[title]
waitForExists(element: listItem, waitSeconds: 5, file: file, line: line)
listItem.tap()
let navBar = app.navigationBars[title]
waitForExists(element: navBar, waitSeconds: 5, file: file, line: line)
}
fileprivate func pickSegment(app: XCUIApplication, segmentedIndex: Int, segment: String?, file: StaticString = #file, line: UInt = #line) {
app.segmentedControls.allElementsBoundByIndex[segmentedIndex].buttons[segment ?? "All"].tap()
}
fileprivate func navigateToSection(app: XCUIApplication, title: String, file: StaticString = #file, line: UInt = #line) {
let adapter = app.tabBars.buttons[title]
waitForExists(element: adapter, waitSeconds: 5)
adapter.tap()
}
// MARK: - Helper Methods (app management)
class AppLifebox {
var app: XCUIApplication!
private var interruptionMonitor: NSObjectProtocol?
private var removeMonitorClosure: (NSObjectProtocol) -> ()
init(addMonitorClosure: (String, @escaping (XCUIElement) -> Bool) -> NSObjectProtocol?, removeMonitorClosure: @escaping (NSObjectProtocol) -> ()) {
app = XCUIApplication()
app.launchArguments.append("-keyUITests")
app.launch()
interruptionMonitor = addMonitorClosure("System Dialog") {
(alert) -> Bool in
alert.buttons["Don’t Allow"].tap()
return true
}
app.navigationBars.firstMatch.tap()
self.removeMonitorClosure = removeMonitorClosure
}
deinit {
if let monitor = interruptionMonitor {
interruptionMonitor = nil
removeMonitorClosure(monitor)
}
if app.state != .notRunning {
app.terminate()
}
}
}
func constructApp() -> AppLifebox {
return AppLifebox( addMonitorClosure: self.addUIInterruptionMonitor, removeMonitorClosure: self.removeUIInterruptionMonitor)
}
// MARK: - Private Helpers (failing)
private func failHelper(message: String, file: StaticString, line: UInt, nothrow: Bool = false) {
let screenshot = XCUIScreen.main.screenshot()
let attachment = XCTAttachment(screenshot: screenshot)
add(attachment)
if let failable = self as? Failable {
failable.failWithMessage(message, file: "\(file)", line: line, nothrow: nothrow)
} else {
XCTFail(message, file: file, line: line)
}
}
}
extension BaseUITestCase {
enum Tag: String, CaseIterable {
// Note: order defines search priority during the detection
case native = "Native"
case mraid = "MRAID"
case video = "Video"
case interstitial = "Interstitial"
case banner = "Banner"
}
enum AdServer: String, CaseIterable {
// Note: order defines search priority during the detection
case inapp = "In-App"
case gam = "GAM"
}
private func detect<T: RawRepresentable & CaseIterable>(from exampleTitle: String) -> T? where T.RawValue == String {
if let rawVal = T
.allCases
.map({ $0.rawValue })
.filter({ exampleTitle.contains($0.replacingOccurrences(of: " ", with: "")) })
.first
{
return T.init(rawValue: rawVal)
} else {
return nil
}
}
func navigateToExample(_ title: String, file: StaticString = #file, line: UInt = #line) {
applyFilter(adServer: detect(from: title))
applyFilter(tag: detect(from: title))
navigateToExample(app: app, title: title, file: file, line: line)
}
func applyFilter(tag: Tag?, file: StaticString = #file, line: UInt = #line) {
pickSegment(app: app, segmentedIndex: 0, segment: tag?.rawValue, file: file, line: line)
}
func applyFilter(adServer: AdServer?, file: StaticString = #file, line: UInt = #line) {
pickSegment(app: app, segmentedIndex: 1, segment: adServer?.rawValue, file: file, line: line)
}
func navigateToExamplesSection(file: StaticString = #file, line: UInt = #line) {
navigateToSection(app: app, title: "Examples", file: file, line: line)
}
}
| 5e736c1ed41f62ae672be931469e405e | 43.58952 | 204 | 0.634806 | false | false | false | false |
coodly/SlimTimerAPI | refs/heads/master | Tests/SlimTimerAPITests/LoadMultipleEntriesTests.swift | apache-2.0 | 1 | /*
* Copyright 2017 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
import SWXMLHash
@testable import SlimTimerAPI
class LoadMultipleEntriesTests: XCTestCase {
func testLoadMultipleEntries() {
let input =
"""
<?xml version="1.0" encoding="UTF-8"?>
<time-entries>
<time-entry>
<end-time type="datetime">2017-12-02T15:19:22Z</end-time>
<created-at type="datetime">2017-12-03T06:12:31Z</created-at>
<comments nil="true"></comments>
<updated-at type="datetime">2017-12-03T06:12:31Z</updated-at>
<tags></tags>
<id type="integer">34493713</id>
<duration-in-seconds type="integer">79</duration-in-seconds>
<task>
<coworkers>
</coworkers>
<name>Review apps</name>
<created-at type="datetime">2014-01-11T16:51:43Z</created-at>
<completed-on nil="true"></completed-on>
<owners>
<person>
<name>Apple</name>
<user-id type="integer">119695</user-id>
<email>[email protected]</email>
</person>
</owners>
<updated-at type="datetime">2014-01-11T16:51:43Z</updated-at>
<role>owner</role>
<tags></tags>
<id type="integer">2267906</id>
<reporters>
</reporters>
<hours type="float">10.04</hours>
</task>
<in-progress type="boolean">false</in-progress>
<start-time type="datetime">2017-12-02T15:18:02Z</start-time>
</time-entry>
<time-entry>
<end-time type="datetime">2017-12-02T15:50:45Z</end-time>
<created-at type="datetime">2017-12-02T15:50:29Z</created-at>
<comments nil="true"></comments>
<updated-at type="datetime">2017-12-02T15:50:46Z</updated-at>
<tags></tags>
<id type="integer">34493460</id>
<duration-in-seconds type="integer">60</duration-in-seconds>
<task>
<coworkers>
</coworkers>
<name>The Secret Project</name>
<created-at type="datetime">2015-03-07T13:21:28Z</created-at>
<completed-on nil="true"></completed-on>
<owners>
<person>
<name>Apple</name>
<user-id type="integer">119695</user-id>
<email>[email protected]</email>
</person>
</owners>
<updated-at type="datetime">2015-03-07T13:21:28Z</updated-at>
<role>owner</role>
<tags></tags>
<id type="integer">2536936</id>
<reporters>
</reporters>
<hours type="float">0.02</hours>
</task>
<in-progress type="boolean">false</in-progress>
<start-time type="datetime">2017-12-02T15:50:28Z</start-time>
</time-entry>
<time-entry>
<end-time type="datetime">2017-12-02T15:26:37Z</end-time>
<created-at type="datetime">2017-12-02T15:19:31Z</created-at>
<comments nil="true"></comments>
<updated-at type="datetime">2017-12-02T15:26:39Z</updated-at>
<tags></tags>
<id type="integer">34493451</id>
<duration-in-seconds type="integer">427</duration-in-seconds>
<task>
<coworkers>
</coworkers>
<name>Reading</name>
<created-at type="datetime">2015-03-07T13:22:24Z</created-at>
<completed-on nil="true"></completed-on>
<owners>
<person>
<name>Apple</name>
<user-id type="integer">119695</user-id>
<email>[email protected]</email>
</person>
</owners>
<updated-at type="datetime">2015-03-07T13:22:24Z</updated-at>
<role>owner</role>
<tags></tags>
<id type="integer">2536937</id>
<reporters>
</reporters>
<hours type="float">4.52</hours>
</task>
<in-progress type="boolean">false</in-progress>
<start-time type="datetime">2017-12-02T15:19:30Z</start-time>
</time-entry>
</time-entries>
"""
let xml = SWXMLHash.parse(input)
guard let entries = Entries(xml: xml) else {
XCTAssertFalse(true)
return
}
XCTAssertEqual(3, entries.entries.count)
}
}
| d56af2823c08a761b0536bbf297a21d9 | 37.992537 | 75 | 0.523445 | false | false | false | false |
schibsted/layout | refs/heads/master | LayoutTool/main.swift | mit | 1 | // Copyright © 2017 Schibsted. All rights reserved.
import Foundation
/// The current LayoutTool version
let version = "0.7.0"
extension String {
var inDefault: String { return "\u{001B}[39m\(self)" }
var inRed: String { return "\u{001B}[31m\(self)\u{001B}[0m" }
var inGreen: String { return "\u{001B}[32m\(self)\u{001B}[0m" }
var inYellow: String { return "\u{001B}[33m\(self)\u{001B}[0m" }
}
extension FileHandle: TextOutputStream {
public func write(_ string: String) {
if let data = string.data(using: .utf8) {
write(data)
}
}
}
private var stderr = FileHandle.standardError
func printHelp() {
print("")
print("LayoutTool, version \(version)")
print("copyright (c) 2017 Schibsted")
print("")
print("help")
print(" - prints this help page")
print("")
print("version")
print(" - prints the currently installed LayoutTool version")
print("")
print("format <files>")
print(" - formats all xml files found at the specified path(s)")
print("")
print("list <files>")
print(" - lists all Layout xml files found at the specified path(s)")
print("")
print("rename <files> <old> <new>")
print(" - renames all classes or symbols named <old> to <new> in <files>")
print("")
print("strings <files>")
print(" - lists all Localizable.strings keys used in <files>")
print("")
}
enum ExitResult: Int32 {
case success = 0
case failure = 1
}
func timeEvent(block: () throws -> Void) rethrows -> String {
let start = CFAbsoluteTimeGetCurrent()
try block()
let time = round((CFAbsoluteTimeGetCurrent() - start) * 100) / 100 // round to nearest 10ms
return String(format: "%gs", time)
}
func processArguments(_ args: [String]) -> ExitResult {
var errors = [FormatError]()
guard args.count > 1 else {
print("error: missing command argument", to: &stderr)
print("LayoutTool requires a command argument".inRed, to: &stderr)
return .failure
}
switch args[1] {
case "help":
printHelp()
case "version":
print(version)
case "format":
let paths = Array(args.dropFirst(2))
if paths.isEmpty {
errors.append(.options("format command expects one or more file paths as input"))
break
}
var filesChecked = 0, filesUpdated = 0
let time = timeEvent {
(filesChecked, filesUpdated, errors) = format(paths)
}
if errors.isEmpty {
print("LayoutTool format completed. \(filesUpdated)/\(filesChecked) files updated in \(time)".inGreen)
}
case "list":
let paths = Array(args.dropFirst(2))
if paths.isEmpty {
errors.append(.options("list command expects one or more file paths to search"))
break
}
errors += list(paths)
case "rename":
var paths = Array(args.dropFirst(2))
guard let new = paths.popLast(), let old = paths.popLast(), !new.contains("/"), !old.contains("/") else {
errors.append(.options("rename command expects a name and replacement"))
break
}
if paths.isEmpty {
errors.append(.options("rename command expects one or more file paths to search"))
break
}
errors += rename(old, to: new, in: paths)
case "strings":
let paths = Array(args.dropFirst(2))
if paths.isEmpty {
errors.append(.options("list command expects one or more file paths to search"))
break
}
errors += listStrings(in: paths)
case let arg:
print("error: unknown command \(arg)", to: &stderr)
print("LayoutTool \(arg) is not a valid command".inRed, to: &stderr)
return .failure
}
for error in errors {
print("error: \(error)", to: &stderr)
}
if errors.isEmpty {
return .success
} else {
print("LayoutTool \(args[1]) failed".inRed, to: &stderr)
return .failure
}
}
// Pass in arguments and exit
let result = processArguments(CommandLine.arguments)
exit(result.rawValue)
| b36fef1f62d75838df4190a624248d23 | 31.015385 | 114 | 0.59851 | false | false | false | false |
adityaaggarwal1/CMLibrary | refs/heads/master | Example/CMLibrary/ViewController.swift | mit | 1 | //
// ViewController.swift
// CMLibrary
//
// Created by adityaaggarwal1 on 09/23/2015.
// Copyright (c) 2015 adityaaggarwal1. All rights reserved.
//
import UIKit
import CMLibrary
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let toggleButton = UIButton(frame: CGRect(x: 10, y: 60, width: 200, height: 30))
toggleButton.setTitle("Webservice Call", forState: .Normal)
toggleButton.setTitleColor(UIColor.redColor(), forState: .Normal)
toggleButton.addTarget(self, action: "getTokenService", forControlEvents: .TouchUpInside)
view.addSubview(toggleButton)
let toggleButton1 = UIButton(frame: CGRect(x: 10, y: 120, width: 200, height: 30))
toggleButton1.setTitle("Webservice Call With Auth", forState: .Normal)
toggleButton1.setTitleColor(UIColor.redColor(), forState: .Normal)
toggleButton1.addTarget(self, action: "getFromKeyChain", forControlEvents: .TouchUpInside)
view.addSubview(toggleButton1)
}
func callWebservice() {
let webserviceCall = WebserviceCall(responseType: WebserviceCallResponseJSON, requestType: WebserviceCallRequestTypeJson, cachePolicy: WebserviceCallCachePolicyRequestFromUrlNoCache)
webserviceCall.isShowLoader = true
// http://jsonplaceholder.typicode.com/comments?postId=1
// webserviceCall.GET(NSURL(string: "http://jsonplaceholder.typicode.com/posts"), parameters: nil, withSuccessHandler: { (response: WebserviceResponse!) -> Void in
//
// let responseDict = response as WebserviceResponse
//
// print(responseDict.webserviceResponse)
//
// }) { (error: NSError!) -> Void in
//
// }
webserviceCall.shouldDisableInteraction = false
webserviceCall.GET(NSURL(string: "http://jsonplaceholder.typicode.com/comments"), parameters: ["postId":"1"], withSuccessHandler: { (response: WebserviceResponse!) -> Void in
let responseDict = response as WebserviceResponse
print(responseDict.webserviceResponse)
}) { (error: NSError!) -> Void in
}
}
func callPatchWebservice() {
let webserviceCall = WebserviceCall(responseType: WebserviceCallResponseJSON, requestType: WebserviceCallRequestTypeJson, cachePolicy: WebserviceCallCachePolicyRequestFromUrlNoCache)
webserviceCall.isShowLoader = true
// http://jsonplaceholder.typicode.com/comments?postId=1
// webserviceCall.GET(NSURL(string: "http://jsonplaceholder.typicode.com/posts"), parameters: nil, withSuccessHandler: { (response: WebserviceResponse!) -> Void in
//
// let responseDict = response as WebserviceResponse
//
// print(responseDict.webserviceResponse)
//
// }) { (error: NSError!) -> Void in
//
// }
webserviceCall.headerFieldsDict = ["Authorization" : "Bearer PuJq65INyxSipxFDipCXdyhJPBhUws"]
webserviceCall.shouldDisableInteraction = false
webserviceCall.DELETE(NSURL(string: "http://172.16.13.206:8009/app/api/delsrvc/20123/"), parameters: ["postId":"1"], withSuccessHandler: { (response: WebserviceResponse!) -> Void in
let responseDict = response as WebserviceResponse
print(responseDict.webserviceResponse)
}) { (error: NSError!) -> Void in
}
}
func uploadFileUsingMultipartUpload() {
let webserviceCall = WebserviceCall(responseType: WebserviceCallResponseString, requestType: WebserviceCallRequestTypeJson, cachePolicy: WebserviceCallCachePolicyRequestFromUrlNoCache)
webserviceCall.isShowLoader = true
let fileData = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("iOS Simulator Screen.png", ofType: nil)!)
webserviceCall.uploadFile(fileData, withFileName: "iOS Simulator Screen.png", withFieldName: "file", mimeType: "image/png", onUrl: NSURL(string: "http://posttestserver.com/post.php?dir=example"), withSuccessHandler: { (response: WebserviceResponse!) -> Void in
let responseDict = response as WebserviceResponse
print(responseDict.webserviceResponse)
}) { (error: NSError!) -> Void in
}
}
@IBAction func btnDummyTapped(sender: AnyObject) {
print("test >>>>>>>>>>>>>>>>>>>>>>>>>")
callWebservice()
}
func saveInKeyChain() {
let token = AuthToken()
token.access_token = "abc123"
FXKeychain.defaultKeychain().setObject(token, forKey: "Key")
}
func getFromKeyChain() {
let webserviceCall = WebserviceCall(responseType: WebserviceCallResponseJSON, requestType: WebserviceCallRequestTypeJson, cachePolicy: WebserviceCallCachePolicyRequestFromUrlNoCache)
webserviceCall.isShowLoader = true
webserviceCall.addAuthTokenInHeaderFromKey("AuthToken")
webserviceCall.POST(NSURL(string: "http://172.16.13.33:8009/app/api/signup/"), parameters: ["name":"test2", "email":"[email protected]", "password":"test2", "mobile":"8765657700", "device_id":"123awd1233", "device_token":"23424234sdfsd234234", "device_type":"1"], withSuccessHandler: { (response: WebserviceResponse!) -> Void in
let responseDict = (response as WebserviceResponse).webserviceResponse as! NSDictionary
NSLog("responseDict >>>>>>> %@", responseDict.description)
}) { (error: NSError!) -> Void in
}
}
func getTokenService() {
let webserviceCall = WebserviceCall(responseType: WebserviceCallResponseJSON, requestType: WebserviceCallRequestTypeFormURLEncoded, cachePolicy: WebserviceCallCachePolicyRequestFromUrlNoCache)
webserviceCall.isShowLoader = true
webserviceCall.fetchAuthTokenForClientSecret("lkeg7r@IQDwrFa7NHbNnV?e:oOs=UeHQ0j=83sJWux5mCOV6EX_DJx?vu0uLnwvlk1KM@BXX?.LBRrgWbW:rSF-ll_eCG!BwtkYIGn04JtVoLi=VYE3EAk:A.zS3u0VF", clientId: "qUiOEFk9Uyjw1z2pDUKW8=PMSv9FasXkYpgFa0P2", grantType: "client_credentials", andStoreAtKey: "AuthToken")
webserviceCall.POST(NSURL(string: "http://172.16.13.33:8009/o/token/"), parameters: nil, withSuccessHandler: { (response: WebserviceResponse!) -> Void in
let responseDict = (response as WebserviceResponse).webserviceResponse as! NSDictionary
NSLog("responseDict >>>>>>> %@", responseDict.description)
}) { (error: NSError!) -> Void in
}
}
}
| 5994e18afdf23c9d2c2591bace8022fa | 41.575163 | 338 | 0.687903 | false | false | false | false |
arvedviehweger/swift | refs/heads/master | stdlib/public/core/CompilerProtocols.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Intrinsic protocols shared with the compiler
//===----------------------------------------------------------------------===//
/// A type that can be converted to and from an associated raw value.
///
/// With a `RawRepresentable` type, you can switch back and forth between a
/// custom type and an associated `RawValue` type without losing the value of
/// the original `RawRepresentable` type. Using the raw value of a conforming
/// type streamlines interoperation with Objective-C and legacy APIs and
/// simplifies conformance to other protocols, such as `Equatable`,
/// `Comparable`, and `Hashable`.
///
/// The `RawRepresentable` protocol is seen mainly in two categories of types:
/// enumerations with raw value types and option sets.
///
/// Enumerations with Raw Values
/// ============================
///
/// For any enumeration with a string, integer, or floating-point raw type, the
/// Swift compiler automatically adds `RawRepresentable` conformance. When
/// defining your own custom enumeration, you give it a raw type by specifying
/// the raw type as the first item in the enumeration's type inheritance list.
/// You can also use literals to specify values for one or more cases.
///
/// For example, the `Counter` enumeration defined here has an `Int` raw value
/// type and gives the first case a raw value of `1`:
///
/// enum Counter: Int {
/// case one = 1, two, three, four, five
/// }
///
/// You can create a `Counter` instance from an integer value between 1 and 5
/// by using the `init?(rawValue:)` initializer declared in the
/// `RawRepresentable` protocol. This initializer is failable because although
/// every case of the `Counter` type has a corresponding `Int` value, there
/// are many `Int` values that *don't* correspond to a case of `Counter`.
///
/// for i in 3...6 {
/// print(Counter(rawValue: i))
/// }
/// // Prints "Optional(Counter.three)"
/// // Prints "Optional(Counter.four)"
/// // Prints "Optional(Counter.five)"
/// // Prints "nil"
///
/// Option Sets
/// ===========
///
/// Option sets all conform to `RawRepresentable` by inheritance using the
/// `OptionSet` protocol. Whether using an option set or creating your own,
/// you use the raw value of an option set instance to store the instance's
/// bitfield. The raw value must therefore be of a type that conforms to the
/// `FixedWidthInteger` protocol, such as `UInt8` or `Int`. For example, the
/// `Direction` type defines an option set for the four directions you can
/// move in a game.
///
/// struct Directions: OptionSet {
/// let rawValue: UInt8
///
/// static let up = Directions(rawValue: 1 << 0)
/// static let down = Directions(rawValue: 1 << 1)
/// static let left = Directions(rawValue: 1 << 2)
/// static let right = Directions(rawValue: 1 << 3)
/// }
///
/// Unlike enumerations, option sets provide a nonfailable `init(rawValue:)`
/// initializer to convert from a raw value, because option sets don't have an
/// enumerated list of all possible cases. Option set values have
/// a one-to-one correspondence with their associated raw values.
///
/// In the case of the `Directions` option set, an instance can contain zero,
/// one, or more of the four defined directions. This example declares a
/// constant with three currently allowed moves. The raw value of the
/// `allowedMoves` instance is the result of the bitwise OR of its three
/// members' raw values:
///
/// let allowedMoves: Directions = [.up, .down, .left]
/// print(allowedMoves.rawValue)
/// // Prints "7"
///
/// Option sets use bitwise operations on their associated raw values to
/// implement their mathematical set operations. For example, the `contains()`
/// method on `allowedMoves` performs a bitwise AND operation to check whether
/// the option set contains an element.
///
/// print(allowedMoves.contains(.right))
/// // Prints "false"
/// print(allowedMoves.rawValue & Directions.right.rawValue)
/// // Prints "0"
///
/// - SeeAlso: `OptionSet`, `FixedWidthInteger`
public protocol RawRepresentable {
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
associatedtype RawValue
/// Creates a new instance with the specified raw value.
///
/// If there is no value of the type that corresponds with the specified raw
/// value, this initializer returns `nil`. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// print(PaperSize(rawValue: "Legal"))
/// // Prints "Optional("PaperSize.Legal")"
///
/// print(PaperSize(rawValue: "Tabloid"))
/// // Prints "nil"
///
/// - Parameter rawValue: The raw value to use for the new instance.
init?(rawValue: RawValue)
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
var rawValue: RawValue { get }
}
/// Returns a Boolean value indicating whether the two arguments are equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
public func == <T : RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue : Equatable {
return lhs.rawValue == rhs.rawValue
}
/// Returns a Boolean value indicating whether the two arguments are not equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
public func != <T : RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue : Equatable {
return lhs.rawValue != rhs.rawValue
}
// This overload is needed for ambiguity resolution against the
// implementation of != for T : Equatable
/// Returns a Boolean value indicating whether the two arguments are not equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
public func != <T : Equatable>(lhs: T, rhs: T) -> Bool
where T : RawRepresentable, T.RawValue : Equatable {
return lhs.rawValue != rhs.rawValue
}
/// A type that can be initialized using the nil literal, `nil`.
///
/// `nil` has a specific meaning in Swift---the absence of a value. Only the
/// `Optional` type conforms to `ExpressibleByNilLiteral`.
/// `ExpressibleByNilLiteral` conformance for types that use `nil` for other
/// purposes is discouraged.
///
/// - SeeAlso: `Optional`
public protocol ExpressibleByNilLiteral {
/// Creates an instance initialized with `nil`.
init(nilLiteral: ())
}
public protocol _ExpressibleByBuiltinIntegerLiteral {
init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType)
}
/// A type that can be initialized with an integer literal.
///
/// The standard library integer and floating-point types, such as `Int` and
/// `Double`, conform to the `ExpressibleByIntegerLiteral` protocol. You can
/// initialize a variable or constant of any of these types by assigning an
/// integer literal.
///
/// // Type inferred as 'Int'
/// let cookieCount = 12
///
/// // An array of 'Int'
/// let chipsPerCookie = [21, 22, 25, 23, 24, 19]
///
/// // A floating-point value initialized using an integer literal
/// let redPercentage: Double = 1
/// // redPercentage == 1.0
///
/// Conforming to ExpressibleByIntegerLiteral
/// =========================================
///
/// To add `ExpressibleByIntegerLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByIntegerLiteral {
/// A type that represents an integer literal.
///
/// The standard library integer and floating-point types are all valid types
/// for `IntegerLiteralType`.
associatedtype IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral
/// Creates an instance initialized to the specified integer value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an integer literal. For example:
///
/// let x = 23
///
/// In this example, the assignment to the `x` constant calls this integer
/// literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
init(integerLiteral value: IntegerLiteralType)
}
public protocol _ExpressibleByBuiltinFloatLiteral {
init(_builtinFloatLiteral value: _MaxBuiltinFloatType)
}
/// A type that can be initialized with a floating-point literal.
///
/// The standard library floating-point types---`Float`, `Double`, and
/// `Float80` where available---all conform to the `ExpressibleByFloatLiteral`
/// protocol. You can initialize a variable or constant of any of these types
/// by assigning a floating-point literal.
///
/// // Type inferred as 'Double'
/// let threshold = 6.0
///
/// // An array of 'Double'
/// let measurements = [2.2, 4.1, 3.65, 4.2, 9.1]
///
/// Conforming to ExpressibleByFloatLiteral
/// =======================================
///
/// To add `ExpressibleByFloatLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByFloatLiteral {
/// A type that represents a floating-point literal.
///
/// Valid types for `FloatLiteralType` are `Float`, `Double`, and `Float80`
/// where available.
associatedtype FloatLiteralType : _ExpressibleByBuiltinFloatLiteral
/// Creates an instance initialized to the specified floating-point value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a floating-point literal. For example:
///
/// let x = 21.5
///
/// In this example, the assignment to the `x` constant calls this
/// floating-point literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
init(floatLiteral value: FloatLiteralType)
}
public protocol _ExpressibleByBuiltinBooleanLiteral {
init(_builtinBooleanLiteral value: Builtin.Int1)
}
/// A type that can be initialized with the Boolean literals `true` and
/// `false`.
///
/// Only three types provided by Swift---`Bool`, `DarwinBoolean`, and
/// `ObjCBool`---are treated as Boolean values. Expanding this set to include
/// types that represent more than simple Boolean values is discouraged.
///
/// To add `ExpressibleByBooleanLiteral` conformance to your custom type,
/// implement the `init(booleanLiteral:)` initializer that creates an instance
/// of your type with the given Boolean value.
public protocol ExpressibleByBooleanLiteral {
/// A type that represents a Boolean literal, such as `Bool`.
associatedtype BooleanLiteralType : _ExpressibleByBuiltinBooleanLiteral
/// Creates an instance initialized to the given Boolean value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using one of the Boolean literals `true` and `false`. For
/// example:
///
/// let twasBrillig = true
///
/// In this example, the assignment to the `twasBrillig` constant calls this
/// Boolean literal initializer behind the scenes.
///
/// - Parameter value: The value of the new instance.
init(booleanLiteral value: BooleanLiteralType)
}
public protocol _ExpressibleByBuiltinUnicodeScalarLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32)
}
/// A type that can be initialized with a string literal containing a single
/// Unicode scalar value.
///
/// The `String`, `StaticString`, `Character`, and `UnicodeScalar` types all
/// conform to the `ExpressibleByUnicodeScalarLiteral` protocol. You can
/// initialize a variable of any of these types using a string literal that
/// holds a single Unicode scalar.
///
/// let ñ: UnicodeScalar = "ñ"
/// print(ñ)
/// // Prints "ñ"
///
/// Conforming to ExpressibleByUnicodeScalarLiteral
/// ===============================================
///
/// To add `ExpressibleByUnicodeScalarLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByUnicodeScalarLiteral {
/// A type that represents a Unicode scalar literal.
///
/// Valid types for `UnicodeScalarLiteralType` are `UnicodeScalar`,
/// `Character`, `String`, and `StaticString`.
associatedtype UnicodeScalarLiteralType : _ExpressibleByBuiltinUnicodeScalarLiteral
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
init(unicodeScalarLiteral value: UnicodeScalarLiteralType)
}
public protocol _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
: _ExpressibleByBuiltinUnicodeScalarLiteral {
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
/// A type that can be initialized with a string literal containing a single
/// extended grapheme cluster.
///
/// An *extended grapheme cluster* is a group of one or more Unicode code
/// points that approximates a single user-perceived character. Many
/// individual characters, such as "é", "김", and "🇮🇳", can be made up of
/// multiple Unicode code points. These code points are combined by Unicode's
/// boundary algorithms into extended grapheme clusters.
///
/// The `String`, `StaticString`, and `Character` types conform to the
/// `ExpressibleByExtendedGraphemeClusterLiteral` protocol. You can initialize a
/// variable or constant of any of these types using a string literal that
/// holds a single character.
///
/// let snowflake: Character = "❄︎"
/// print(snowflake)
/// // Prints "❄︎"
///
/// Conforming to ExpressibleByExtendedGraphemeClusterLiteral
/// =========================================================
///
/// To add `ExpressibleByExtendedGraphemeClusterLiteral` conformance to your
/// custom type, implement the required initializer.
public protocol ExpressibleByExtendedGraphemeClusterLiteral
: ExpressibleByUnicodeScalarLiteral {
/// A type that represents an extended grapheme cluster literal.
///
/// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`,
/// `String`, and `StaticString`.
associatedtype ExtendedGraphemeClusterLiteralType
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType)
}
extension ExpressibleByExtendedGraphemeClusterLiteral
where ExtendedGraphemeClusterLiteralType == UnicodeScalarLiteralType {
@_transparent
public init(unicodeScalarLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(extendedGraphemeClusterLiteral: value)
}
}
public protocol _ExpressibleByBuiltinStringLiteral
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
public protocol _ExpressibleByBuiltinUTF16StringLiteral
: _ExpressibleByBuiltinStringLiteral {
init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word)
}
public protocol _ExpressibleByBuiltinConstStringLiteral
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
init(_builtinConstStringLiteral constantString: Builtin.RawPointer)
}
public protocol _ExpressibleByBuiltinConstUTF16StringLiteral
: _ExpressibleByBuiltinConstStringLiteral {
init(_builtinConstUTF16StringLiteral constantUTF16String: Builtin.RawPointer)
}
/// A type that can be initialized with a string literal.
///
/// The `String` and `StaticString` types conform to the
/// `ExpressibleByStringLiteral` protocol. You can initialize a variable or
/// constant of either of these types using a string literal of any length.
///
/// let picnicGuest = "Deserving porcupine"
///
/// Conforming to ExpressibleByStringLiteral
/// ========================================
///
/// To add `ExpressibleByStringLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByStringLiteral
: ExpressibleByExtendedGraphemeClusterLiteral {
/// A type that represents a string literal.
///
/// Valid types for `StringLiteralType` are `String` and `StaticString`.
associatedtype StringLiteralType : _ExpressibleByBuiltinStringLiteral
/// Creates an instance initialized to the given string value.
///
/// - Parameter value: The value of the new instance.
init(stringLiteral value: StringLiteralType)
}
extension ExpressibleByStringLiteral
where StringLiteralType == ExtendedGraphemeClusterLiteralType {
@_transparent
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(stringLiteral: value)
}
}
/// A type that can be initialized using an array literal.
///
/// An array literal is a simple way of expressing a list of values. Simply
/// surround a comma-separated list of values, instances, or literals with
/// square brackets to create an array literal. You can use an array literal
/// anywhere an instance of an `ExpressibleByArrayLiteral` type is expected: as
/// a value assigned to a variable or constant, as a parameter to a method or
/// initializer, or even as the subject of a nonmutating operation like
/// `map(_:)` or `filter(_:)`.
///
/// Arrays, sets, and option sets all conform to `ExpressibleByArrayLiteral`,
/// and your own custom types can as well. Here's an example of creating a set
/// and an array using array literals:
///
/// let employeesSet: Set<String> = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]
/// print(employeesSet)
/// // Prints "["Amir", "Dave", "Jihye", "Alessia"]"
///
/// let employeesArray: [String] = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]
/// print(employeesArray)
/// // Prints "["Amir", "Jihye", "Dave", "Alessia", "Dave"]"
///
/// The `Set` and `Array` types each handle array literals in their own way to
/// create new instances. In this case, the newly created set drops the
/// duplicate value ("Dave") and doesn't maintain the order of the array
/// literal's elements. The new array, on the other hand, matches the order
/// and number of elements provided.
///
/// - Note: An array literal is not the same as an `Array` instance. You can't
/// initialize a type that conforms to `ExpressibleByArrayLiteral` simply by
/// assigning an existing array.
///
/// let anotherSet: Set = employeesArray
/// // error: cannot convert value of type '[String]' to specified type 'Set'
///
/// Type Inference of Array Literals
/// ================================
///
/// Whenever possible, Swift's compiler infers the full intended type of your
/// array literal. Because `Array` is the default type for an array literal,
/// without writing any other code, you can declare an array with a particular
/// element type by providing one or more values.
///
/// In this example, the compiler infers the full type of each array literal.
///
/// let integers = [1, 2, 3]
/// // 'integers' has type '[Int]'
///
/// let strings = ["a", "b", "c"]
/// // 'strings' has type '[String]'
///
/// An empty array literal alone doesn't provide enough information for the
/// compiler to infer the intended type of the `Array` instance. When using an
/// empty array literal, specify the type of the variable or constant.
///
/// var emptyArray: [Bool] = []
/// // 'emptyArray' has type '[Bool]'
///
/// Because many functions and initializers fully specify the types of their
/// parameters, you can often use an array literal with or without elements as
/// a parameter. For example, the `sum(_:)` function shown here takes an `Int`
/// array as a parameter:
///
/// func sum(values: [Int]) -> Int {
/// return values.reduce(0, +)
/// }
///
/// let sumOfFour = sum([5, 10, 15, 20])
/// // 'sumOfFour' == 50
///
/// let sumOfNone = sum([])
/// // 'sumOfNone' == 0
///
/// When you call a function that does not fully specify its parameters' types,
/// use the type-cast operator (`as`) to specify the type of an array literal.
/// For example, the `log(name:value:)` function shown here has an
/// unconstrained generic `value` parameter.
///
/// func log<T>(name name: String, value: T) {
/// print("\(name): \(value)")
/// }
///
/// log(name: "Four integers", value: [5, 10, 15, 20])
/// // Prints "Four integers: [5, 10, 15, 20]"
///
/// log(name: "Zero integers", value: [] as [Int])
/// // Prints "Zero integers: []"
///
/// Conforming to ExpressibleByArrayLiteral
/// =======================================
///
/// Add the capability to be initialized with an array literal to your own
/// custom types by declaring an `init(arrayLiteral:)` initializer. The
/// following example shows the array literal initializer for a hypothetical
/// `OrderedSet` type, which has setlike semantics but maintains the order of
/// its elements.
///
/// struct OrderedSet<Element: Hashable>: Collection, SetAlgebra {
/// // implementation details
/// }
///
/// extension OrderedSet: ExpressibleByArrayLiteral {
/// init(arrayLiteral: Element...) {
/// self.init()
/// for element in arrayLiteral {
/// self.append(element)
/// }
/// }
/// }
public protocol ExpressibleByArrayLiteral {
/// The type of the elements of an array literal.
associatedtype Element
/// Creates an instance initialized with the given elements.
init(arrayLiteral elements: Element...)
}
/// A type that can be initialized using a dictionary literal.
///
/// A dictionary literal is a simple way of writing a list of key-value pairs.
/// You write each key-value pair with a colon (`:`) separating the key and
/// the value. The dictionary literal is made up of one or more key-value
/// pairs, separated by commas and surrounded with square brackets.
///
/// To declare a dictionary, assign a dictionary literal to a variable or
/// constant:
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana",
/// "JP": "Japan", "US": "United States"]
/// // 'countryCodes' has type [String: String]
///
/// print(countryCodes["BR"]!)
/// // Prints "Brazil"
///
/// When the context provides enough type information, you can use a special
/// form of the dictionary literal, square brackets surrounding a single
/// colon, to initialize an empty dictionary.
///
/// var frequencies: [String: Int] = [:]
/// print(frequencies.count)
/// // Prints "0"
///
/// - Note: A dictionary literal is *not* the same as an instance of
/// `Dictionary` or the similarly named `DictionaryLiteral` type. You can't
/// initialize a type that conforms to `ExpressibleByDictionaryLiteral` simply
/// by assigning an instance of one of these types.
///
/// Conforming to the ExpressibleByDictionaryLiteral Protocol
/// =========================================================
///
/// To add the capability to be initialized with a dictionary literal to your
/// own custom types, declare an `init(dictionaryLiteral:)` initializer. The
/// following example shows the dictionary literal initializer for a
/// hypothetical `CountedSet` type, which uses setlike semantics while keeping
/// track of the count for duplicate elements:
///
/// struct CountedSet<Element: Hashable>: Collection, SetAlgebra {
/// // implementation details
///
/// /// Updates the count stored in the set for the given element,
/// /// adding the element if necessary.
/// ///
/// /// - Parameter n: The new count for `element`. `n` must be greater
/// /// than or equal to zero.
/// /// - Parameter element: The element to set the new count on.
/// mutating func updateCount(_ n: Int, for element: Element)
/// }
///
/// extension CountedSet: ExpressibleByDictionaryLiteral {
/// init(dictionaryLiteral elements: (Element, Int)...) {
/// self.init()
/// for (element, count) in elements {
/// self.updateCount(count, for: element)
/// }
/// }
/// }
public protocol ExpressibleByDictionaryLiteral {
/// The key type of a dictionary literal.
associatedtype Key
/// The value type of a dictionary literal.
associatedtype Value
/// Creates an instance initialized with the given key-value pairs.
init(dictionaryLiteral elements: (Key, Value)...)
}
/// A type that can be initialized by string interpolation with a string
/// literal that includes expressions.
///
/// Use string interpolation to include one or more expressions in a string
/// literal, wrapped in a set of parentheses and prefixed by a backslash. For
/// example:
///
/// let price = 2
/// let number = 3
/// let message = "One cookie: $\(price), \(number) cookies: $\(price * number)."
/// print(message)
/// // Prints "One cookie: $2, 3 cookies: $6."
///
/// Conforming to the ExpressibleByStringInterpolation Protocol
/// ===========================================================
///
/// To use string interpolation to initialize instances of your custom type,
/// implement the required initializers for `ExpressibleByStringInterpolation`
/// conformance. String interpolation is a multiple-step initialization
/// process. When you use string interpolation, the following steps occur:
///
/// 1. The string literal is broken into pieces. Each segment of the string
/// literal before, between, and after any included expressions, along with
/// the individual expressions themselves, are passed to the
/// `init(stringInterpolationSegment:)` initializer.
/// 2. The results of those calls are passed to the
/// `init(stringInterpolation:)` initializer in the order in which they
/// appear in the string literal.
///
/// In other words, initializing the `message` constant in the example above
/// using string interpolation is equivalent to the following code:
///
/// let message = String(stringInterpolation:
/// String(stringInterpolationSegment: "One cookie: $"),
/// String(stringInterpolationSegment: price),
/// String(stringInterpolationSegment: ", "),
/// String(stringInterpolationSegment: number),
/// String(stringInterpolationSegment: " cookies: $"),
/// String(stringInterpolationSegment: price * number),
/// String(stringInterpolationSegment: "."))
@available(*, deprecated, message: "it will be replaced or redesigned in Swift 4.0. Instead of conforming to 'ExpressibleByStringInterpolation', consider adding an 'init(_:String)'")
public typealias ExpressibleByStringInterpolation = _ExpressibleByStringInterpolation
public protocol _ExpressibleByStringInterpolation {
/// Creates an instance by concatenating the given values.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use string interpolation. For example:
///
/// let s = "\(5) x \(2) = \(5 * 2)"
/// print(s)
/// // Prints "5 x 2 = 10"
///
/// After calling `init(stringInterpolationSegment:)` with each segment of
/// the string literal, this initializer is called with their string
/// representations.
///
/// - Parameter strings: An array of instances of the conforming type.
init(stringInterpolation strings: Self...)
/// Creates an instance containing the appropriate representation for the
/// given value.
///
/// Do not call this initializer directly. It is used by the compiler for
/// each string interpolation segment when you use string interpolation. For
/// example:
///
/// let s = "\(5) x \(2) = \(5 * 2)"
/// print(s)
/// // Prints "5 x 2 = 10"
///
/// This initializer is called five times when processing the string literal
/// in the example above; once each for the following: the integer `5`, the
/// string `" x "`, the integer `2`, the string `" = "`, and the result of
/// the expression `5 * 2`.
///
/// - Parameter expr: The expression to represent.
init<T>(stringInterpolationSegment expr: T)
}
/// A type that can be initialized using a color literal (e.g.
/// `#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)`).
public protocol _ExpressibleByColorLiteral {
/// Creates an instance initialized with the given properties of a color
/// literal.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a color literal.
init(colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float)
}
/// A type that can be initialized using an image literal (e.g.
/// `#imageLiteral(resourceName: "hi.png")`).
public protocol _ExpressibleByImageLiteral {
/// Creates an instance initialized with the given resource name.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an image literal.
init(imageLiteralResourceName path: String)
}
/// A type that can be initialized using a file reference literal (e.g.
/// `#fileLiteral(resourceName: "resource.txt")`).
public protocol _ExpressibleByFileReferenceLiteral {
/// Creates an instance initialized with the given resource name.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a file reference literal.
init(fileReferenceLiteralResourceName path: String)
}
/// A container is destructor safe if whether it may store to memory on
/// destruction only depends on its type parameters destructors.
/// For example, whether `Array<Element>` may store to memory on destruction
/// depends only on `Element`.
/// If `Element` is an `Int` we know the `Array<Int>` does not store to memory
/// during destruction. If `Element` is an arbitrary class
/// `Array<MemoryUnsafeDestructorClass>` then the compiler will deduce may
/// store to memory on destruction because `MemoryUnsafeDestructorClass`'s
/// destructor may store to memory on destruction.
/// If in this example during `Array`'s destructor we would call a method on any
/// type parameter - say `Element.extraCleanup()` - that could store to memory,
/// then Array would no longer be a _DestructorSafeContainer.
public protocol _DestructorSafeContainer {
}
@available(*, unavailable, renamed: "Bool")
public typealias BooleanType = Bool
// Deprecated by SE-0115.
@available(*, deprecated, renamed: "ExpressibleByNilLiteral")
public typealias NilLiteralConvertible
= ExpressibleByNilLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinIntegerLiteral")
public typealias _BuiltinIntegerLiteralConvertible
= _ExpressibleByBuiltinIntegerLiteral
@available(*, deprecated, renamed: "ExpressibleByIntegerLiteral")
public typealias IntegerLiteralConvertible
= ExpressibleByIntegerLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinFloatLiteral")
public typealias _BuiltinFloatLiteralConvertible
= _ExpressibleByBuiltinFloatLiteral
@available(*, deprecated, renamed: "ExpressibleByFloatLiteral")
public typealias FloatLiteralConvertible
= ExpressibleByFloatLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinBooleanLiteral")
public typealias _BuiltinBooleanLiteralConvertible
= _ExpressibleByBuiltinBooleanLiteral
@available(*, deprecated, renamed: "ExpressibleByBooleanLiteral")
public typealias BooleanLiteralConvertible
= ExpressibleByBooleanLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinUnicodeScalarLiteral")
public typealias _BuiltinUnicodeScalarLiteralConvertible
= _ExpressibleByBuiltinUnicodeScalarLiteral
@available(*, deprecated, renamed: "ExpressibleByUnicodeScalarLiteral")
public typealias UnicodeScalarLiteralConvertible
= ExpressibleByUnicodeScalarLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinExtendedGraphemeClusterLiteral")
public typealias _BuiltinExtendedGraphemeClusterLiteralConvertible
= _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
@available(*, deprecated, renamed: "ExpressibleByExtendedGraphemeClusterLiteral")
public typealias ExtendedGraphemeClusterLiteralConvertible
= ExpressibleByExtendedGraphemeClusterLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinStringLiteral")
public typealias _BuiltinStringLiteralConvertible
= _ExpressibleByBuiltinStringLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinUTF16StringLiteral")
public typealias _BuiltinUTF16StringLiteralConvertible
= _ExpressibleByBuiltinUTF16StringLiteral
@available(*, deprecated, renamed: "ExpressibleByStringLiteral")
public typealias StringLiteralConvertible
= ExpressibleByStringLiteral
@available(*, deprecated, renamed: "ExpressibleByArrayLiteral")
public typealias ArrayLiteralConvertible
= ExpressibleByArrayLiteral
@available(*, deprecated, renamed: "ExpressibleByDictionaryLiteral")
public typealias DictionaryLiteralConvertible
= ExpressibleByDictionaryLiteral
@available(*, deprecated, message: "it will be replaced or redesigned in Swift 4.0. Instead of conforming to 'StringInterpolationConvertible', consider adding an 'init(_:String)'")
public typealias StringInterpolationConvertible
= ExpressibleByStringInterpolation
@available(*, deprecated, renamed: "_ExpressibleByColorLiteral")
public typealias _ColorLiteralConvertible
= _ExpressibleByColorLiteral
@available(*, deprecated, renamed: "_ExpressibleByImageLiteral")
public typealias _ImageLiteralConvertible
= _ExpressibleByImageLiteral
@available(*, deprecated, renamed: "_ExpressibleByFileReferenceLiteral")
public typealias _FileReferenceLiteralConvertible
= _ExpressibleByFileReferenceLiteral
| 44373a3c1b887e8e9eb7d44d1100279b | 40.177305 | 183 | 0.696722 | false | false | false | false |
cloudinary/cloudinary_ios | refs/heads/master | Cloudinary/Classes/Core/Features/CacheSystem/StorehouseLibrary/Core/StorehouseAccess/StorehouseAccessor.swift | mit | 1 | //
// StorehouseAccessor.swift
//
// Copyright (c) 2020 Cloudinary (http://cloudinary.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Dispatch
///
///
///
internal class StorehouseAccessor<StoredItem>
{
/// MARK: - Typealias
internal typealias Item = StoredItem
/// MARK: - Public Properties
internal var storehouse : StorehouseHybrid<Item>
internal let accessQueue : DispatchQueue
internal var memoryCapacity : Int {
var value : Int!
accessQueue.sync { value = storehouse.memoryCapacity }
return value
}
internal var diskCapacity : Int {
var value : Int!
accessQueue.sync { value = storehouse.diskCapacity }
return value
}
internal var currentMemoryUsage : Int {
var value : Int!
accessQueue.sync { value = storehouse.currentMemoryUsage }
return value
}
internal var currentDiskUsage: Int {
var value : Int!
accessQueue.sync { value = storehouse.currentDiskUsage }
return value
}
/// MARK: - Initializers
internal init(storage: StorehouseHybrid<Item>, queue: DispatchQueue)
{
self.storehouse = storage
self.accessQueue = queue
}
internal func replaceStorage(_ storage: StorehouseHybrid<Item>)
{
accessQueue.sync(flags: [.barrier]) {
self.storehouse = storage
}
}
}
extension StorehouseAccessor : StorehouseProtocol
{
@discardableResult
internal func entry(forKey key: String) throws -> StorehouseEntry<Item>
{
var entry : StorehouseEntry<Item>!
try accessQueue.sync {
entry = try storehouse.entry(forKey: key)
}
return entry
}
internal func removeObject(forKey key: String) throws
{
try accessQueue.sync(flags: [.barrier]) {
try self.storehouse.removeObject(forKey: key)
}
}
internal func setObject(_ object: Item, forKey key: String, expiry: StorehouseExpiry? = nil) throws
{
try accessQueue.sync(flags: [.barrier]) {
try storehouse.setObject(object, forKey: key, expiry: expiry)
}
}
internal func removeAll() throws
{
try accessQueue.sync(flags: [.barrier]) {
try storehouse.removeAll()
}
}
internal func removeExpiredObjects() throws
{
try accessQueue.sync(flags: [.barrier]) {
try storehouse.removeExpiredObjects()
}
}
internal func removeStoredObjects(since date: Date) throws
{
try accessQueue.sync(flags: [.barrier]) {
try storehouse.removeStoredObjects(since: date)
}
}
internal func removeObjectIfExpired(forKey key: String) throws
{
try accessQueue.sync(flags: [.barrier]) {
try storehouse.removeObjectIfExpired(forKey: key)
}
}
}
| 5daae28b1854bda6313673601e5d1ac0 | 29.823077 | 103 | 0.649863 | false | false | false | false |
pusher-community/pusher-websocket-swift | refs/heads/master | Sources/Helpers/EventParser.swift | mit | 2 | import Foundation
struct EventParser {
/**
Parse a string to extract Pusher event information from it
- parameter string: The string received over the websocket connection containing
Pusher event information
- returns: A dictionary of Pusher-relevant event data
*/
static func getPusherEventJSON(from string: String) -> [String: AnyObject]? {
let data = (string as NSString).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)
do {
if let jsonData = data,
let jsonObject = try JSONSerialization.jsonObject(with: jsonData,
options: []) as? [String: AnyObject] {
return jsonObject
} else {
Logger.shared.debug(for: .unableToParseStringAsJSON,
context: string)
}
} catch let error as NSError {
Logger.shared.error(for: .genericError,
context: error.localizedDescription)
}
return nil
}
/**
Parse a string to extract Pusher event data from it
- parameter string: The data string received as part of a Pusher message
- returns: The object sent as the payload part of the Pusher message
*/
static func getEventDataJSON(from string: String) -> Any? {
let data = (string as NSString).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)
do {
if let jsonData = data, let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) {
return jsonObject
} else {
Logger.shared.debug(for: .unableToParseStringAsJSON,
context: string)
}
}
return nil
}
}
| 93d4e2731ad59a62f200ba6b968c3e82 | 34.471698 | 117 | 0.573404 | false | false | false | false |
lazerwalker/storyboard-iOS | refs/heads/master | Storyboard-Example/ProjectListViewController.swift | mit | 1 | import UIKit
class ProjectListViewController : UITableViewController {
let projects:[String]
let handler:(String?) -> Void
required init(projects:[String], handler:@escaping ((String?) -> Void)) {
self.projects = projects
self.handler = handler
super.init(style: .plain)
self.title = "Projects"
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(ProjectListViewController.cancel))
}
required init?(coder aDecoder: NSCoder) {
projects = []
handler = { _ in }
super.init(coder: aDecoder)
}
//-
@objc func cancel() {
self.handler(nil)
}
//- UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
let project = projects[indexPath.row]
self.handler(project)
}
//- UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return projects.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = projects[indexPath.row]
return cell
}
}
| 002e94c39556db6ad6a13e038995974a | 29.58 | 160 | 0.669065 | false | false | false | false |
quickthyme/PUTcat | refs/heads/master | PUTcat/Application/Data/Service/Entity/PCService.swift | apache-2.0 | 1 |
import Foundation
final class PCService: PCItem, PCCopyable, PCLocal {
var id: String
var name: String
var transactions : PCList<PCTransaction>?
init(id: String, name: String) {
self.id = id
self.name = name
}
convenience init(name: String) {
self.init(id: UUID().uuidString, name: name)
}
convenience init() {
self.init(name: "New Service")
}
required convenience init(copy: PCService) {
self.init(name: copy.name)
self.transactions = copy.transactions?.copy()
}
required init(fromLocal: [String:Any]) {
self.id = fromLocal["id"] as? String ?? ""
self.name = fromLocal["name"] as? String ?? ""
}
func toLocal() -> [String:Any] {
return [
"id" : self.id,
"name" : self.name
]
}
}
extension PCService : PCLocalExport {
func toLocalExport() -> [String:Any] {
var local = self.toLocal()
if let array = self.transactions?.toLocalExport() {
local["transactions"] = array
}
return local
}
}
| 3fb3b8cb268e218a83395717556c6fba | 22.163265 | 59 | 0.548018 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | refs/heads/master | Solutions/SolutionsTests/Medium/Medium_075_Sort_Colors_Test.swift | mit | 1 | //
// Medium_075_Sort_Colors_Test.swift
// Solutions
//
// Created by Di Wu on 7/30/15.
// Copyright © 2015 diwu. All rights reserved.
//
import XCTest
class Medium_075_Sort_Colors_Test: XCTestCase, SolutionsTestCase {
func test_001() {
var input: [Int] = [2, 1, 1, 2, 2, 1, 0, 0, 1, 2]
let expected: [Int] = [0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
asyncHelper(input: &input, expected: expected)
}
private func asyncHelper(input: inout [Int], expected: [Int]) {
weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
var localInput = input
serialQueue().async(execute: { () -> Void in
Medium_075_Sort_Colors.sortColors(&localInput)
let result = localInput
assertHelper(result == expected, problemName:self.problemName(), input: localInput, resultValue: result, expectedValue: expected)
if let unwrapped = expectation {
unwrapped.fulfill()
}
})
waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
if error != nil {
assertHelper(false, problemName:self.problemName(), input: localInput, resultValue:self.timeOutName(), expectedValue: expected)
}
}
}
}
| cd4120f893de8de4c5348944a1d8e66c | 37.205882 | 143 | 0.603541 | false | true | false | false |
icylydia/PlayWithLeetCode | refs/heads/master | 260. Single Number III/solution.swift | mit | 1 | class Solution {
func singleNumber(nums: [Int]) -> [Int] {
let xor = nums.reduce(0){$0^$1}
var diffBit = 1
while(diffBit & xor == 0) {
diffBit <<= 1
}
var groupA = Array<Int>()
var groupB = Array<Int>()
for num in nums {
if num & diffBit == 0 {
groupA.append(num)
} else {
groupB.append(num)
}
}
let a = groupA.reduce(0){$0^$1}
let b = groupB.reduce(0){$0^$1}
return [a, b]
}
} | 8be73d51fa6001ab04c6f8776cb39012 | 21.809524 | 45 | 0.485356 | false | false | false | false |
Drusy/auvergne-webcams-ios | refs/heads/master | Carthage/Checkouts/Eureka/Example/Example/Controllers/ListSectionsController.swift | apache-2.0 | 4 | //
// ListSectionsController.swift
// Example
//
// Created by Mathias Claassen on 3/15/18.
// Copyright © 2018 Xmartlabs. All rights reserved.
//
import Eureka
class ListSectionsController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
let continents = ["Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America"]
form +++ SelectableSection<ImageCheckRow<String>>() { section in
section.header = HeaderFooterView(title: "Where do you live?")
}
for option in continents {
form.last! <<< ImageCheckRow<String>(option){ lrow in
lrow.title = option
lrow.selectableValue = option
lrow.value = nil
}
}
let oceans = ["Arctic", "Atlantic", "Indian", "Pacific", "Southern"]
form +++ SelectableSection<ImageCheckRow<String>>("And which of the following oceans have you taken a bath in?", selectionType: .multipleSelection)
for option in oceans {
form.last! <<< ImageCheckRow<String>(option){ lrow in
lrow.title = option
lrow.selectableValue = option
lrow.value = nil
}.cellSetup { cell, _ in
cell.trueImage = UIImage(named: "selectedRectangle")!
cell.falseImage = UIImage(named: "unselectedRectangle")!
cell.accessoryType = .checkmark
}
}
}
override func valueHasBeenChanged(for row: BaseRow, oldValue: Any?, newValue: Any?) {
if row.section === form[0] {
print("Single Selection:\((row.section as! SelectableSection<ImageCheckRow<String>>).selectedRow()?.baseValue ?? "No row selected")")
}
else if row.section === form[1] {
print("Mutiple Selection:\((row.section as! SelectableSection<ImageCheckRow<String>>).selectedRows().map({$0.baseValue}))")
}
}
}
| 1c5890a877188d128047e1b910ea3329 | 36 | 155 | 0.589089 | false | false | false | false |
wildthink/DataBasis | refs/heads/master | DataBasis/CSVAtomicStore.swift | mit | 1 | //
// CSVAtomicStore.swift
// Pods
//
// Created by Jason Jobe on 5/28/16.
//
//
import Cocoa
class CSVAtomicStore: NSAtomicStore {
enum Error: ErrorType {
case InvalidFormat
case InaccessableURL
}
var dateFormatter: NSDateFormatter
private var cache = [NSManagedObjectID: AnyObject]()
var localStorageURL: NSURL?
var primaryKey: String = "_id"
var entityKey: String = "_entity"
class var storeType: String {
return NSStringFromClass(JSONAtomicStore.self)
}
override class func initialize() {
NSPersistentStoreCoordinator.registerStoreClass(self, forStoreType:self.storeType)
}
override init(persistentStoreCoordinator root: NSPersistentStoreCoordinator?, configurationName name: String?, URL url: NSURL, options: [NSObject : AnyObject]?) {
self.localStorageURL = url
dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
super.init(persistentStoreCoordinator: root, configurationName: name, URL: url, options: options)
}
// MARK: - NSAtomicStore
override func loadMetadata() throws {
let uuid = NSProcessInfo.processInfo().globallyUniqueString
self.metadata = [NSStoreTypeKey : JSONAtomicStore.storeType, NSStoreUUIDKey : uuid]
}
override func load() throws
{
guard let items = try self.loadObjectsFromJSON() else { return }
for value in items {
if let item = value as? [String: AnyObject] {
cacheNodeForValues(item)
}
}
}
// MARK: - Private
func createRelationship (relationship: NSRelationshipDescription, from subject: AnyObject, to object: AnyObject, includeInverse: Bool = true) {
let key = relationship.name
if relationship.toMany {
if var rel_object = subject.valueForKey (key) as? [AnyObject] {
rel_object.append(object)
} else {
subject.setValue([object], forKey: key)
}
} else {
subject.setValue(object, forKey: key)
}
guard includeInverse else { return }
if let inverse = relationship.inverseRelationship {
// NOTE: includeInverse MUST be false to avoid infinite recursion
createRelationship(inverse, from: object, to: subject, includeInverse: false)
}
}
func entityNamed (name: String?) -> NSEntityDescription? {
guard let name = name else { return nil }
return persistentStoreCoordinator?.managedObjectModel.entitiesByName[name]
}
func transformValue (attribute: NSAttributeDescription, from input: AnyObject?) -> AnyObject? {
var value: AnyObject? = nil
guard let input = input?.description else { return nil }
switch attribute.attributeType
{
case .DateAttributeType: value = dateFormatter.dateFromString(input)
case .StringAttributeType: value = input
case .Integer16AttributeType: value = Int(input)
case .Integer32AttributeType: value = Int(input)
case .Integer64AttributeType: value = Int(input)
case .FloatAttributeType: value = Float(input)
case .DoubleAttributeType: value = Double(input)
case .DecimalAttributeType: value = NSDecimalNumber(string: input, locale: nil)
default:
value = input
Swift.print ("\(attribute.attributeType.rawValue) is PASS THRU")
}
return value
}
func cacheNodeForValues (values: [String: AnyObject]) -> NSAtomicStoreCacheNode?
{
guard let entity = entityNamed(values[entityKey] as? String) else { return nil }
guard let referenceId = values[primaryKey] as? String else { return nil }
let objectId = objectIDForEntity(entity, referenceObject: referenceId)
// Make sure we avoid creating duplicates
if let found = self.cacheNodeForObjectID(objectId) { return found }
let node = NSAtomicStoreCacheNode(objectID: objectId)
var nodes = Set<NSAtomicStoreCacheNode>()
nodes.insert(node)
for (key, attr) in entity.attributesByName {
var value: AnyObject?
node.setValue(value, forKey: key)
}
for (key, rel) in entity.relationshipsByName
{
if let values = values[key] as? [String: AnyObject],
let object = cacheNodeForValues(values)
{
nodes.insert(object)
createRelationship (rel, from: node, to: object)
}
}
self.addCacheNodes(nodes)
return node
}
/**
Loads object data from a local JSON file
- returns An Array of object objects in dictionary form.
*/
func loadObjectsFromJSON() throws -> [AnyObject]? {
guard let localStorageURL = localStorageURL else { return nil }
guard let data = NSData(contentsOfURL: localStorageURL) else { throw Error.InvalidFormat }
do {
let results = try NSJSONSerialization.JSONObjectWithData(data, options: [])
guard let objects = results as? [NSDictionary] else {
return nil
}
return objects
}
catch {
throw Error.InvalidFormat
}
}
}
| baab37e924e184da3ac22d5834affb42 | 32.193939 | 166 | 0.633193 | false | false | false | false |
CodaFi/swift | refs/heads/main | tools/swift-inspect/Sources/swift-inspect/RemoteMirrorExtensions.swift | apache-2.0 | 10 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftRemoteMirror
extension SwiftReflectionContextRef {
struct Error: Swift.Error, CustomStringConvertible {
var description: String
init(cString: UnsafePointer<CChar>) {
description = String(cString: cString)
}
}
func name(metadata: swift_reflection_ptr_t) -> String? {
let tr = swift_reflection_typeRefForMetadata(self, UInt(metadata));
guard tr != 0 else { return nil }
guard let cstr = swift_reflection_copyDemangledNameForTypeRef(self, tr)
else { return nil }
defer { free(cstr) }
return String(cString: cstr)
}
func name(proto: swift_reflection_ptr_t) -> String? {
guard let cstr = swift_reflection_copyDemangledNameForProtocolDescriptor(
self, proto) else { return nil }
defer { free(cstr) }
return String(cString: cstr)
}
func iterateConformanceCache(
_ body: (swift_reflection_ptr_t, swift_reflection_ptr_t) -> Void
) throws {
var body = body
let errStr = swift_reflection_iterateConformanceCache(self, {
let callPtr = $2!.bindMemory(to:
((swift_reflection_ptr_t, swift_reflection_ptr_t) -> Void).self,
capacity: 1)
callPtr.pointee($0, $1)
}, &body)
try throwError(str: errStr)
}
func iterateMetadataAllocations(
_ body: (swift_metadata_allocation_t) -> Void
) throws {
var body = body
let errStr = swift_reflection_iterateMetadataAllocations(self, {
let callPtr = $1!.bindMemory(to:
((swift_metadata_allocation_t) -> Void).self, capacity: 1)
callPtr.pointee($0)
}, &body)
try throwError(str: errStr)
}
func iterateMetadataAllocationBacktraces(
_ body: (swift_reflection_ptr_t, Int, UnsafePointer<swift_reflection_ptr_t>)
-> Void
) throws {
var body = body
let errStr = swift_reflection_iterateMetadataAllocationBacktraces(self, {
let callPtr = $3!.bindMemory(to:
((swift_reflection_ptr_t, Int, UnsafePointer<swift_reflection_ptr_t>)
-> Void).self, capacity: 1)
callPtr.pointee($0, $1, $2!)
}, &body)
try throwError(str: errStr)
}
func metadataPointer(
allocation: swift_metadata_allocation_t
) -> swift_reflection_ptr_t {
swift_reflection_allocationMetadataPointer(self, allocation)
}
func metadataTagName(_ tag: swift_metadata_allocation_tag_t) -> String? {
swift_reflection_metadataAllocationTagName(self, tag)
.map(String.init)
}
func metadataAllocationCacheNode(
_ allocation: swift_metadata_allocation_t
) -> swift_metadata_cache_node_t? {
var node = swift_metadata_cache_node_t();
let success = swift_reflection_metadataAllocationCacheNode(
self, allocation, &node)
if success == 0 {
return nil
}
return node
}
private func throwError(str: UnsafePointer<CChar>?) throws {
if let str = str {
throw Error(cString: str)
}
}
var allocations: [Allocation] {
var allocations: [Allocation] = []
try! iterateMetadataAllocations { allocation_t in
allocations.append(.init(allocation_t: allocation_t))
}
return allocations
}
var allocationBacktraces: [swift_reflection_ptr_t: Backtrace] {
var backtraces: [swift_reflection_ptr_t: Backtrace] = [:]
try! iterateMetadataAllocationBacktraces { allocation, count, ptrs in
let array = Array(UnsafeBufferPointer(start: ptrs, count: count))
backtraces[allocation] = Backtrace(ptrs: array)
}
return backtraces
}
}
| 1ca6ae91eccb1623d327f1a8ca05bad0 | 30.928 | 80 | 0.649712 | false | false | false | false |
visualitysoftware/swift-sdk | refs/heads/master | CloudBoost/CloudFile.swift | mit | 1 | //
// CloudFile.swift
// CloudBoost
//
// Created by Randhir Singh on 31/03/16.
// Copyright © 2016 Randhir Singh. All rights reserved.
//
import Foundation
public class CloudFile {
var document = NSMutableDictionary()
private var data: NSData?
private var strEncodedData: String?
public init(name: String, data: NSData, contentType: String){
self.data = data
self.strEncodedData = data.base64EncodedStringWithOptions([])
document["_id"] = nil
document["_type"] = "file"
document["ACL"] = ACL().getACL()
document["name"] = name
document["size"] = data.length
document["url"] = nil
document["expires"] = nil
document["contentType"] = contentType
}
public init(id: String){
document["_id"] = id
}
public init(doc: NSMutableDictionary){
self.document = doc
self.data = nil
}
// MARK: Getters
public func getId() -> String? {
return document["_id"] as? String
}
public func getContentType() -> String? {
return document["contentType"] as? String
}
public func getFileUrl() -> String? {
return document["url"] as? String
}
public func getFileName() -> String? {
return document["name"] as? String
}
public func getACL() -> ACL? {
if let acl = document["ACL"] as? NSMutableDictionary {
return ACL(acl: acl)
}
return nil
}
public func getData() -> NSData? {
return data
}
public func getExpires() -> NSDate? {
if let expires = document["expires"] as? String {
return CloudBoostDateFormatter.getISOFormatter().dateFromString(expires)
}
return nil
}
public func setExpires(date: NSDate) {
document["expires"] = CloudBoostDateFormatter.getISOFormatter().stringFromDate(date)
}
// MARK: Setters
public func setId(id: String){
document["_id"] = id
}
public func setContentType(contentType: String){
document["contentType"] = contentType
}
public func setFileUrl(url: String){
document["url"] = url
}
public func setFileName(name: String){
document["name"] = name
}
public func setACL(acl: ACL){
document["ACL"] = acl.getACL()
}
public func setDate(data: NSData) {
self.data = data
self.strEncodedData = data.base64EncodedStringWithOptions([])
}
// Save a CloudFile object
public func save(callback: (response: CloudBoostResponse) -> Void){
let params = NSMutableDictionary()
params["key"] = CloudApp.getAppKey()!
params["fileObj"] = self.document
params["data"] = self.strEncodedData
let url = CloudApp.getApiUrl() + "/file/" + CloudApp.getAppId()!
CloudCommunications._request("POST", url: NSURL(string: url)!, params: params, callback: {
(response: CloudBoostResponse) in
if(response.success) {
self.document = (response.object as? NSMutableDictionary)!
}
callback(response: response)
})
}
// Save an array of CloudFile
public static func saveAll(array: [CloudFile], callback: (CloudBoostResponse)->Void) {
// Ready the response
let resp = CloudBoostResponse()
resp.success = true
var count = 0
// Iterate through the array
for object in array {
let url = CloudApp.serverUrl + "/file/" + CloudApp.appID!
let params = NSMutableDictionary()
params["key"] = CloudApp.appKey!
params["fileObj"] = object.document
params["data"] = object.strEncodedData
CloudCommunications._request("POST", url: NSURL(string: url)!, params: params, callback:
{(response: CloudBoostResponse) in
count += 1
if(response.success){
if let newDocument = response.object {
object.document = newDocument as! NSMutableDictionary
}
}else{
resp.success = false
resp.message = "one or more objects were not saved"
}
if(count == array.count){
resp.object = count
callback(resp)
}
})
}
}
// delete a CloudFile
public func delete(callback: (response: CloudBoostResponse) -> Void) throws {
guard let _ = document["url"] else{
throw CloudBoostError.InvalidArgument
}
let params = NSMutableDictionary()
params["fileObj"] = document
params["key"] = CloudApp.getAppKey()!
let url = CloudApp.getApiUrl() + "/file/" + CloudApp.getAppId()! + "/" + self.getId()!
CloudCommunications._request("DELETE", url: NSURL(string: url)!, params: params, callback: {
(response: CloudBoostResponse) in
if response.success && (response.status >= 200 || response.status < 300) {
self.document = [:]
}
callback(response: response)
})
}
public static func getFileFromUrl(url: NSURL, callback: (response: CloudBoostResponse)->Void){
let cbResponse = CloudBoostResponse()
cbResponse.success = false
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
data, response, error -> Void in
guard let httpRes = response as? NSHTTPURLResponse else {
cbResponse.message = "Proper response not received"
callback(response: cbResponse)
return
}
cbResponse.status = httpRes.statusCode
if( httpRes.statusCode == 200){
guard let strEncodedData = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String else {
cbResponse.message = "Error in encoding/decoding"
callback(response: cbResponse)
return
}
let nsData = NSData(base64EncodedString: strEncodedData, options: [])
cbResponse.success = true
cbResponse.object = nsData
} else {
cbResponse.message = "\(httpRes.statusCode) error"
}
callback(response: cbResponse)
}).resume()
}
public func uploadSave(progressCallback : (response: CloudBoostProgressResponse)->Void){
let params = NSMutableDictionary()
params["key"] = CloudApp.getAppKey()!
params["fileObj"] = self.document
params["data"] = self.strEncodedData
let url = CloudApp.getApiUrl() + "/file/" + CloudApp.getAppId()!
CloudCommunications()._requestFile("POST", url: NSURL(string: url)!, params: params, data: data, uploadCallback: {
uploadResponse in
progressCallback(response: uploadResponse)
})
}
public func fetch(callback: (CloudBoostResponse)->Void){
let res = CloudBoostResponse()
let query = CloudQuery(tableName: "_File")
if getId() == nil {
res.message = "ID not set in the object"
callback(res)
}else{
try! query.equalTo("id", obj: getId()!)
query.setLimit(1)
query.find({ res in
if res.success {
if let obj = res.object as? [NSMutableDictionary] {
self.document = obj[0]
callback(res)
}else{
res.success = false
res.message = "Invalid response received"
callback(res)
}
}
})
}
}
} | 5607748f151073f5dddde5d036fa88ac | 31.375 | 122 | 0.536262 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/2 - Primitives/Media/Media.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AVKit
import CasePaths
import Extensions
import Nuke
import NukeUI
import SwiftUI
import UniformTypeIdentifiers
public typealias Media = NukeUI.Image
@MainActor
public struct AsyncMedia<Content: View>: View {
private let url: URL?
private let transaction: Transaction
private let content: (AsyncPhase<Media>) -> Content
@Environment(\.resizingMode) var resizingMode
public init(
url: URL?,
transaction: Transaction = Transaction(),
@ViewBuilder content: @escaping (AsyncPhase<Media>) -> Content
) {
self.url = url
self.transaction = transaction
self.content = content
}
public var body: some View {
LazyImage(
url: url,
content: { state in
withTransaction(transaction) {
which(state)
}
}
)
}
@ViewBuilder
private func which(_ state: LazyImageState) -> some View {
if let image: NukeUI.Image = state.image {
#if os(macOS)
content(.success(image))
#else
content(.success(image.resizingMode(resizingMode.imageResizingMode)))
#endif
} else if let error = state.error {
content(.failure(error))
} else {
content(.empty)
}
}
}
extension AsyncMedia {
public init(
url: URL?,
transaction: Transaction = Transaction()
) where Content == _ConditionalContent<Media, ProgressView<EmptyView, EmptyView>>? {
self.init(url: url, transaction: transaction, placeholder: { ProgressView() })
}
public init<I: View, P: View>(
url: URL?,
transaction: Transaction = Transaction(),
@ViewBuilder content: @escaping (Media) -> I,
@ViewBuilder placeholder: @escaping () -> P
) where Content == _ConditionalContent<_ConditionalContent<I, EmptyView>, P> {
self.init(url: url, transaction: transaction, content: content, failure: { _ in EmptyView() }, placeholder: placeholder)
}
public init<I: View, F: View, P: View>(
url: URL?,
transaction: Transaction = Transaction(),
@ViewBuilder content: @escaping (Media) -> I,
@ViewBuilder failure: @escaping (Error) -> F,
@ViewBuilder placeholder: @escaping () -> P
) where Content == _ConditionalContent<_ConditionalContent<I, F>, P> {
self.init(url: url, transaction: transaction) { phase in
switch phase {
case .success(let media):
content(media)
case .failure(let error):
failure(error)
case .empty:
placeholder()
}
}
}
public init<P: View>(
url: URL?,
transaction: Transaction = Transaction(),
@ViewBuilder placeholder: @escaping () -> P
) where Content == _ConditionalContent<Media, P>? {
self.init(
url: url,
transaction: transaction,
content: { phase in
if case .success(let media) = phase {
media
} else if case .empty = phase {
placeholder()
}
}
)
}
}
extension URL {
var uniformTypeIdentifier: UTType? { UTType(filenameExtension: pathExtension) }
}
extension EnvironmentValues {
public var resizingMode: MediaResizingMode {
get { self[ImageResizingModeEnvironmentKey.self] }
set { self[ImageResizingModeEnvironmentKey.self] = newValue }
}
}
private struct ImageResizingModeEnvironmentKey: EnvironmentKey {
static var defaultValue = MediaResizingMode.aspectFit
}
extension View {
@warn_unqualified_access @inlinable
public func resizingMode(_ resizingMode: MediaResizingMode) -> some View {
environment(\.resizingMode, resizingMode)
}
}
public enum MediaResizingMode: String, Codable {
case fill
case aspectFit = "aspect_fit"
case aspectFill = "aspect_fill"
case center
case top
case bottom
case left
case right
case topLeft = "top_left"
case topRight = "top_right"
case bottomLeft = "bottom_left"
case bottomRight = "bottom_right"
}
extension MediaResizingMode {
@usableFromInline var imageResizingMode: ImageResizingMode {
switch self {
case .fill: return .fill
case .aspectFit: return .aspectFit
case .aspectFill: return .aspectFill
case .center: return .center
case .top: return .top
case .bottom: return .bottom
case .left: return .left
case .right: return .right
case .topLeft: return .topLeft
case .topRight: return .topRight
case .bottomLeft: return .bottomLeft
case .bottomRight: return .bottomRight
}
}
}
| 72813ece76e70c3ae91482e45491df1a | 27.439306 | 128 | 0.6 | false | false | false | false |
Electrode-iOS/ELHybridWeb | refs/heads/master | Source/Web View/WebViewController.swift | mit | 2 | //
// WebViewController.swift
// ELHybridWeb
//
// Created by Angelo Di Paolo on 4/16/15.
// Copyright (c) 2015 WalmartLabs. All rights reserved.
//
import Foundation
import JavaScriptCore
import UIKit
/**
Defines methods that a delegate of a WebViewController object can optionally
implement to interact with the web view's loading cycle.
*/
@objc public protocol WebViewControllerDelegate {
/**
Sent before the web view begins loading a frame.
- parameter webViewController: The web view controller loading the web view frame.
- parameter request: The request that will load the frame.
- parameter navigationType: The type of user action that started the load.
- returns: Return true to
*/
@objc optional func webViewController(_ webViewController: WebViewController, shouldStartLoadWithRequest request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool
/**
Sent before the web view begins loading a frame.
- parameter webViewController: The web view controller that has begun loading the frame.
*/
@objc optional func webViewControllerDidStartLoad(_ webViewController: WebViewController)
/**
Sent after the web view as finished loading a frame.
- parameter webViewController: The web view controller that has completed loading the frame.
*/
@objc optional func webViewControllerDidFinishLoad(_ webViewController: WebViewController)
/**
Sent if the web view fails to load a frame.
- parameter webViewController: The web view controller that failed to load the frame.
- parameter error: The error that occured during loading.
*/
@objc optional func webViewController(_ webViewController: WebViewController, didFailLoadWithError error: Error)
/**
Sent when the web view creates the JS context for the frame.
parameter webViewController: The web view controller that failed to load the frame.
parameter context: The newly created JavaScript context.
*/
@objc optional func webViewControllerDidCreateJavaScriptContext(_ webViewController: WebViewController, context: JSContext)
}
/**
A view controller that integrates a web view with the hybrid JavaScript API.
# Usage
Initialize a web view controller and call `loadURL()` to asynchronously load
the web view with a URL.
```
let webController = WebViewController()
webController.loadURL(NSURL(string: "foo")!)
window?.rootViewController = webController
```
Call `addBridgeAPIObject()` to add the bridged JavaScript API to the web view.
The JavaScript API will be accessible to any web pages that are loaded in the
web view controller.
```
let webController = WebViewController()
webController.addBridgeAPIObject()
webController.loadURL(NSURL(string: "foo")!)
window?.rootViewController = webController
```
To utilize the navigation JavaScript API you must provide a navigation
controller for the web view controller.
```
let webController = WebViewController()
webController.addBridgeAPIObject()
webController.loadURL(NSURL(string: "foo")!)
let navigationController = UINavigationController(rootViewController: webController)
window?.rootViewController = navigationController
```
*/
open class WebViewController: UIViewController {
public enum AppearenceCause {
case unknown, webPush, webPop, webModal, webDismiss, external
}
/// The URL that was loaded with `loadURL()`
private(set) public var url: URL?
/// The web view used to load and render the web content.
@objc private(set) public lazy var webView: UIWebView = {
let webView = UIWebView(frame: CGRect.zero)
webView.delegate = self
WebViewManager.addBridgedWebView(webView: webView)
webView.translatesAutoresizingMaskIntoConstraints = false
return webView
}()
fileprivate(set) public var bridgeContext: JSContext! = JSContext()
private var storedScreenshotGUID: String? = nil
private var firstLoadCycleCompleted = true
fileprivate (set) var disappearedBy = AppearenceCause.unknown
private var storedAppearence = AppearenceCause.webPush
// TODO: make appearedFrom internal in Swift 2 with @testable
private (set) public var appearedFrom: AppearenceCause {
get {
switch disappearedBy {
case .webPush: return .webPop
case .webModal: return .webDismiss
default: return storedAppearence
}
}
set {
storedAppearence = newValue
}
}
private lazy var placeholderImageView: UIImageView = {
return UIImageView(frame: self.view.bounds)
}()
public var errorView: UIView?
public var errorLabel: UILabel?
public var reloadButton: UIButton?
public weak var hybridAPI: HybridAPI?
private (set) weak var externalPresentingWebViewController: WebViewController?
private(set) public var externalReturnURL: URL?
/// Handles web view controller events.
@objc public weak var delegate: WebViewControllerDelegate?
/// Set `false` to disable error message UI.
public var showErrorDisplay = true
/// An optional custom user agent string to be used in the header when loading the URL.
@objc public var userAgent: String?
/// Host for NSURLSessionDelegate challenge
@objc public var challengeHost: String?
lazy public var urlSession: URLSession = {
let configuration: URLSessionConfiguration = URLSessionConfiguration.default
if let agent = self.userAgent {
configuration.httpAdditionalHeaders = [
"User-Agent": agent
]
}
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
return session
}()
/// A NSURLSessionDataTask object used to load the URLs
public var dataTask: URLSessionDataTask?
/**
Initialize a web view controller instance with a web view and JavaScript
bridge. The newly initialized web view controller becomes the delegate of
the web view.
:param: webView The web view to use in the web view controller.
:param: bridge The bridge instance to integrate int
*/
public required init(webView: UIWebView, context: JSContext) {
super.init(nibName: nil, bundle: nil)
self.bridgeContext = context
self.webView = webView
self.webView.delegate = self
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
if webView.delegate === self {
webView.delegate = nil
}
}
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
edgesForExtendedLayout = []
view.addSubview(placeholderImageView)
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
switch appearedFrom {
case .webPush, .webModal, .webPop, .webDismiss, .external:
webView.delegate = self
webView.removeFromSuperview() // remove webView from previous view controller's view
webView.frame = view.bounds
view.addSubview(webView) // add webView to this view controller's view
// Pin web view top and bottom to top and bottom of view
if #available(iOS 11.0, *) {
webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
webView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
} else {
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[webView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["webView" : webView]))
}
// Pin web view sides to sides of view
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[webView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["webView" : webView]))
view.removeDoubleTapGestures()
if let storedScreenshotGUID = storedScreenshotGUID {
placeholderImageView.image = UIImage.loadImageFromGUID(guid: storedScreenshotGUID)
view.bringSubviewToFront(placeholderImageView)
}
case .unknown: break
}
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
hybridAPI?.view.appeared()
switch appearedFrom {
case .webPop, .webDismiss: addBridgeAPIObject()
case .webPush, .webModal, .external, .unknown: break
}
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
switch disappearedBy {
case .webPop, .webDismiss, .webPush, .webModal:
// only store screen shot when disappearing by web transition
placeholderImageView.frame = webView.frame // must align frames for image capture
if let screenshotImage = webView.captureImage() {
placeholderImageView.image = screenshotImage
storedScreenshotGUID = screenshotImage.saveImageToGUID()
}
view.bringSubviewToFront(placeholderImageView)
webView.isHidden = true
case .unknown:
if isMovingFromParent {
webView.isHidden = true
}
case .external: break
}
if disappearedBy != .webPop && isMovingFromParent {
hybridAPI?.navigation.back()
}
hybridAPI?.view.disappeared() // needs to be called in viewWillDisappear not Did
switch disappearedBy {
// clear out parent reference to prevent the popping view's onAppear from
// showing the web view too early
case .webPop,
.unknown where isMovingFromParent:
hybridAPI?.parentViewController = nil
default: break
}
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
switch disappearedBy {
case .webPop, .webDismiss, .webPush, .webModal, .external:
// we're gone. dump the screenshot, we'll load it later if we need to.
placeholderImageView.image = nil
case .unknown:
// we don't know how it will appear if we don't know how it disappeared
appearedFrom = .unknown
}
}
public final func showWebView() {
webView.isHidden = false
placeholderImageView.image = nil
view.sendSubviewToBack(placeholderImageView)
}
// MARK: Request Loading
/**
Load the web view with the provided URL.
:param: url The URL used to load the web view.
*/
@objc final public func load(url: URL) {
self.dataTask?.cancel() // cancel any running task
hybridAPI = nil
firstLoadCycleCompleted = false
self.url = url
let request = self.request(url: url)
self.dataTask = self.urlSession.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
DispatchQueue.main.async {
if let httpError = error {
// render error display
if self.showErrorDisplay {
self.renderFeatureErrorDisplayWithError(error: httpError, featureName: self.featureName(forError: httpError))
}
} else if let urlResponse = response as? HTTPURLResponse {
if urlResponse.statusCode >= 400 {
// render error display
if self.showErrorDisplay {
let httpError = NSError(domain: "WebViewController", code: urlResponse.statusCode, userInfo: ["response" : urlResponse, NSLocalizedDescriptionKey : "HTTP Response Status \(urlResponse.statusCode)"])
self.renderFeatureErrorDisplayWithError(error: httpError, featureName: self.featureName(forError: httpError))
}
} else if let data = data,
let MIMEType = urlResponse.mimeType,
let textEncodingName = urlResponse.textEncodingName,
let url = urlResponse.url {
self.webView.load(data, mimeType: MIMEType, textEncodingName: textEncodingName, baseURL: url)
}
}
}
}
self.dataTask?.resume()
}
/**
Create a request with the provided URL.
:param: url The URL for the request.
*/
public func request(url: URL) -> URLRequest {
return URLRequest(url: url)
}
fileprivate func didInterceptRequest(_ request: URLRequest) -> Bool {
if appearedFrom == .external {
// intercept requests that match external return URL
if let url = request.url, shouldInterceptExternalURL(url: url) {
returnFromExternal(returnURL: url)
return true
}
}
return false
}
// MARK: Web Controller Navigation
/**
Push a new web view controller on the navigation stack using the existing
web view instance. Does not affect web view history. Uses animation.
*/
public func pushWebViewController() {
pushWebViewController(options: nil)
}
/**
Push a new web view controller on the navigation stack using the existing
web view instance. Does not affect web view history. Uses animation.
:param: hideBottomBar Hides the bottom bar of the view controller when true.
*/
public func pushWebViewController(options: WebViewControllerOptions?) {
disappearedBy = .webPush
let webViewController = newWebViewController(options: options)
webViewController.appearedFrom = .webPush
navigationController?.pushViewController(webViewController, animated: true)
}
/**
Pop a web view controller off of the navigation. Does not affect
web view history. Uses animation.
*/
public func popWebViewController() {
disappearedBy = .webPop
if let navController = self.navigationController, navController.viewControllers.count > 1 {
navController.popViewController(animated: true)
}
}
/**
Present a navigation controller containing a new web view controller as the
root view controller. The existing web view instance is reused.
*/
public func presentModalWebViewController(options: WebViewControllerOptions?) {
disappearedBy = .webModal
let webViewController = newWebViewController(options: options)
webViewController.appearedFrom = .webModal
let navigationController = UINavigationController(rootViewController: webViewController)
navigationController.modalPresentationStyle = .overCurrentContext
if let tabBarController = tabBarController {
tabBarController.present(navigationController, animated: true, completion: nil)
} else {
present(navigationController, animated: true, completion: nil)
}
}
/// Pops until there's only a single view controller left on the navigation stack.
public func popToRootWebViewController(animated: Bool) {
disappearedBy = .webPop
let _ = navigationController?.popToRootViewController(animated: animated)
}
/**
Return `true` to have the web view controller push a new web view controller
on the stack for a given navigation type of a request.
*/
public func pushesWebViewControllerForNavigationType(navigationType: UIWebView.NavigationType) -> Bool {
return false
}
public func newWebViewController(options: WebViewControllerOptions?) -> WebViewController {
let webViewController = type(of: self).init(webView: webView, context: bridgeContext)
webViewController.addBridgeAPIObject()
webViewController.hybridAPI?.navigationBar.title = options?.title
webViewController.hidesBottomBarWhenPushed = options?.tabBarHidden ?? false
webViewController.hybridAPI?.view.onAppearCallback = options?.onAppearCallback?.asValidValue
if let navigationBarButtons = options?.navigationBarButtons {
webViewController.hybridAPI?.navigationBar.configureButtons(navigationBarButtons, callback: options?.navigationBarButtonCallback)
}
return webViewController
}
// MARK: External Navigation
final var shouldDismissExternalURLModal: Bool {
return !webView.canGoBack
}
final func shouldInterceptExternalURL(url: URL) -> Bool {
if let requestedURLString = url.absoluteStringWithoutQuery,
let returnURLString = externalReturnURL?.absoluteStringWithoutQuery, (requestedURLString as NSString).range(of: returnURLString).location != NSNotFound {
return true
}
return false
}
// TODO: make internal after migrating to Swift 2 and @testable
@discardableResult final public func presentExternalURL(options: ExternalNavigationOptions) -> WebViewController {
let externalWebViewController = type(of: self).init()
externalWebViewController.externalPresentingWebViewController = self
externalWebViewController.addBridgeAPIObject()
externalWebViewController.load(url: options.url)
externalWebViewController.appearedFrom = .external
externalWebViewController.externalReturnURL = options.returnURL
externalWebViewController.title = options.title
let backText = NSLocalizedString("Back", tableName: nil, bundle: Bundle.main, value: "", comment: "")
externalWebViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: backText, style: .plain, target: externalWebViewController, action: #selector(WebViewController.externalBackButtonTapped))
let doneText = NSLocalizedString("Done", tableName: nil, bundle: Bundle.main, value: "", comment: "")
externalWebViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: doneText, style: .done, target: externalWebViewController, action: #selector(WebViewController.dismissExternalURL))
let navigationController = UINavigationController(rootViewController: externalWebViewController)
present(navigationController, animated: true, completion: nil)
return externalWebViewController
}
@objc final func externalBackButtonTapped() {
if shouldDismissExternalURLModal {
externalPresentingWebViewController?.showWebView()
dismissExternalURL()
}
webView.goBack()
}
final func returnFromExternal(returnURL url: URL) {
externalPresentingWebViewController?.load(url: url)
dismissExternalURL()
}
@objc final func dismissExternalURL() {
dismiss(animated: true, completion: nil)
}
// MARK: Error UI
private func createErrorLabel() -> UILabel? {
let height = CGFloat(50)
let y = view.bounds.midY - (height / 2) - 100
let label = UILabel(frame: CGRect(x: 0, y: y, width: view.bounds.width, height: height))
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.numberOfLines = 0
label.textAlignment = NSTextAlignment.center
label.backgroundColor = view.backgroundColor
label.font = UIFont.boldSystemFont(ofSize: 12)
return label
}
private func createReloadButton() -> UIButton? {
let button = UIButton(type: .custom)
let size = CGSize(width: 170, height: 38)
let x = view.bounds.midX - (size.width / 2)
var y = view.bounds.midY - (size.height / 2)
if let label = errorLabel {
y = label.frame.maxY + 20
}
button.setTitle(NSLocalizedString("Try again", comment: "Try again"), for: UIControl.State.normal)
button.frame = CGRect(x: x, y: y, width: size.width, height: size.height)
button.backgroundColor = UIColor.lightGray
button.titleLabel?.backgroundColor = UIColor.lightGray
button.titleLabel?.textColor = UIColor.white
return button
}
// MARK: Error Display Events
/// Override to completely customize error display. Must also override `removeErrorDisplay`
open func renderErrorDisplay(error: Error, message: String) {
let errorView = UIView(frame: view.bounds)
view.addSubview(errorView)
self.errorView = errorView
self.errorLabel = createErrorLabel()
self.reloadButton = createReloadButton()
if let errorLabel = errorLabel {
errorLabel.text = NSLocalizedString(message, comment: "Web View Load Error")
errorView.addSubview(errorLabel)
}
if let button = reloadButton {
button.addTarget(self, action: #selector(WebViewController.reloadButtonTapped), for: .touchUpInside)
errorView.addSubview(button)
}
}
/// Override to handle custom error display removal.
public func removeErrorDisplay() {
errorView?.removeFromSuperview()
errorView = nil
showWebView()
}
/// Override to customize the feature name that appears in the error display.
open func featureName(forError error: Error) -> String {
return "This feature"
}
/// Override to customize the error message text.
open func renderFeatureErrorDisplayWithError(error: Error, featureName: String) {
let message = "Sorry!\n \(featureName) isn't working right now."
webView.isHidden = true
renderErrorDisplay(error: error, message: message)
}
/// Removes the error display and attempts to reload the web view.
@objc open func reloadButtonTapped(sender: AnyObject) {
guard let url = url else { return }
load(url: url)
}
// MARK: Bridge API
@objc open func addBridgeAPIObject() {
if let bridgeObject = hybridAPI {
bridgeContext.setObject(bridgeObject, forKeyedSubscript: HybridAPI.exportName as NSString)
} else {
let platform = HybridAPI(parentViewController: self)
bridgeContext.setObject(platform, forKeyedSubscript: HybridAPI.exportName as NSString)
hybridAPI = platform
}
}
}
// MARK: - NSURLSessionDelegate
extension WebViewController: URLSessionDelegate {
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let host = challengeHost,
let serverTrust = challenge.protectionSpace.serverTrust, challenge.protectionSpace.host == host {
let credential = URLCredential(trust: serverTrust)
completionHandler(.useCredential, credential)
} else {
completionHandler(.performDefaultHandling, nil)
}
}
}
}
// MARK: - UIWebViewDelegate
extension WebViewController: UIWebViewDelegate {
final public func webViewDidStartLoad(_ webView: UIWebView) {
delegate?.webViewControllerDidStartLoad?(self)
}
public func webViewDidFinishLoad(_ webView: UIWebView) {
delegate?.webViewControllerDidFinishLoad?(self)
if self.errorView != nil {
self.removeErrorDisplay()
}
}
final public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
if pushesWebViewControllerForNavigationType(navigationType: navigationType) {
pushWebViewController()
}
if didInterceptRequest(request) {
return false
} else {
return delegate?.webViewController?(self, shouldStartLoadWithRequest: request, navigationType: navigationType) ?? true
}
}
final public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
if (error as NSError).code != NSURLErrorCancelled && showErrorDisplay {
renderFeatureErrorDisplayWithError(error: error, featureName: featureName(forError: error))
}
delegate?.webViewController?(self, didFailLoadWithError: error)
}
}
// MARK: - JavaScript Context
extension WebViewController: WebViewBridging {
/**
Update the bridge's JavaScript context by attempting to retrieve a context
from the web view.
*/
final public func updateBridgeContext() {
if let context = webView.javaScriptContext {
configureBridgeContext(context: context)
} else {
print("Failed to retrieve JavaScript context from web view.")
}
}
public func didCreateJavaScriptContext(context: JSContext) {
configureBridgeContext(context: context)
delegate?.webViewControllerDidCreateJavaScriptContext?(self, context: context)
configureContext(context: context)
if let hybridAPI = hybridAPI, let readyCallback = context.objectForKeyedSubscript("nativeBridgeReady") {
if !readyCallback.isUndefined {
readyCallback.call(withData: hybridAPI)
}
}
}
/**
Explictly set the bridge's JavaScript context.
*/
final public func configureBridgeContext(context: JSContext) {
bridgeContext = context
}
public func configureContext(context: JSContext) {
addBridgeAPIObject()
}
}
// MARK: - UIView Utils
extension UIView {
func captureImage() -> UIImage? {
guard let context = UIGraphicsGetCurrentContext() else { return nil }
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func removeDoubleTapGestures() {
for view in self.subviews {
view.removeDoubleTapGestures()
}
if let gestureRecognizers = gestureRecognizers {
for gesture in gestureRecognizers {
if let gesture = gesture as? UITapGestureRecognizer, gesture.numberOfTapsRequired == 2 {
removeGestureRecognizer(gesture)
}
}
}
}
}
// MARK: - UIImage utils
extension UIImage {
// saves image to temp directory and returns a GUID so you can fetch it later.
func saveImageToGUID() -> String? {
let guid = UUID().uuidString
DispatchQueue.global().async {
if let imageData = self.jpegData(compressionQuality: 1.0),
let filePath = UIImage.absoluteFilePath(guid: guid) {
FileManager.default.createFile(atPath: filePath, contents: imageData, attributes: nil)
}
}
return guid
}
class func loadImageFromGUID(guid: String) -> UIImage? {
guard let filePath = UIImage.absoluteFilePath(guid: guid) else { return nil }
return UIImage(contentsOfFile: filePath)
}
private class func absoluteFilePath(guid: String) -> String? {
return NSURL(string: NSTemporaryDirectory())?.appendingPathComponent(guid)!.absoluteString
}
}
// MARK: - JSContext Event
@objc(WebViewBridging)
public protocol WebViewBridging {
func didCreateJavaScriptContext(context: JSContext)
}
private var globalWebViews = NSHashTable<UIWebView>.weakObjects()
@objc(WebViewManager)
public class WebViewManager: NSObject {
// globalWebViews is a weak hash table. No need to remove items.
@objc static public func addBridgedWebView(webView: UIWebView?) {
if let webView = webView {
globalWebViews.add(webView)
}
}
}
public extension NSObject {
private struct AssociatedKeys {
static var uniqueIDKey = "nsobject_uniqueID"
}
@objc var uniqueWebViewID: String! {
if let currentValue = objc_getAssociatedObject(self, &AssociatedKeys.uniqueIDKey) as? String {
return currentValue
} else {
let newValue = UUID().uuidString
objc_setAssociatedObject(self, &AssociatedKeys.uniqueIDKey, newValue as NSString?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return newValue
}
}
@objc func webView(_ webView: AnyObject, didCreateJavaScriptContext context: JSContext, forFrame frame: AnyObject) {
let notifyWebviews = { () -> Void in
let allWebViews = globalWebViews.allObjects
for webView in allWebViews {
let cookie = "__thgWebviewCookie\(webView.hash)"
let js = "var \(cookie) = '\(cookie)'"
webView.stringByEvaluatingJavaScript(from: js)
let contextCookie = context.objectForKeyedSubscript(cookie).toString()
if contextCookie == cookie {
if let bridgingDelegate = webView.delegate as? WebViewBridging {
bridgingDelegate.didCreateJavaScriptContext(context: context)
}
}
}
}
let webFrameClass1: AnyClass! = NSClassFromString("WebFrame") // Most web-views
let webFrameClass2: AnyClass! = NSClassFromString("NSKVONotifying_WebFrame") // Objc webviews accessed via swift
if (type(of: frame) === webFrameClass1) || (type(of: frame) === webFrameClass2) {
if Thread.isMainThread {
notifyWebviews()
} else {
DispatchQueue.main.async(execute: notifyWebviews)
}
}
}
}
extension URL {
/// Get the absolute URL string value without the query string.
var absoluteStringWithoutQuery: String? {
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)
components?.query = nil
return components?.string
}
}
| 04c8b5c0967dc3e2c5a74e560241b117 | 36.997555 | 226 | 0.652468 | false | false | false | false |
loudnate/LoopKit | refs/heads/master | LoopKitUI/Views/CustomOverrideCollectionViewCell.swift | mit | 1 | //
// CustomOverrideCollectionViewCell.swift
// LoopKitUI
//
// Created by Michael Pangburn on 11/5/19.
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import UIKit
final class CustomOverrideCollectionViewCell: UICollectionViewCell, IdentifiableClass {
@IBOutlet weak var titleLabel: UILabel!
private lazy var overlayDimmerView: UIView = {
let view = UIView()
if #available(iOSApplicationExtension 13.0, *) {
view.backgroundColor = .systemBackground
} else {
view.backgroundColor = .white
}
view.alpha = 0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func awakeFromNib() {
super.awakeFromNib()
let selectedBackgroundView = UIView()
self.selectedBackgroundView = selectedBackgroundView
if #available(iOSApplicationExtension 13.0, iOS 13.0, *) {
selectedBackgroundView.backgroundColor = .tertiarySystemFill
backgroundColor = .secondarySystemGroupedBackground
layer.cornerCurve = .continuous
} else {
selectedBackgroundView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3)
backgroundColor = .white
}
layer.cornerRadius = 16
addSubview(overlayDimmerView)
NSLayoutConstraint.activate([
overlayDimmerView.leadingAnchor.constraint(equalTo: leadingAnchor),
overlayDimmerView.trailingAnchor.constraint(equalTo: trailingAnchor),
overlayDimmerView.topAnchor.constraint(equalTo: topAnchor),
overlayDimmerView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
override func prepareForReuse() {
removeOverlay(animated: false)
}
func applyOverlayToFade(animated: Bool) {
if animated {
UIView.animate(withDuration: 0.3, animations: {
self.overlayDimmerView.alpha = 0.5
})
} else {
self.overlayDimmerView.alpha = 0.5
}
}
func removeOverlay(animated: Bool) {
if animated {
UIView.animate(withDuration: 0.3, animations: {
self.overlayDimmerView.alpha = 0
})
} else {
self.overlayDimmerView.alpha = 0
}
}
}
| 484eba56bd969c7fad6f5ac8a75f6861 | 28.974359 | 94 | 0.634303 | false | false | false | false |
kzietek/SampleApp | refs/heads/master | KZSampleApp/Modules/RootNavigation/DemoFlowNavigation.swift | mit | 1 | //
// DemoFlowNavigation.swift
// KZSampleApp
//
// Created by Kamil Ziętek on 03.07.2017.
// Copyright © 2017 Kamil Ziętek. All rights reserved.
//
import UIKit
final class DemoFlowNavigation {
let navigationController: UINavigationController
init(with navigationController: UINavigationController) {
self.navigationController = navigationController
}
func startFlow() {
let factory = SelectionScreenFactory()
factory.onSelection = { [weak self] (result) in
self?.goToTable(with: result)
}
let selectionScreen = factory.createWithoutContext()
navigationController.setViewControllers([selectionScreen], animated: false)
}
func goToTable(with result:SelectionResult) -> () {
NSLog("Instantinate another view controller!")
let factory = SelectionDetailsScreenFactory()
let selectionDetailsVC = factory.create(for: result)
push(selectionDetailsVC)
}
fileprivate func push(_ viewController: UIViewController) {
navigationController.pushViewController(viewController, animated: true)
}
fileprivate func createRedScreen() -> (UIViewController) {
let emptyScreen = UIViewController()
emptyScreen.view = UIView()
emptyScreen.view.backgroundColor = UIColor.red
return emptyScreen
}
}
| 60668533239a0177e92a8a359f522dca | 30.409091 | 83 | 0.682344 | false | false | false | false |
sweetmans/SMInstagramPhotoPicker | refs/heads/master | Demo/Demo/ViewController.swift | mit | 1 | //
// ViewController.swift
// Demo
//
// Created by MacBook Pro on 2017/4/21.
// Copyright © 2017年 Sweetman, Inc. All rights reserved.
//
import UIKit
import SMInstagramPhotoPicker
import Photos
class ViewController: UIViewController, SMPhotoPickerViewControllerDelegate {
var picker: SMPhotoPickerViewController?
@IBOutlet var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
/*
First. It is importance to do this step.
Be sour your app have Authorization to assecc your photo library.
*/
PHPhotoLibrary.requestAuthorization { (status) in
if status == .authorized {
self.picker = SMPhotoPickerViewController()
self.picker?.delegate = self
}
}
}
//show picker. You need use present.
@IBAction func show(_ sender: UIButton) {
if picker != nil {
present(picker!, animated: true, completion: nil)
}
}
//No things to show here.
@IBAction func nothings(_ sender: UIButton) {
let alert = UIAlertController.init(title: "都说啥都没有啦,还点。。。", message: "Do not understan Chinaese? You need google translate.", preferredStyle: .alert)
let cancel = UIAlertAction.init(title: "我错了😯", style: .cancel, handler: { (action) in
})
alert.addAction(cancel)
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
func didCancelPickingPhoto() {
print("User cancel picking image")
}
func didFinishPickingPhoto(image: UIImage, meteData: [String : Any]) {
imageView.image = image
}
}
| 2a1e206a58afc1a4a5faada941c013b8 | 22.776316 | 156 | 0.588268 | false | false | false | false |
CharlinFeng/PhotoBrowser | refs/heads/master | PhotoBrowser/PhotoBrowser/Controller/PhotoBrowser+Indicator.swift | mit | 1 | //
// PhotoBrowser+Indicator.swift
// PhotoBrowser
//
// Created by 冯成林 on 15/8/13.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
extension PhotoBrowser{
/** pagecontrol准备 */
func pagecontrolPrepare(){
if !hideMsgForZoomAndDismissWithSingleTap {return}
view.addSubview(pagecontrol)
pagecontrol.make_bottomInsets_bottomHeight(left: 0, bottom: 0, right: 0, bottomHeight: 37)
pagecontrol.numberOfPages = photoModels.count
pagecontrol.isEnabled = false
}
/** pageControl页面变动 */
func pageControlPageChanged(_ page: Int){
if page<0 || page>=photoModels.count {return}
if showType == PhotoBrowser.ShowType.zoomAndDismissWithSingleTap && hideMsgForZoomAndDismissWithSingleTap{
pagecontrol.currentPage = page
}
}
}
| 3b74001cdf047421738b6c86727aa397 | 25.058824 | 114 | 0.638826 | false | false | false | false |
Johennes/firefox-ios | refs/heads/master | ReadingList/ReadingListClient.swift | mpl-2.0 | 1 | /* 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 Alamofire
enum ReadingListDeleteRecordResult {
case Success(ReadingListRecordResponse)
case PreconditionFailed(ReadingListResponse)
case NotFound(ReadingListResponse)
case Failure(ReadingListResponse)
case Error(NSError)
}
enum ReadingListGetRecordResult {
case Success(ReadingListRecordResponse)
case NotModified(ReadingListResponse) // TODO Should really call this NotModified for clarity
case NotFound(ReadingListResponse)
case Failure(ReadingListResponse)
case Error(NSError)
}
enum ReadingListGetAllRecordsResult {
case Success(ReadingListRecordsResponse)
case NotModified(ReadingListResponse) // TODO Should really call this NotModified for clarity
case Failure(ReadingListResponse)
case Error(NSError)
}
enum ReadingListPatchRecordResult {
}
enum ReadingListAddRecordResult {
case Success(ReadingListRecordResponse)
case Failure(ReadingListResponse)
case Conflict(ReadingListResponse)
case Error(NSError)
}
enum ReadingListBatchAddRecordsResult {
case Success(ReadingListBatchRecordResponse)
case Failure(ReadingListResponse)
case Error(NSError)
}
private let ReadingListClientUnknownError = NSError(domain: "org.mozilla.ios.Fennec.ReadingListClient", code: -1, userInfo: nil)
class ReadingListClient {
var serviceURL: NSURL
var authenticator: ReadingListAuthenticator
var articlesURL: NSURL!
var articlesBaseURL: NSURL!
var batchURL: NSURL!
func getRecordWithGuid(guid: String, ifModifiedSince: ReadingListTimestamp?, completion: (ReadingListGetRecordResult) -> Void) {
if let url = NSURL(string: guid, relativeToURL: articlesBaseURL) {
Alamofire.Manager.sharedInstance.request(createRequest("GET", url, ifModifiedSince: ifModifiedSince)).responseJSON(options: [], completionHandler: { response -> Void in
if let json = response.result.value, response = response.response {
switch response.statusCode {
case 200:
completion(.Success(ReadingListRecordResponse(response: response, json: json)!))
case 304:
completion(.NotModified(ReadingListResponse(response: response, json: json)!))
case 404:
completion(.NotFound(ReadingListResponse(response: response, json: json)!))
default:
completion(.Failure(ReadingListResponse(response: response, json: json)!))
}
} else {
completion(.Error(response.result.error ?? ReadingListClientUnknownError))
}
})
} else {
// TODO ???
}
}
func getRecordWithGuid(guid: String, completion: (ReadingListGetRecordResult) -> Void) {
getRecordWithGuid(guid, ifModifiedSince: nil, completion: completion)
}
func getAllRecordsWithFetchSpec(fetchSpec: ReadingListFetchSpec, ifModifiedSince: ReadingListTimestamp?, completion: (ReadingListGetAllRecordsResult) -> Void) {
if let url = fetchSpec.getURL(serviceURL: serviceURL, path: "/v1/articles") {
Alamofire.Manager.sharedInstance.request(createRequest("GET", url)).responseJSON(options: [], completionHandler: { response -> Void in
if let json = response.result.value, response = response.response {
switch response.statusCode {
case 200:
completion(.Success(ReadingListRecordsResponse(response: response, json: json)!))
case 304:
completion(.NotModified(ReadingListResponse(response: response, json: json)!))
default:
completion(.Failure(ReadingListResponse(response: response, json: json)!))
}
} else {
completion(.Error(response.result.error ?? ReadingListClientUnknownError))
}
})
} else {
// TODO ???
}
}
func getAllRecordsWithFetchSpec(fetchSpec: ReadingListFetchSpec, completion: (ReadingListGetAllRecordsResult) -> Void) {
getAllRecordsWithFetchSpec(fetchSpec, ifModifiedSince: nil, completion: completion)
}
func patchRecord(record: ReadingListClientRecord, completion: (ReadingListPatchRecordResult) -> Void) {
}
func addRecord(record: ReadingListClientRecord, completion: (ReadingListAddRecordResult) -> Void) {
Alamofire.Manager.sharedInstance.request(createRequest("POST", articlesURL, json: record.json)).responseJSON(options: [], completionHandler: { response in
if let json = response.result.value, response = response.response {
switch response.statusCode {
case 200, 201: // TODO Should we have different results for these? Do we care about 200 vs 201?
completion(.Success(ReadingListRecordResponse(response: response, json: json)!))
case 303:
completion(.Conflict(ReadingListResponse(response: response, json: json)!))
default:
completion(.Failure(ReadingListResponse(response: response, json: json)!))
}
} else {
completion(.Error(response.result.error ?? ReadingListClientUnknownError))
}
})
}
/// Build the JSON body for POST /v1/batch { defaults: {}, request: [ {body: {} } ] }
private func recordsToBatchJSON(records: [ReadingListClientRecord]) -> AnyObject {
return [
"defaults": ["method": "POST", "path": "/v1/articles", "headers": ["Content-Type": "application/json"]],
"requests": records.map { ["body": $0.json] }
]
}
func batchAddRecords(records: [ReadingListClientRecord], completion: (ReadingListBatchAddRecordsResult) -> Void) {
Alamofire.Manager.sharedInstance.request(createRequest("POST", batchURL, json: recordsToBatchJSON(records))).responseJSON(options: [], completionHandler: { response in
if let json = response.result.value, response = response.response {
switch response.statusCode {
case 200:
completion(.Success(ReadingListBatchRecordResponse(response: response, json: json)!))
default:
completion(.Failure(ReadingListResponse(response: response, json: json)!))
}
} else {
completion(.Error(response.result.error ?? ReadingListClientUnknownError))
}
})
}
func deleteRecordWithGuid(guid: String, ifUnmodifiedSince: ReadingListTimestamp?, completion: (ReadingListDeleteRecordResult) -> Void) {
if let url = NSURL(string: guid, relativeToURL: articlesBaseURL) {
Alamofire.Manager.sharedInstance.request(createRequest("DELETE", url, ifUnmodifiedSince: ifUnmodifiedSince)).responseJSON(options: [], completionHandler: { response in
if let json = response.result.value, let response = response.response {
switch response.statusCode {
case 200:
completion(.Success(ReadingListRecordResponse(response: response, json: json)!))
case 412:
completion(.PreconditionFailed(ReadingListResponse(response: response, json: json)!))
case 404:
completion(.NotFound(ReadingListResponse(response: response, json: json)!))
default:
completion(.Failure(ReadingListResponse(response: response, json: json)!))
}
} else {
completion(.Error(response.result.error ?? ReadingListClientUnknownError))
}
})
} else {
// TODO ???
}
}
func deleteRecordWithGuid(guid: String, completion: (ReadingListDeleteRecordResult) -> Void) {
deleteRecordWithGuid(guid, ifUnmodifiedSince: nil, completion: completion)
}
func createRequest(method: String, _ url: NSURL, ifUnmodifiedSince: ReadingListTimestamp? = nil, ifModifiedSince: ReadingListTimestamp? = nil, json: AnyObject? = nil) -> NSURLRequest {
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = method
if let ifUnmodifiedSince = ifUnmodifiedSince {
request.setValue(String(ifUnmodifiedSince), forHTTPHeaderField: "If-Unmodified-Since")
}
if let ifModifiedSince = ifModifiedSince {
request.setValue(String(ifModifiedSince), forHTTPHeaderField: "If-Modified-Since")
}
for (headerField, value) in authenticator.headers {
request.setValue(value, forHTTPHeaderField: headerField)
}
request.addValue("application/json", forHTTPHeaderField: "Accept")
if let json: AnyObject = json {
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
} catch _ {
request.HTTPBody = nil
} // TODO Handle errors here
}
return request
}
init(serviceURL: NSURL, authenticator: ReadingListAuthenticator) {
self.serviceURL = serviceURL
self.authenticator = authenticator
self.articlesURL = NSURL(string: "/v1/articles", relativeToURL: self.serviceURL)
self.articlesBaseURL = NSURL(string: "/v1/articles/", relativeToURL: self.serviceURL)
self.batchURL = NSURL(string: "/v1/batch", relativeToURL: self.serviceURL)
}
}
| dbbb5c2ab55ec66f15272bb4ad3e5bc3 | 46.914692 | 188 | 0.636795 | false | false | false | false |
AdamZikmund/strv | refs/heads/master | strv/strv/Classes/Handler/CitiesHandler.swift | mit | 1 | //
// CitiesHandler.swift
// strv
//
// Created by Adam Zikmund on 22.05.15.
// Copyright (c) 2015 Adam Zikmund. All rights reserved.
//
import UIKit
import Alamofire
class CitiesHandler: NSObject {
class func getCitiesForName(name : String, completionHandler : ([City]) -> Void){
let url = "http://api.geonames.org/searchJSON"
let parameters = ["q" : name, "maxRows" : 10, "username" : "funn3r"] as [String : AnyObject]
Alamofire.request(.GET, url, parameters: parameters, encoding: ParameterEncoding.URL)
.responseJSON(options: NSJSONReadingOptions.MutableContainers) { (_, _, json, error) -> Void in
if error == nil {
if let json = json as? [String : AnyObject], geonames = json["geonames"] as? [[String : AnyObject]] {
var cities = [City]()
for geoname in geonames {
if let cityName = geoname["name"] as? String, stateCode = geoname["countryCode"] as? String {
cities.append(City(stateCode: stateCode, name: cityName))
}
}
completionHandler(cities)
}
}
}
}
}
| 79ea1d770e393c1dd46c214699a51311 | 38.121212 | 121 | 0.529047 | false | false | false | false |
cconeil/Standard-Template-Protocols | refs/heads/master | STP/Moveable.swift | mit | 1 | //
// Moveable.swift
// Standard Template Protocols
//
// Created by Chris O'Neil on 9/20/15.
// Copyright (c) 2015 Because. All rights reserved.
//
import UIKit
public protocol Moveable {
func makeMoveable()
func didStartMoving()
func didFinishMoving(velocity:CGPoint)
func canMoveToX(x:CGFloat) -> Bool
func canMoveToY(y:CGFloat) -> Bool
func translateCenter(translation:CGPoint, velocity:CGPoint, startPoint:CGPoint, currentPoint:CGPoint) -> CGPoint
func animateToMovedTransform(transform:CGAffineTransform)
}
public extension Moveable where Self:UIView {
func makeMoveable() {
var startPoint:CGPoint = CGPointZero
var currentPoint:CGPoint = CGPointZero
let gestureRecognizer = UIPanGestureRecognizer { [unowned self] (recognizer) -> Void in
let pan = recognizer as! UIPanGestureRecognizer
let velocity = pan.velocityInView(self.superview)
let translation = pan.translationInView(self.superview)
switch recognizer.state {
case .Began:
startPoint = self.center
currentPoint = self.center
self.didStartMoving()
case .Ended, .Cancelled, .Failed:
self.didFinishMoving(velocity)
default:
let point = self.translateCenter(translation, velocity:velocity, startPoint: startPoint, currentPoint: currentPoint)
self.animateToMovedTransform(self.transformFromCenter(point, currentPoint: currentPoint))
currentPoint = point
}
}
self.addGestureRecognizer(gestureRecognizer)
}
func animateToMovedTransform(transform:CGAffineTransform) {
UIView.animateWithDuration(0.01) { () -> Void in
self.transform = transform;
}
}
func translateCenter(translation:CGPoint, velocity:CGPoint, startPoint:CGPoint, currentPoint:CGPoint) -> CGPoint {
var point = startPoint
if (self.canMoveToX(point.x + translation.x)) {
point.x += translation.x
} else {
point.x = translation.x > 0.0 ? maximumPoint().x : minimumPoint().x
}
if (self.canMoveToY(point.y + translation.y)) {
point.y += translation.y
} else {
point.y = translation.y > 0.0 ? maximumPoint().y : minimumPoint().y
}
return point
}
func transformFromCenter(center:CGPoint, currentPoint:CGPoint) -> CGAffineTransform {
return CGAffineTransformTranslate(self.transform, center.x - currentPoint.x , center.y - currentPoint.y)
}
func didStartMoving() {
return
}
func didFinishMoving(velocity:CGPoint) {
return
}
func canMoveToX(x:CGFloat) -> Bool {
if let superviewFrame = self.superview?.frame {
let diameter = self.frame.size.width / 2.0
if x + diameter > superviewFrame.size.width {
return false
}
if x - diameter < 0.0 {
return false
}
}
return true
}
func canMoveToY(y:CGFloat) -> Bool {
if let superviewFrame = self.superview?.frame {
let diameter = self.frame.size.height / 2.0
if y + diameter > superviewFrame.size.height {
return false
}
if y - diameter < 0.0 {
return false
}
}
return true
}
func maximumPoint() -> CGPoint {
if let superviewFrame = self.superview?.frame {
let x = superviewFrame.size.width - self.frame.size.width / 2.0
let y = superviewFrame.size.height - self.frame.size.height / 2.0
return CGPointMake(x, y)
} else {
return CGPoint.zero
}
}
func minimumPoint() -> CGPoint {
let x = self.frame.size.width / 2.0
let y = self.frame.size.height / 2.0
return CGPointMake(x, y)
}
}
| da7b88003c0fcdef9b591ac685fbb97f | 31.024 | 132 | 0.598051 | false | false | false | false |
Legoless/ViewModelable | refs/heads/master | Demo/Demo/CarViewModel.swift | mit | 1 | //
// CarViewModel.swift
// Demo
//
// Created by Dal Rupnik on 09/07/16.
// Copyright © 2016 Unified Sense. All rights reserved.
//
import Foundation
import ViewModelable
class CarViewModel : ViewModel {
//
// MARK: Input of the view model, must be
//
var car : Car?
//
// MARK: Output of view model, must be populated at all times, so screen can be
//
private(set) var loading : Bool = false
private(set) var carDescription = ""
private(set) var engineDescription = ""
override func startSetup() {
super.startSetup()
//
// View model should handle data, here we just pull a car if it was not set.
//
loading = true
}
override func startLoading() {
loading = true
carDescription = "Loading..."
engineDescription = ""
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0) {
self.loading = false
if self.car == nil {
self.car = Car.lamborghiniAvendator()
}
//
// Call to finish loading, to ensure state transition is correct.
//
self.finishLoading()
}
}
override func updateOutput() {
//
// This method is called multiple times during state transitions and
// should just set output variables in a synchronous way.
//
if let car = car {
carDescription = "\(car.make) \(car.model)"
engineDescription = "\(car.engine.displacement) cc, \(car.engine.brakeHorsepower) BHP"
}
else if loading == true {
carDescription = "Loading..."
engineDescription = ""
}
else {
carDescription = "Unknown"
engineDescription = ""
}
}
}
| 54674a09b88b2ecc6e992171cd492093 | 24.12987 | 98 | 0.525581 | false | false | false | false |
CatchChat/Yep | refs/heads/master | Yep/Views/MessageToolbar/VoiceRecordButton.swift | mit | 1 | //
// VoiceRecordButton.swift
// Yep
//
// Created by NIX on 15/4/2.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
final class VoiceRecordButton: UIView {
var touchesBegin: (() -> Void)?
var touchesEnded: ((needAbort: Bool) -> Void)?
var touchesCancelled: (() -> Void)?
var checkAbort: ((topOffset: CGFloat) -> Bool)?
var abort = false
var titleLabel: UILabel?
var leftVoiceImageView: UIImageView?
var rightVoiceImageView: UIImageView?
enum State {
case Default
case Touched
}
var state: State = .Default {
willSet {
let color: UIColor
switch newValue {
case .Default:
color = UIColor.yepMessageToolbarSubviewBorderColor()
case .Touched:
color = UIColor.yepTintColor()
}
layer.borderColor = color.CGColor
leftVoiceImageView?.tintColor = color
rightVoiceImageView?.tintColor = color
switch newValue {
case .Default:
titleLabel?.textColor = tintColor
case .Touched:
titleLabel?.textColor = UIColor.yepTintColor()
}
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
abort = false
touchesBegin?()
titleLabel?.text = NSLocalizedString("Release to Send", comment: "")
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
touchesEnded?(needAbort: abort)
titleLabel?.text = NSLocalizedString("Hold for Voice", comment: "")
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
touchesCancelled?()
titleLabel?.text = NSLocalizedString("Hold for Voice", comment: "")
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesMoved(touches, withEvent: event)
if let touch = touches.first {
let location = touch.locationInView(touch.view)
if location.y < 0 {
abort = checkAbort?(topOffset: abs(location.y)) ?? false
}
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
makeUI()
}
private func makeUI() {
let titleLabel = UILabel()
titleLabel.font = UIFont.systemFontOfSize(15.0)
titleLabel.text = NSLocalizedString("Hold for Voice", comment: "")
titleLabel.textAlignment = .Center
titleLabel.textColor = self.tintColor
self.titleLabel = titleLabel
self.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
let leftVoiceImageView = UIImageView(image: UIImage.yep_iconVoiceLeft)
leftVoiceImageView.contentMode = .Center
leftVoiceImageView.tintColor = self.tintColor
self.leftVoiceImageView = leftVoiceImageView
self.addSubview(leftVoiceImageView)
leftVoiceImageView.translatesAutoresizingMaskIntoConstraints = false
let rightVoiceImageView = UIImageView(image: UIImage.yep_iconVoiceRight)
rightVoiceImageView.contentMode = .Center
rightVoiceImageView.tintColor = self.tintColor
self.rightVoiceImageView = rightVoiceImageView
self.addSubview(rightVoiceImageView)
rightVoiceImageView.translatesAutoresizingMaskIntoConstraints = false
let viewsDictionary: [String: AnyObject] = [
"leftVoiceImageView": leftVoiceImageView,
"titleLabel": titleLabel,
"rightVoiceImageView": rightVoiceImageView,
]
let leftVoiceImageViewConstraintCenterY = NSLayoutConstraint(item: leftVoiceImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[leftVoiceImageView(20)][titleLabel][rightVoiceImageView(==leftVoiceImageView)]-10-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints([leftVoiceImageViewConstraintCenterY])
NSLayoutConstraint.activateConstraints(constraintsH)
}
}
| 8a9d42e3ec76dfbab23f19c1849cad55 | 31.167832 | 254 | 0.652391 | false | false | false | false |
brentsimmons/Frontier | refs/heads/master | BeforeTheRename/FrontierVerbs/FrontierVerbs/VerbTables/KBVerbs.swift | gpl-2.0 | 1 | //
// KBVerbs.swift
// FrontierVerbs
//
// Created by Brent Simmons on 4/15/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
struct KBVerbs: VerbTable {
private enum Verb: String {
case optionKey = "optionkey"
case cmdKey = "cmdkey"
case shiftKey = "shiftkey"
case controlKey = "controlkey"
}
static func evaluate(_ lowerVerbName: String, _ params: VerbParams, _ verbAppDelegate: VerbAppDelegate) throws -> Value {
guard let verb = Verb(rawValue: lowerVerbName) else {
throw LangError(.verbNotFound)
}
do {
switch verb {
case .optionKey:
return try isOptionKeyDown(params)
case .cmdKey:
return try isCmdKeyDown(params)
case .shiftKey:
return try isShiftKeyDown(params)
case .controlKey:
return try isControlKeyDown(params)
}
}
catch { throw error }
}
}
private extension KBVerbs {
static func isOptionKeyDown(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func isCmdKeyDown(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func isShiftKeyDown(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func isControlKeyDown(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
}
| 96974591ad364fd9fc981915d04feea2 | 19.893939 | 122 | 0.699057 | false | false | false | false |
ShiWeiCN/JESAlertView | refs/heads/master | Demo/Demo/JESAlertView/Maker/AlertMakerAlertPromptable.swift | mit | 2 | //
// AlertMakerAlertPromptable.swift
// Demo
//
// Created by Jerry on 17/10/2016.
// Copyright © 2016 jerryshi. All rights reserved.
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
#if os(iOS)
import UIKit
#endif
public class AlertMakerAlertPromptable: AlertMakerEditable {
internal func prompt(of prompt: AlertPrompt, content: String, file: String, line: UInt) -> AlertMakerAlertPromptable {
self.description.prompt = prompt
if prompt.isTitlePrompt() {
self.description.title = content
} else {
self.description.message = content
}
return self
}
@discardableResult
public func title(_ title: String, _ file: String = #file, _ line: UInt = #line) -> AlertMakerAlertPromptable {
return self.prompt(of: .title, content: title, file: file, line: line)
}
@discardableResult
public func message(_ message: String, _ file: String = #file, _ line: UInt = #line) -> AlertMakerAlertPromptable {
return self.prompt(of: .message, content: message, file: file, line: line)
}
}
| 1bdbdd65470fcc2f768aa7a7816a7513 | 30.594595 | 122 | 0.650128 | false | false | false | false |
CosmicMind/MaterialKit | refs/heads/master | Sources/iOS/NavigationBar.swift | bsd-3-clause | 1 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* 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.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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 UIKit
open class NavigationBar: UINavigationBar {
/// Will layout the view.
open var willLayout: Bool {
return 0 < bounds.width && 0 < bounds.height && nil != superview
}
/// Detail UILabel when in landscape for iOS 11.
fileprivate var toolbarToText: [Toolbar: String?]?
open override var intrinsicContentSize: CGSize {
return CGSize(width: bounds.width, height: bounds.height)
}
/// A preset wrapper around contentEdgeInsets.
open var contentEdgeInsetsPreset = EdgeInsetsPreset.square1 {
didSet {
contentEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset)
}
}
/// A reference to EdgeInsets.
@IBInspectable
open var contentEdgeInsets = EdgeInsetsPresetToValue(preset: .square1) {
didSet {
layoutSubviews()
}
}
/// A preset wrapper around interimSpace.
open var interimSpacePreset = InterimSpacePreset.interimSpace3 {
didSet {
interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset)
}
}
/// A wrapper around grid.interimSpace.
@IBInspectable
open var interimSpace = InterimSpacePresetToValue(preset: .interimSpace3) {
didSet {
layoutSubviews()
}
}
/**
The back button image writes to the backIndicatorImage property and
backIndicatorTransitionMaskImage property.
*/
@IBInspectable
open var backButtonImage: UIImage? {
get {
return backIndicatorImage
}
set(value) {
let image: UIImage? = value
backIndicatorImage = image
backIndicatorTransitionMaskImage = image
}
}
/// A property that accesses the backing layer's background
@IBInspectable
open override var backgroundColor: UIColor? {
get {
return barTintColor
}
set(value) {
barTintColor = value
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
return intrinsicContentSize
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutShape()
layoutShadowPath()
//iOS 11 added left/right layout margin in subviews of UINavigationBar
//since we do not want to unsafely access private view directly
//iterate subviews to set `layoutMargin` to zero
for v in subviews {
v.layoutMargins = .zero
}
if let v = topItem {
layoutNavigationItem(item: v)
}
if let v = backItem {
layoutNavigationItem(item: v)
}
layoutDivider()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
barStyle = .black
isTranslucent = false
depthPreset = .none
contentScaleFactor = Screen.scale
backButtonImage = Icon.cm.arrowBack
if #available(iOS 11, *) {
toolbarToText = [:]
}
let image = UIImage()
shadowImage = image
setBackgroundImage(image, for: .default)
backgroundColor = .white
}
}
internal extension NavigationBar {
/**
Lays out the UINavigationItem.
- Parameter item: A UINavigationItem to layout.
*/
func layoutNavigationItem(item: UINavigationItem) {
guard willLayout else {
return
}
let toolbar = item.toolbar
toolbar.backgroundColor = .clear
toolbar.interimSpace = interimSpace
toolbar.contentEdgeInsets = contentEdgeInsets
if #available(iOS 11, *) {
if Application.shouldStatusBarBeHidden {
toolbar.contentEdgeInsetsPreset = .none
if nil != toolbar.detailLabel.text {
toolbarToText?[toolbar] = toolbar.detailLabel.text
toolbar.detailLabel.text = nil
}
} else if nil != toolbarToText?[toolbar] {
toolbar.detailLabel.text = toolbarToText?[toolbar] ?? nil
toolbarToText?[toolbar] = nil
}
}
item.titleView = toolbar
item.titleView!.frame = bounds
}
}
| 8a66d79065089e0424f90d82f09d70fc | 28.961353 | 88 | 0.695905 | false | false | false | false |
brentdax/swift | refs/heads/master | stdlib/public/core/CollectionAlgorithms.swift | apache-2.0 | 1 | //===--- CollectionAlgorithms.swift.gyb -----------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// last
//===----------------------------------------------------------------------===//
extension BidirectionalCollection {
/// The last element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let lastNumber = numbers.last {
/// print(lastNumber)
/// }
/// // Prints "50"
///
/// - Complexity: O(1)
@inlinable
public var last: Element? {
return isEmpty ? nil : self[index(before: endIndex)]
}
}
//===----------------------------------------------------------------------===//
// firstIndex(of:)/firstIndex(where:)
//===----------------------------------------------------------------------===//
extension Collection where Element : Equatable {
/// Returns the first index where the specified value appears in the
/// collection.
///
/// After using `firstIndex(of:)` to find the position of a particular element
/// in a collection, you can use it to access the element by subscripting.
/// This example shows how you can modify one of the names in an array of
/// students.
///
/// var students = ["Ben", "Ivy", "Jordell", "Maxime"]
/// if let i = students.firstIndex(of: "Maxime") {
/// students[i] = "Max"
/// }
/// print(students)
/// // Prints "["Ben", "Ivy", "Jordell", "Max"]"
///
/// - Parameter element: An element to search for in the collection.
/// - Returns: The first index where `element` is found. If `element` is not
/// found in the collection, returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func firstIndex(of element: Element) -> Index? {
if let result = _customIndexOfEquatableElement(element) {
return result
}
var i = self.startIndex
while i != self.endIndex {
if self[i] == element {
return i
}
self.formIndex(after: &i)
}
return nil
}
}
extension Collection {
/// Returns the first index in which an element of the collection satisfies
/// the given predicate.
///
/// You can use the predicate to find an element of a type that doesn't
/// conform to the `Equatable` protocol or to find an element that matches
/// particular criteria. Here's an example that finds a student name that
/// begins with the letter "A":
///
/// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// if let i = students.firstIndex(where: { $0.hasPrefix("A") }) {
/// print("\(students[i]) starts with 'A'!")
/// }
/// // Prints "Abena starts with 'A'!"
///
/// - Parameter predicate: A closure that takes an element as its argument
/// and returns a Boolean value that indicates whether the passed element
/// represents a match.
/// - Returns: The index of the first element for which `predicate` returns
/// `true`. If no elements in the collection satisfy the given predicate,
/// returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func firstIndex(
where predicate: (Element) throws -> Bool
) rethrows -> Index? {
var i = self.startIndex
while i != self.endIndex {
if try predicate(self[i]) {
return i
}
self.formIndex(after: &i)
}
return nil
}
}
//===----------------------------------------------------------------------===//
// lastIndex(of:)/lastIndex(where:)
//===----------------------------------------------------------------------===//
extension BidirectionalCollection {
/// Returns the last element of the sequence that satisfies the given
/// predicate.
///
/// This example uses the `last(where:)` method to find the last
/// negative number in an array of integers:
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// if let lastNegative = numbers.last(where: { $0 < 0 }) {
/// print("The last negative number is \(lastNegative).")
/// }
/// // Prints "The last negative number is -6."
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element is a match.
/// - Returns: The last element of the sequence that satisfies `predicate`,
/// or `nil` if there is no element that satisfies `predicate`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func last(
where predicate: (Element) throws -> Bool
) rethrows -> Element? {
return try lastIndex(where: predicate).map { self[$0] }
}
/// Returns the index of the last element in the collection that matches the
/// given predicate.
///
/// You can use the predicate to find an element of a type that doesn't
/// conform to the `Equatable` protocol or to find an element that matches
/// particular criteria. This example finds the index of the last name that
/// begins with the letter *A:*
///
/// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// if let i = students.lastIndex(where: { $0.hasPrefix("A") }) {
/// print("\(students[i]) starts with 'A'!")
/// }
/// // Prints "Akosua starts with 'A'!"
///
/// - Parameter predicate: A closure that takes an element as its argument
/// and returns a Boolean value that indicates whether the passed element
/// represents a match.
/// - Returns: The index of the last element in the collection that matches
/// `predicate`, or `nil` if no elements match.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func lastIndex(
where predicate: (Element) throws -> Bool
) rethrows -> Index? {
var i = endIndex
while i != startIndex {
formIndex(before: &i)
if try predicate(self[i]) {
return i
}
}
return nil
}
}
extension BidirectionalCollection where Element : Equatable {
/// Returns the last index where the specified value appears in the
/// collection.
///
/// After using `lastIndex(of:)` to find the position of the last instance of
/// a particular element in a collection, you can use it to access the
/// element by subscripting. This example shows how you can modify one of
/// the names in an array of students.
///
/// var students = ["Ben", "Ivy", "Jordell", "Ben", "Maxime"]
/// if let i = students.lastIndex(of: "Ben") {
/// students[i] = "Benjamin"
/// }
/// print(students)
/// // Prints "["Ben", "Ivy", "Jordell", "Benjamin", "Max"]"
///
/// - Parameter element: An element to search for in the collection.
/// - Returns: The last index where `element` is found. If `element` is not
/// found in the collection, this method returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func lastIndex(of element: Element) -> Index? {
if let result = _customLastIndexOfEquatableElement(element) {
return result
}
return lastIndex(where: { $0 == element })
}
}
//===----------------------------------------------------------------------===//
// partition(by:)
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Reorders the elements of the collection such that all the elements
/// that match the given predicate are after all the elements that don't
/// match.
///
/// After partitioning a collection, there is a pivot index `p` where
/// no element before `p` satisfies the `belongsInSecondPartition`
/// predicate and every element at or after `p` satisfies
/// `belongsInSecondPartition`.
///
/// In the following example, an array of numbers is partitioned by a
/// predicate that matches elements greater than 30.
///
/// var numbers = [30, 40, 20, 30, 30, 60, 10]
/// let p = numbers.partition(by: { $0 > 30 })
/// // p == 5
/// // numbers == [30, 10, 20, 30, 30, 60, 40]
///
/// The `numbers` array is now arranged in two partitions. The first
/// partition, `numbers[..<p]`, is made up of the elements that
/// are not greater than 30. The second partition, `numbers[p...]`,
/// is made up of the elements that *are* greater than 30.
///
/// let first = numbers[..<p]
/// // first == [30, 10, 20, 30, 30]
/// let second = numbers[p...]
/// // second == [60, 40]
///
/// - Parameter belongsInSecondPartition: A predicate used to partition
/// the collection. All elements satisfying this predicate are ordered
/// after all elements not satisfying it.
/// - Returns: The index of the first element in the reordered collection
/// that matches `belongsInSecondPartition`. If no elements in the
/// collection match `belongsInSecondPartition`, the returned index is
/// equal to the collection's `endIndex`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func partition(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
return try _halfStablePartition(isSuffixElement: belongsInSecondPartition)
}
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, returning the start position of the resulting suffix.
///
/// - Complexity: O(*n*) where n is the length of the collection.
@inlinable
internal mutating func _halfStablePartition(
isSuffixElement: (Element) throws -> Bool
) rethrows -> Index {
guard var i = try firstIndex(where: isSuffixElement)
else { return endIndex }
var j = index(after: i)
while j != endIndex {
if try !isSuffixElement(self[j]) { swapAt(i, j); formIndex(after: &i) }
formIndex(after: &j)
}
return i
}
}
extension MutableCollection where Self : BidirectionalCollection {
/// Reorders the elements of the collection such that all the elements
/// that match the given predicate are after all the elements that don't
/// match.
///
/// After partitioning a collection, there is a pivot index `p` where
/// no element before `p` satisfies the `belongsInSecondPartition`
/// predicate and every element at or after `p` satisfies
/// `belongsInSecondPartition`.
///
/// In the following example, an array of numbers is partitioned by a
/// predicate that matches elements greater than 30.
///
/// var numbers = [30, 40, 20, 30, 30, 60, 10]
/// let p = numbers.partition(by: { $0 > 30 })
/// // p == 5
/// // numbers == [30, 10, 20, 30, 30, 60, 40]
///
/// The `numbers` array is now arranged in two partitions. The first
/// partition, `numbers[..<p]`, is made up of the elements that
/// are not greater than 30. The second partition, `numbers[p...]`,
/// is made up of the elements that *are* greater than 30.
///
/// let first = numbers[..<p]
/// // first == [30, 10, 20, 30, 30]
/// let second = numbers[p...]
/// // second == [60, 40]
///
/// - Parameter belongsInSecondPartition: A predicate used to partition
/// the collection. All elements satisfying this predicate are ordered
/// after all elements not satisfying it.
/// - Returns: The index of the first element in the reordered collection
/// that matches `belongsInSecondPartition`. If no elements in the
/// collection match `belongsInSecondPartition`, the returned index is
/// equal to the collection's `endIndex`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func partition(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
let maybeOffset = try _withUnsafeMutableBufferPointerIfSupported {
(bufferPointer) -> Int in
let unsafeBufferPivot = try bufferPointer.partition(
by: belongsInSecondPartition)
return unsafeBufferPivot - bufferPointer.startIndex
}
if let offset = maybeOffset {
return index(startIndex, offsetBy: numericCast(offset))
}
var lo = startIndex
var hi = endIndex
// 'Loop' invariants (at start of Loop, all are true):
// * lo < hi
// * predicate(self[i]) == false, for i in startIndex ..< lo
// * predicate(self[i]) == true, for i in hi ..< endIndex
Loop: while true {
FindLo: repeat {
while lo < hi {
if try belongsInSecondPartition(self[lo]) { break FindLo }
formIndex(after: &lo)
}
break Loop
} while false
FindHi: repeat {
formIndex(before: &hi)
while lo < hi {
if try !belongsInSecondPartition(self[hi]) { break FindHi }
formIndex(before: &hi)
}
break Loop
} while false
swapAt(lo, hi)
formIndex(after: &lo)
}
return lo
}
}
//===----------------------------------------------------------------------===//
// shuffled()/shuffle()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the elements of the sequence, shuffled using the given generator
/// as a source for randomness.
///
/// You use this method to randomize the elements of a sequence when you are
/// using a custom random number generator. For example, you can shuffle the
/// numbers between `0` and `9` by calling the `shuffled(using:)` method on
/// that range:
///
/// let numbers = 0...9
/// let shuffledNumbers = numbers.shuffled(using: &myGenerator)
/// // shuffledNumbers == [8, 9, 4, 3, 2, 6, 7, 0, 5, 1]
///
/// - Parameter generator: The random number generator to use when shuffling
/// the sequence.
/// - Returns: An array of this sequence's elements in a shuffled order.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
/// - Note: The algorithm used to shuffle a sequence may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same shuffled order each time you run your program, that sequence may
/// change when your program is compiled using a different version of
/// Swift.
@inlinable
public func shuffled<T: RandomNumberGenerator>(
using generator: inout T
) -> [Element] {
var result = ContiguousArray(self)
result.shuffle(using: &generator)
return Array(result)
}
/// Returns the elements of the sequence, shuffled.
///
/// For example, you can shuffle the numbers between `0` and `9` by calling
/// the `shuffled()` method on that range:
///
/// let numbers = 0...9
/// let shuffledNumbers = numbers.shuffled()
/// // shuffledNumbers == [1, 7, 6, 2, 8, 9, 4, 3, 5, 0]
///
/// This method is equivalent to calling `shuffled(using:)`, passing in the
/// system's default random generator.
///
/// - Returns: A shuffled array of this sequence's elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func shuffled() -> [Element] {
var g = SystemRandomNumberGenerator()
return shuffled(using: &g)
}
}
extension MutableCollection where Self : RandomAccessCollection {
/// Shuffles the collection in place, using the given generator as a source
/// for randomness.
///
/// You use this method to randomize the elements of a collection when you
/// are using a custom random number generator. For example, you can use the
/// `shuffle(using:)` method to randomly reorder the elements of an array.
///
/// var names = ["Alejandro", "Camila", "Diego", "Luciana", "Luis", "Sofía"]
/// names.shuffle(using: &myGenerator)
/// // names == ["Sofía", "Alejandro", "Camila", "Luis", "Diego", "Luciana"]
///
/// - Parameter generator: The random number generator to use when shuffling
/// the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
/// - Note: The algorithm used to shuffle a collection may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same shuffled order each time you run your program, that sequence may
/// change when your program is compiled using a different version of
/// Swift.
@inlinable
public mutating func shuffle<T: RandomNumberGenerator>(
using generator: inout T
) {
let count = self.count
guard count > 1 else { return }
var amount = count
var currentIndex = startIndex
while amount > 1 {
let random = generator.next(upperBound: UInt(amount))
amount -= 1
swapAt(
currentIndex,
index(currentIndex, offsetBy: numericCast(random))
)
formIndex(after: ¤tIndex)
}
}
/// Shuffles the collection in place.
///
/// Use the `shuffle()` method to randomly reorder the elements of an array.
///
/// var names = ["Alejandro", "Camila", "Diego", "Luciana", "Luis", "Sofía"]
/// names.shuffle(using: myGenerator)
/// // names == ["Luis", "Camila", "Luciana", "Sofía", "Alejandro", "Diego"]
///
/// This method is equivalent to calling `shuffle(using:)`, passing in the
/// system's default random generator.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func shuffle() {
var g = SystemRandomNumberGenerator()
shuffle(using: &g)
}
}
| 53f3fd3ae8dbabbdc6fec72fed8adf92 | 36.76875 | 82 | 0.60053 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | refs/heads/master | ch24-DeepObjc/Runtime/Runtime/RunMyMsgSend.swift | mit | 1 | //
// RunMyMsgSend.swift
// Runtime
//
// Created by wj on 15/12/3.
// Copyright © 2015年 wj. All rights reserved.
//
import Foundation
typealias MyvoidIMP = @convention(c)(NSObject,Selector)->()
func myMsgSend(_ receiver:NSObject,name:String){
let selector = sel_registerName(name)
let methodIMP = class_getMethodImplementation(receiver.classForCoder, selector)
let callBack = unsafeBitCast(methodIMP, to: MyvoidIMP.self)
return callBack(receiver,Selector( name))
}
func RunMyMsgSend(){
// let cla = objc_getClass("NSObject") as! AnyClass
let object = NSObject()
myMsgSend(object, name: "init")
let description = object.description
let cstr = description.utf8
print(cstr)
}
| 30edf9e6ce0050165a31afabb0b06c1b | 22.935484 | 83 | 0.687332 | false | false | false | false |
yangalex/WeMeet | refs/heads/master | WeMeet/View Controllers/ByUsernameViewController.swift | mit | 1 | //
// ByUsernameViewController.swift
// WeMeet
//
// Created by Alexandre Yang on 8/5/15.
// Copyright (c) 2015 Alex Yang. All rights reserved.
//
import UIKit
class ByUsernameViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
var currentGroup: Group!
override func viewDidLoad() {
super.viewDidLoad()
setupUsernameTextField()
self.navigationController?.navigationBar.topItem?.backBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
}
func setupUsernameTextField() {
let borderColor = UIColor(red: 210/255, green: 210/255, blue: 210/255, alpha: 1.0)
var bottomBorder = CALayer()
bottomBorder.frame = CGRectMake(0, usernameTextField.frame.height-1, usernameTextField.frame.width, 1.0)
bottomBorder.backgroundColor = borderColor.CGColor
usernameTextField.layer.addSublayer(bottomBorder)
var topBorder = CALayer()
topBorder.frame = CGRectMake(0, 0, usernameTextField.frame.width, 1.0)
topBorder.backgroundColor = borderColor.CGColor
usernameTextField.layer.addSublayer(topBorder)
// set a left margin (can also be used for images later on
let leftView = UIView(frame: CGRectMake(0, 0, 10, usernameTextField.frame.height))
leftView.backgroundColor = usernameTextField.backgroundColor
usernameTextField.leftView = leftView
usernameTextField.leftViewMode = UITextFieldViewMode.Always
}
@IBAction func addPressed(sender: AnyObject) {
var usersQuery = PFUser.query()!
usersQuery.whereKey("username", equalTo: usernameTextField.text)
usersQuery.findObjectsInBackgroundWithBlock { results, error in
if let results = results as? [PFUser] {
// if user was not found
if results.count == 0 {
let errorController = UIAlertController(title: "Invalid Username", message: "This user does not exist", preferredStyle: .Alert)
errorController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(errorController, animated: true, completion: nil)
} else {
var userAlreadyInGroup: Bool = false
for user in self.currentGroup!.users {
if user.username == results[0].username {
userAlreadyInGroup = true
}
}
if userAlreadyInGroup {
let errorController = UIAlertController(title: "Inavlid User", message: "User is already in this group", preferredStyle: .Alert)
errorController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(errorController, animated: true, completion: nil)
} else {
self.currentGroup?.users.append(results[0])
self.currentGroup?.saveInBackground()
self.navigationController?.popViewControllerAnimated(true)
}
}
}
}
}
@IBAction func cancelPressed(sender: AnyObject) {
navigationController?.popViewControllerAnimated(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.
}
*/
}
| 1321de968a8d2beffa0b71094224c1e1 | 41.72043 | 169 | 0.6222 | false | false | false | false |
TimurBK/Swift500pxMobile | refs/heads/develop | Swift500pxMobile/Code/Architecture/Services/Network/Networking.swift | mit | 1 | //
// Networking.swift
// Swift500pxMobile
//
// Created by Timur Kuchkarov on 05.03.17.
// Copyright © 2017 Timur Kuchkarov. All rights reserved.
//
import Foundation
import Moya
import ReactiveCocoa
import ReactiveSwift
typealias ListUpdate<T> = ([T], String?) -> ()
class Networking {
let provider: MoyaProvider<PXAPI>
init() {
self.provider = MoyaProvider<PXAPI>()
}
func fetchPhotos(page:Int64, category: String, completion:@escaping ListUpdate<PhotoModel>) {
self.provider.request(.photos(page: page, category: category)) { result in
switch result {
case let .success(moyaResponse):
let data = moyaResponse.data
let statusCode = moyaResponse.statusCode
if statusCode > 399 {
completion([], "Error detected")
return
}
let parsed: [PhotoModel]? = try? unbox(data: data, atKeyPath: "photos", allowInvalidElements: false)
if parsed != nil {
completion(parsed!, nil)
} else {
completion([], "Parse error")
}
// do something with the response data or statusCode
case let .failure(error):
print("error = \(error)")
switch error {
case .underlying(let nsError):
// now can access NSError error.code or whatever
// e.g. NSURLErrorTimedOut or NSURLErrorNotConnectedToInternet
completion([], nsError.localizedDescription)
return
default: break
}
guard
let error = error as? CustomStringConvertible else {
completion([], "Unknown error")
return
}
completion([], error.description)
// this means there was a network failure - either the request
// wasn't sent (connectivity), or no response was received (server
// timed out). If the server responds with a 4xx or 5xx error, that
// will be sent as a ".success"-ful response.
}
}
}
}
enum PXAPI {
case photos(page: Int64, category: String)
}
extension PXAPI : TargetType {
public var parameterEncoding: ParameterEncoding {
return URLEncoding.default
}
var baseURL: URL { return URL(string: Constants.API.Paths.baseAddress)! }
var path : String {
switch self {
case .photos(_):
return Constants.API.Paths.photosPath
}
}
var method : Moya.Method {
switch self {
case .photos(_):
return .get
}
}
var parameters: [String: Any]? {
switch self {
case .photos(let page, let category):
var params = [
Constants.API.ParametersKeys.apiKey: Constants.API.apiKey,
Constants.API.ParametersKeys.feature: Constants.API.ParametersValues.feature,
Constants.API.ParametersKeys.imageSize: Constants.API.ParametersValues.imageSize,
Constants.API.ParametersKeys.page: page,
Constants.API.ParametersKeys.pageSize: Constants.API.ParametersValues.pageSize] as [String : Any]
if category != Constants.API.noFilterCategory {
params[Constants.API.ParametersKeys.categoryFilter] = category
}
return params
}
}
var sampleData: Data {
switch self {
case .photos(_):
return "{}".utf8Encoded
}
}
var task: Task {
switch self {
case .photos(_):
return .request
}
}
}
private extension String {
var urlEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
var utf8Encoded: Data {
return self.data(using: .utf8)!
}
}
| 735c4e654968ef4479afd0ee8b0a0248 | 24.390625 | 104 | 0.688923 | false | false | false | false |
ConradoMateu/Swift-Basics | refs/heads/master | Basic/Closures.playground/Contents.swift | apache-2.0 | 1 | //Github: Conradomateu
/*
Closures: usually enclosed in {}
(argument) -> (return type)
Anonimous functions -> blocks in Objective-C and lambda in other languages
*/
func calculate(x:Int, _ y: Int, _ operation: (Int , Int) -> Int) -> Int{
return operation(x,y)
}
func divide(x: Int, y: Int) -> Int { return x / y }
calculate(10, 5, divide)
// Inlining -> passing the function as parameter
calculate(10, 5, {(x: Int, y: Int) -> Int in return x / y })
// Type inference
calculate(10, 5, {(x,y) in return x / y })
// Delete braces and the `return` statement.
calculate(10, 5, {a, b in a / b})
// Shorthand arguments
calculate(10, 5, {$0 / $1})
// Trailing closures: last argument in the function call.Closure argument just goes out of braces.
calculate(3, 7){$0 * $1}
// Capturing values (Apple Sample)
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
let incrementByTen = makeIncrementer(forIncrement: 10)
incrementByTen()
incrementByTen()
// Nonescaping Closures: Adding @noescape guarantees that the closure will not be stored somewhere, used at a later time, or used asynchronously.
var foo: (()->Void)?
func noEscapeClosure(@noescape preparations: () -> Void) {
/*
closure trying to scape
foo = preparations
tryToScape(){preparations}
*/
preparations() //noescape
}
func tryToScape(closure: () -> ()){
foo = closure
}
//Autoclosures: If you pass expression as an argument of a function, it will be automatically wrapped by `autoclosure`, also applies @noescape for that closure parameter.
func num(n: () -> Int) -> Int {
return n()*2
}
var a = 10
var b = 15
num({a*b})
num(){a * b} //Trailing closures
func num(@autoclosure n: () -> Int) -> Int {
return n()*2
}
var c = 10
var d = 15
num (c*d)
| a7ad0d2cc43864cf8954463ad5466b42 | 20.21978 | 170 | 0.655101 | false | false | false | false |
HongliYu/firefox-ios | refs/heads/master | Client/Frontend/Widgets/SeparatorTableCell.swift | mpl-2.0 | 4 | /* 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
class SeparatorTableCell: UITableViewCell {
override var textLabel: UILabel? {
return nil
}
override var detailTextLabel: UILabel? {
return nil
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.indentationWidth = 0
self.separatorInset = .zero
self.layoutMargins = .zero
self.backgroundColor = UIColor.theme.tableView.rowBackground // So we get a gentle white and grey stripe.
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 1ffc1d6ea84cc5ca017b9cd8f9b747c4 | 30.793103 | 116 | 0.67462 | false | false | false | false |
ErAbhishekChandani/ACFloatingTextfield | refs/heads/master | Source-Swift/ACFloatingTextfield.swift | mit | 1 | //
// ACFloatingTextfield.swift
// ACFloatingTextField
//
// Created by Er Abhishek Chandani on 31/07/16.
// Copyright © 2016 Abhishek. All rights reserved.
//
import UIKit
@IBDesignable
@objc open class ACFloatingTextfield: UITextField {
fileprivate var bottomLineView : UIView?
fileprivate var labelPlaceholder : UILabel?
fileprivate var labelErrorPlaceholder : UILabel?
fileprivate var showingError : Bool = false
fileprivate var bottomLineViewHeight : NSLayoutConstraint?
fileprivate var placeholderLabelHeight : NSLayoutConstraint?
fileprivate var errorLabelHieght : NSLayoutConstraint?
/// Disable Floating Label when true.
@IBInspectable open var disableFloatingLabel : Bool = false
/// Shake Bottom line when Showing Error ?
@IBInspectable open var shakeLineWithError : Bool = true
/// Change Bottom Line Color.
@IBInspectable open var lineColor : UIColor = UIColor.black {
didSet{
self.floatTheLabel()
}
}
/// Change line color when Editing in textfield
@IBInspectable open var selectedLineColor : UIColor = UIColor(red: 19/256.0, green: 141/256.0, blue: 117/256.0, alpha: 1.0){
didSet{
self.floatTheLabel()
}
}
/// Change placeholder color.
@IBInspectable open var placeHolderColor : UIColor = UIColor.lightGray {
didSet{
self.floatTheLabel()
}
}
/// Change placeholder color while editing.
@IBInspectable open var selectedPlaceHolderColor : UIColor = UIColor(red: 19/256.0, green: 141/256.0, blue: 117/256.0, alpha: 1.0){
didSet{
self.floatTheLabel()
}
}
/// Change Error Text color.
@IBInspectable open var errorTextColor : UIColor = UIColor.red{
didSet{
self.labelErrorPlaceholder?.textColor = errorTextColor
self.floatTheLabel()
}
}
/// Change Error Line color.
@IBInspectable open var errorLineColor : UIColor = UIColor.red{
didSet{
self.floatTheLabel()
}
}
//MARK:- Set Text
override open var text:String? {
didSet {
if showingError {
self.hideErrorPlaceHolder()
}
floatTheLabel()
}
}
override open var placeholder: String? {
willSet {
if newValue != "" {
self.labelPlaceholder?.text = newValue
}
}
}
open var errorText : String? {
willSet {
self.labelErrorPlaceholder?.text = newValue
}
}
//MARK:- UITtextfield Draw Method Override
override open func draw(_ rect: CGRect) {
super.draw(rect)
self.upadteTextField(frame: CGRect(x:self.frame.minX, y:self.frame.minY, width:rect.width, height:rect.height));
}
// MARK:- Loading From NIB
override open func awakeFromNib() {
super.awakeFromNib()
self.initialize()
}
// MARK:- Intialization
override public init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.initialize()
}
// MARK:- Text Rect Management
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x:4, y:4, width:bounds.size.width, height:bounds.size.height);
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x:4, y:4, width:bounds.size.width, height:bounds.size.height);
}
//MARK:- UITextfield Becomes First Responder
override open func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
self.textFieldDidBeginEditing()
return result
}
//MARK:- UITextfield Resigns Responder
override open func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
self.textFieldDidEndEditing()
return result
}
//MARK:- Show Error Label
public func showError() {
showingError = true;
self.showErrorPlaceHolder();
}
public func hideError() {
showingError = false;
self.hideErrorPlaceHolder();
floatTheLabel()
}
public func showErrorWithText(errorText : String) {
self.errorText = errorText;
self.labelErrorPlaceholder?.text = self.errorText
showingError = true;
self.showErrorPlaceHolder();
}
}
fileprivate extension ACFloatingTextfield {
//MARK:- ACFLoating Initialzation.
func initialize() -> Void {
self.clipsToBounds = true
/// Adding Bottom Line
addBottomLine()
/// Placeholder Label Configuration.
addFloatingLabel()
/// Error Placeholder Label Configuration.
addErrorPlaceholderLabel()
/// Checking Floatibility
if self.text != nil && self.text != "" {
self.floatTheLabel()
}
}
//MARK:- ADD Bottom Line
func addBottomLine(){
if bottomLineView?.superview != nil {
return
}
//Bottom Line UIView Configuration.
bottomLineView = UIView()
bottomLineView?.backgroundColor = lineColor
bottomLineView?.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(bottomLineView!)
let leadingConstraint = NSLayoutConstraint.init(item: bottomLineView!, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint.init(item: bottomLineView!, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint.init(item: bottomLineView!, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
bottomLineViewHeight = NSLayoutConstraint.init(item: bottomLineView!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1)
self.addConstraints([leadingConstraint,trailingConstraint,bottomConstraint])
bottomLineView?.addConstraint(bottomLineViewHeight!)
self.addTarget(self, action: #selector(self.textfieldEditingChanged), for: .editingChanged)
}
@objc func textfieldEditingChanged(){
if showingError {
hideError()
}
}
//MARK:- ADD Floating Label
func addFloatingLabel(){
if labelPlaceholder?.superview != nil {
return
}
var placeholderText : String? = labelPlaceholder?.text
if self.placeholder != nil && self.placeholder != "" {
placeholderText = self.placeholder!
}
labelPlaceholder = UILabel()
labelPlaceholder?.text = placeholderText
labelPlaceholder?.textAlignment = self.textAlignment
labelPlaceholder?.textColor = placeHolderColor
labelPlaceholder?.font = UIFont.init(name: (self.font?.fontName ?? "helvetica")!, size: 12)
labelPlaceholder?.isHidden = true
labelPlaceholder?.sizeToFit()
labelPlaceholder?.translatesAutoresizingMaskIntoConstraints = false
self.attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: placeHolderColor])
if labelPlaceholder != nil {
self.addSubview(labelPlaceholder!)
}
let leadingConstraint = NSLayoutConstraint.init(item: labelPlaceholder!, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5)
let trailingConstraint = NSLayoutConstraint.init(item: labelPlaceholder!, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
let topConstraint = NSLayoutConstraint.init(item: labelPlaceholder!, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
placeholderLabelHeight = NSLayoutConstraint.init(item: labelPlaceholder!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 15)
self.addConstraints([leadingConstraint,trailingConstraint,topConstraint])
labelPlaceholder?.addConstraint(placeholderLabelHeight!)
}
func addErrorPlaceholderLabel() -> Void {
if self.labelErrorPlaceholder?.superview != nil{
return
}
labelErrorPlaceholder = UILabel()
labelErrorPlaceholder?.text = self.errorText
labelErrorPlaceholder?.textAlignment = self.textAlignment
labelErrorPlaceholder?.textColor = errorTextColor
labelErrorPlaceholder?.font = UIFont(name: (self.font?.fontName ?? "helvetica")!, size: 12)
labelErrorPlaceholder?.sizeToFit()
labelErrorPlaceholder?.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(labelErrorPlaceholder!)
let trailingConstraint = NSLayoutConstraint.init(item: labelErrorPlaceholder!, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
let topConstraint = NSLayoutConstraint.init(item: labelErrorPlaceholder!, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
errorLabelHieght = NSLayoutConstraint.init(item: labelErrorPlaceholder!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0)
self.addConstraints([trailingConstraint,topConstraint])
labelErrorPlaceholder?.addConstraint(errorLabelHieght!)
}
func showErrorPlaceHolder() {
bottomLineViewHeight?.constant = 2;
if self.errorText != nil && self.errorText != "" {
errorLabelHieght?.constant = 15;
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
self.bottomLineView?.backgroundColor = self.errorLineColor;
self.layoutIfNeeded()
}, completion: nil)
}else{
errorLabelHieght?.constant = 0;
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
self.bottomLineView?.backgroundColor = self.errorLineColor;
self.layoutIfNeeded()
}, completion: nil)
}
if shakeLineWithError {
bottomLineView?.shake()
}
}
func hideErrorPlaceHolder(){
showingError = false;
if errorText == nil || errorText == "" {
return
}
errorLabelHieght?.constant = 0;
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
//MARK:- Float & Resign
func floatTheLabel() -> Void {
DispatchQueue.main.async {
if self.text == "" && self.isFirstResponder {
self.floatPlaceHolder(selected: true)
}else if self.text == "" && !self.isFirstResponder {
self.resignPlaceholder()
}else if self.text != "" && !self.isFirstResponder {
self.floatPlaceHolder(selected: false)
}else if self.text != "" && self.isFirstResponder {
self.floatPlaceHolder(selected: true)
}
}
}
//MARK:- Upadate and Manage Subviews
func upadteTextField(frame:CGRect) -> Void {
self.frame = frame;
self.initialize()
}
//MARK:- Float UITextfield Placeholder Label
func floatPlaceHolder(selected:Bool) -> Void {
labelPlaceholder?.isHidden = false
if selected {
bottomLineView?.backgroundColor = showingError ? self.errorLineColor : self.selectedLineColor;
bottomLineViewHeight?.constant = 2;
labelPlaceholder?.textColor = self.selectedPlaceHolderColor;
self.attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: selectedPlaceHolderColor])
} else {
bottomLineView?.backgroundColor = showingError ? self.errorLineColor : self.lineColor;
bottomLineViewHeight?.constant = 1;
self.labelPlaceholder?.textColor = self.placeHolderColor
self.attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: placeHolderColor])
}
if disableFloatingLabel == true {
labelPlaceholder?.isHidden = true
return
}
if placeholderLabelHeight?.constant == 15 {
return
}
placeholderLabelHeight?.constant = 15;
labelPlaceholder?.font = UIFont(name: (self.font?.fontName)!, size: 12)
UIView.animate(withDuration: 0.2, animations: {
self.layoutIfNeeded()
})
}
//MARK:- Resign the Placeholder
func resignPlaceholder() -> Void {
self.attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: placeHolderColor])
bottomLineView?.backgroundColor = showingError ? self.errorLineColor : self.lineColor;
bottomLineViewHeight?.constant = 1;
if disableFloatingLabel {
labelPlaceholder?.isHidden = true
self.labelPlaceholder?.textColor = self.placeHolderColor;
UIView.animate(withDuration: 0.2, animations: {
self.layoutIfNeeded()
})
return
}
placeholderLabelHeight?.constant = self.frame.height
UIView.animate(withDuration: 0.3, animations: {
self.labelPlaceholder?.font = self.font
self.labelPlaceholder?.textColor = self.placeHolderColor
self.layoutIfNeeded()
}) { (finished) in
self.labelPlaceholder?.isHidden = true
self.placeholder = self.labelPlaceholder?.text
}
}
//MARK:- UITextField Begin Editing.
func textFieldDidBeginEditing() -> Void {
if showingError {
self.hideErrorPlaceHolder()
}
if !self.disableFloatingLabel {
self.placeholder = ""
}
self.floatTheLabel()
self.layoutSubviews()
}
//MARK:- UITextField Begin Editing.
func textFieldDidEndEditing() -> Void {
self.floatTheLabel()
}
}
//MARK:- Shake
extension UIView {
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
}
}
| 78fec9039d1fdfe4ac798916c21708b9 | 35.435714 | 191 | 0.630661 | false | false | false | false |
volodg/iAsync.social | refs/heads/master | Pods/iAsync.network/Lib/JURLConnectionCallbacks.swift | mit | 1 | //
// JURLConnectionCallbacks.swift
// JNetwork
//
// Created by Vladimir Gorbenko on 25.09.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
public typealias JDidReceiveResponseHandler = (response: NSHTTPURLResponse) -> ()
public typealias JDidFinishLoadingHandler = (error: NSError?) -> ()
public typealias JDidReceiveDataHandler = (data: NSData) -> ()
public typealias JDidUploadDataHandler = (progress: Float) -> ()
public typealias JShouldAcceptCertificateForHost = (host: String) -> Bool
| 7ac1e21185a4bf27c751bde3ba483d67 | 36.733333 | 86 | 0.713781 | false | false | false | false |
aschwaighofer/swift | refs/heads/master | test/SILOptimizer/infinite_recursion.swift | apache-2.0 | 5 | // RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify -enable-ownership-stripping-after-serialization
func a() { // expected-warning {{all paths through this function will call itself}}
a()
}
func b(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
if x != 0 {
b(x)
} else {
b(x+1)
}
}
func c(_ x : Int) {
if x != 0 {
c(5)
}
}
func d(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
var x = x
if x != 0 {
x += 1
}
return d(x)
}
// Doesn't warn on mutually recursive functions
func e() { f() }
func f() { e() }
func g() { // expected-warning {{all paths through this function will call itself}}
while true { // expected-note {{condition always evaluates to true}}
g()
}
g() // expected-warning {{will never be executed}}
}
func h(_ x : Int) {
while (x < 5) {
h(x+1)
}
}
func i(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
var x = x
while (x < 5) {
x -= 1
}
i(0)
}
func j() -> Int { // expected-warning {{all paths through this function will call itself}}
return 5 + j()
}
func k() -> Any { // expected-warning {{all paths through this function will call itself}}
return type(of: k())
}
@_silgen_name("exit") func exit(_: Int32) -> Never
func l() {
guard Bool.random() else {
exit(0) // no warning; calling 'exit' terminates the program
}
l()
}
func m() { // expected-warning {{all paths through this function will call itself}}
guard Bool.random() else {
fatalError() // we _do_ warn here, because fatalError is a programtermination_point
}
m()
}
enum MyNever {}
func blackHole() -> MyNever { // expected-warning {{all paths through this function will call itself}}
blackHole()
}
@_semantics("programtermination_point")
func terminateMe() -> MyNever {
terminateMe() // no warning; terminateMe is a programtermination_point
}
func n() -> MyNever {
if Bool.random() {
blackHole() // no warning; blackHole() will terminate the program
}
n()
}
func o() -> MyNever {
if Bool.random() {
o()
}
blackHole() // no warning; blackHole() will terminate the program
}
func mayHaveSideEffects() {}
func p() { // expected-warning {{all paths through this function will call itself}}
if Bool.random() {
mayHaveSideEffects() // presence of side-effects doesn't alter the check for the programtermination_point apply
fatalError()
}
p()
}
class S {
convenience init(a: Int) { // expected-warning {{all paths through this function will call itself}}
self.init(a: a)
}
init(a: Int?) {}
static func a() { // expected-warning {{all paths through this function will call itself}}
return a()
}
func b() { // expected-warning {{all paths through this function will call itself}}
var i = 0
repeat {
i += 1
b()
} while (i > 5)
}
var bar: String = "hi!"
}
class T: S {
// No warning, calls super
override func b() {
var i = 0
repeat {
i += 1
super.b()
} while (i > 5)
}
override var bar: String {
get {
return super.bar
}
set { // expected-warning {{all paths through this function will call itself}}
self.bar = newValue
}
}
}
func == (l: S?, r: S?) -> Bool { // expected-warning {{all paths through this function will call itself}}
if l == nil && r == nil { return true }
guard let l = l, let r = r else { return false }
return l === r
}
public func == <Element>(lhs: Array<Element>, rhs: Array<Element>) -> Bool { // expected-warning {{all paths through this function will call itself}}
return lhs == rhs
}
func factorial(_ n : UInt) -> UInt { // expected-warning {{all paths through this function will call itself}}
return (n != 0) ? factorial(n - 1) * n : factorial(1)
}
func tr(_ key: String) -> String { // expected-warning {{all paths through this function will call itself}}
return tr(key) ?? key // expected-warning {{left side of nil coalescing operator '??' has non-optional type}}
}
| bad7ae270c846ae58b00506985f6dd00 | 23.109827 | 149 | 0.621913 | false | false | false | false |
ferdinandurban/HUDini | refs/heads/master | HUDini/Views/Base/HUDiniBaseAnimatedView.swift | mit | 1 | //
// HUDiniBaseAnimatedView.swift
// HUDini
//
// Created by Ferdinand Urban on 17/10/15.
// Copyright © 2015 Ferdinand Urban. All rights reserved.
//
import UIKit
public class HUDiniBaseAnimatedView: HUDiniBaseSquareView, HUDiniAnimation {
let defaultAnimationShapeLayer: CAShapeLayer = {
let defaultPath = UIBezierPath()
defaultPath.moveToPoint(CGPointMake(4.0, 27.0))
defaultPath.addLineToPoint(CGPointMake(34.0, 56.0))
defaultPath.addLineToPoint(CGPointMake(88.0, 0.0))
let layer = CAShapeLayer()
layer.frame = CGRectMake(3.0, 3.0, 88.0, 56.0)
layer.path = defaultPath.CGPath
layer.fillMode = kCAFillModeForwards
layer.lineCap = kCALineCapRound
layer.lineJoin = kCALineJoinRound
layer.fillColor = nil
layer.strokeColor = UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1.0).CGColor
layer.lineWidth = 6.0
return layer
}()
var shapeLayer: CAShapeLayer?
public override init() {
super.init(frame: HUDiniBaseSquareView.defaultBaseFrame)
shapeLayer = defaultAnimationShapeLayer
}
public init(withShape shape: HUDiniAnimatedShapeLayers.Code) {
super.init(frame: HUDiniBaseSquareView.defaultBaseFrame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
} | efa59c68f588badd806c573b757f07a1 | 30.510638 | 93 | 0.630405 | false | false | false | false |
tlax/looper | refs/heads/master | looper/View/Camera/Filter/BlenderOverlay/VCameraFilterBlenderOverlayListAdd.swift | mit | 1 | import UIKit
class VCameraFilterBlenderOverlayListAdd:UIButton
{
weak var layoutLeft:NSLayoutConstraint!
private weak var image:UIImageView!
private let kAnimationImagesDuration:TimeInterval = 0.15
private let kAnimationDuration:TimeInterval = 0.5
init()
{
super.init(frame:CGRect.zero)
clipsToBounds = true
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor.clear
let animatingImages:[UIImage] = [
#imageLiteral(resourceName: "assetCameraFilterBlenderAdd1"),
#imageLiteral(resourceName: "assetCameraFilterBlenderAdd2"),
#imageLiteral(resourceName: "assetCameraFilterBlenderAdd3"),
#imageLiteral(resourceName: "assetCameraFilterBlenderAdd4"),
#imageLiteral(resourceName: "assetCameraFilterBlenderAdd5"),
#imageLiteral(resourceName: "assetCameraFilterBlenderAdd0")]
let image:UIImageView = UIImageView()
image.isUserInteractionEnabled = false
image.translatesAutoresizingMaskIntoConstraints = false
image.clipsToBounds = true
image.contentMode = UIViewContentMode.center
image.image = #imageLiteral(resourceName: "assetCameraFilterBlenderAdd0")
image.animationImages = animatingImages
image.animationDuration = kAnimationImagesDuration
self.image = image
addSubview(image)
NSLayoutConstraint.equals(
view:image,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
deinit
{
image.stopAnimating()
}
//MARK: public
func animateHide()
{
guard
let width:CGFloat = superview?.bounds.maxX
else
{
return
}
let halfWidth:CGFloat = width / 2.0
let halfSelfWidth:CGFloat = bounds.midX
let totalWidth:CGFloat = width + halfWidth - halfSelfWidth
image.startAnimating()
layoutLeft.constant = totalWidth
UIView.animate(
withDuration:kAnimationDuration,
animations:
{ [weak self] in
self?.superview?.layoutIfNeeded()
})
{ [weak self] (done:Bool) in
self?.image.stopAnimating()
}
}
func animateShow()
{
guard
let width:CGFloat = superview?.bounds.maxX
else
{
return
}
let selfWidth:CGFloat = bounds.maxX
let remainLeft:CGFloat = width - selfWidth
let marginLeft:CGFloat = remainLeft / 2.0
image.startAnimating()
layoutLeft.constant = marginLeft
UIView.animate(
withDuration:kAnimationDuration,
animations:
{ [weak self] in
self?.superview?.layoutIfNeeded()
})
{ [weak self] (done:Bool) in
self?.image.stopAnimating()
}
}
}
| 58daec57930f562d35de95d37650b42e | 26.350877 | 81 | 0.5805 | false | false | false | false |
raychrd/tada | refs/heads/master | tada/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// tada
//
// Created by Ray on 15/1/24.
// Copyright (c) 2015年 Ray. All rights reserved.
//
import UIKit
import EventKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var eventStore:EKEventStore?
var events:[EKReminder] = Array()
var events2:[EKReminder] = Array()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//UINavigationBar.clipsToBounds = true
//UINavigationBar.appearance().tintColor = UIColor.whiteColor()
/*
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "HelveticaNeue", size: 22)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
//UINavigationBar.appearance().clipsToBounds = true
*/
/*
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
UINavigationBar.navigationController?.interactivePopGestureRecognizer.delegate = nil
}
*/
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
//appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
return true
}
/*
func application(application: UIApplication , didReceiveLocalNotification notification: EKEventStoreChangedNotification) {
alertView.show()
}
*/
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:.
println("BYE")
}
}
| 1c22cc336a0cc7c83b4f7be2e98b6cae | 41.166667 | 285 | 0.719064 | false | false | false | false |
ccrama/Slide-iOS | refs/heads/master | Slide for Reddit/AutoplayScrollViewHandler.swift | apache-2.0 | 1 | //
// AutoplayScrollViewHandler.swift
// Slide for Reddit
//
// Created by Carlos Crane on 9/17/19.
// Copyright © 2019 Haptic Apps. All rights reserved.
//
import UIKit
//Abstracts logic for playing AutoplayBannerLinkCellView videos
/* To enable on any vc, include this line
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollDelegate.scrollViewDidScroll(scrollView)
}
*/
protocol AutoplayScrollViewDelegate: class {
func didScrollExtras(_ currentY: CGFloat)
var isScrollingDown: Bool { get set }
var lastScrollDirectionWasDown: Bool { get set }
var lastYUsed: CGFloat { get set }
var lastY: CGFloat { get set }
var currentPlayingIndex: [IndexPath] { get set }
func getTableView() -> UICollectionView
}
class AutoplayScrollViewHandler {
weak var delegate: AutoplayScrollViewDelegate?
init(delegate: AutoplayScrollViewDelegate) {
self.delegate = delegate
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let currentY = scrollView.contentOffset.y
guard let delegate = self.delegate else {
return
}
delegate.isScrollingDown = currentY > delegate.lastY
delegate.didScrollExtras(currentY)
delegate.lastScrollDirectionWasDown = delegate.isScrollingDown
let center = CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)
delegate.lastYUsed = currentY
delegate.lastY = currentY
if SettingValues.autoPlayMode == .ALWAYS || (SettingValues.autoPlayMode == .WIFI && LinkCellView.cachedCheckWifi) {
let visibleVideoIndices = delegate.getTableView().indexPathsForVisibleItems
let mapping: [(index: IndexPath, cell: LinkCellView)] = visibleVideoIndices.compactMap { index in
// Collect just cells that are autoplay video
if let cell = delegate.getTableView().cellForItem(at: index) as? LinkCellView {
return (index, cell)
} else {
return nil
}
}.sorted { (item1, item2) -> Bool in
delegate.isScrollingDown ? item1.index.row > item2.index.row : item1.index.row < item2.index.row
}
for currentIndex in delegate.currentPlayingIndex {
if let currentCell = delegate.getTableView().cellForItem(at: currentIndex) as? LinkCellView, currentCell is AutoplayBannerLinkCellView || currentCell is GalleryLinkCellView {
let videoViewCenter = currentCell.videoView.convert(currentCell.videoView.bounds, to: nil)
//print("Diff for scroll down is \(abs(videoViewCenter.y - center.y)) and \(scrollView.frame.size.height / 4 )")
if abs(videoViewCenter.midY - center.y) > scrollView.frame.size.height / 2 && currentCell.videoView.player != nil {
currentCell.endVideos()
}
}
}
var chosenPlayItems = [(index: IndexPath, cell: LinkCellView)]()
for item in mapping {
if item.cell is AutoplayBannerLinkCellView || item.cell is GalleryLinkCellView {
let videoViewCenter = item.cell.videoView.convert(item.cell.videoView.bounds, to: nil)
if abs(videoViewCenter.midY - center.y) > scrollView.frame.size.height / 2 {
continue
}
chosenPlayItems.append(item)
}
}
for item in chosenPlayItems {
if !delegate.currentPlayingIndex.contains(where: { (index2) -> Bool in
return item.index.row == index2.row
}) {
item.cell.doLoadVideo()
}
}
delegate.currentPlayingIndex = chosenPlayItems.map({ (item) -> IndexPath in
return item.index
})
}
}
func autoplayOnce(_ scrollView: UICollectionView) {
guard let delegate = self.delegate else {
return
}
if SettingValues.autoPlayMode == .ALWAYS || (SettingValues.autoPlayMode == .WIFI && LinkCellView.cachedCheckWifi) {
let visibleVideoIndices = delegate.getTableView().indexPathsForVisibleItems
let mapping: [(index: IndexPath, cell: LinkCellView)] = visibleVideoIndices.compactMap { index in
// Collect just cells that are autoplay video
if let cell = delegate.getTableView().cellForItem(at: index) as? LinkCellView {
return (index, cell)
} else {
return nil
}
}.sorted { (item1, item2) -> Bool in
delegate.isScrollingDown ? item1.index.row > item2.index.row : item1.index.row < item2.index.row
}
var chosenPlayItems = [(index: IndexPath, cell: LinkCellView)]()
for item in mapping {
if item.cell is AutoplayBannerLinkCellView {
chosenPlayItems.append(item)
}
}
for item in chosenPlayItems {
if !delegate.currentPlayingIndex.contains(where: { (index2) -> Bool in
return item.index.row == index2.row
}) {
(item.cell as! AutoplayBannerLinkCellView).doLoadVideo()
}
}
delegate.currentPlayingIndex = chosenPlayItems.map({ (item) -> IndexPath in
return item.index
})
}
}
}
| 6e97c08c782b068b858ed0636f931dbd | 40.345324 | 190 | 0.577867 | false | false | false | false |
nessBautista/iOSBackup | refs/heads/master | iOSNotebook/Pods/Outlaw/Sources/Outlaw/Set+ValueWithContext.swift | cc0-1.0 | 1 | //
// Set+ValueWithContext.swift
// Outlaw
//
// Created by Brian Mullen on 11/15/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
public extension Set {
public static func mappedValue<Element: ValueWithContext>(from object: Any, using context: Element.Context) throws -> Set<Element> {
let anyArray: [Element] = try [Element].mappedValue(from: object, using: context)
return Set<Element>(anyArray)
}
}
// MARK: -
// MARK: Transforms
public extension Set {
public static func mappedValue<Element: ValueWithContext, T>(from object: Any, using context: Element.Context, with transform:(Element, Element.Context) throws -> T) throws -> Set<T> {
let anyArray: [T] = try [Element].mappedValue(from: object, using: context, with: transform)
return Set<T>(anyArray)
}
public static func mappedValue<Element: ValueWithContext, T>(from object: Any, using context: Element.Context, with transform:(Element?, Element.Context) throws -> T) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, using: context, with: transform)
return Set<T>(anyArray.flatMap { $0 })
}
public static func mappedValue<Element: ValueWithContext, T>(from object: Any, using context: Element.Context, with transform:(Element, Element.Context) -> T?) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, using: context, with: transform)
return Set<T>(anyArray.flatMap { $0 })
}
public static func mappedValue<Element: ValueWithContext, T>(from object: Any, using context: Element.Context, with transform:(Element?, Element.Context) -> T?) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, using: context, with: transform)
return Set<T>(anyArray.flatMap { $0 })
}
}
| 20d9e5abc91b2c26c003bfa5b317f6eb | 43.97619 | 189 | 0.676019 | false | false | false | false |
apparata/ProjectKit | refs/heads/master | Sources/ProjectKit/Project File Objects/Base/ObjectID.swift | mit | 1 |
import Foundation
public class ObjectID {
public let id: String
public required init(id: String) {
self.id = id
}
}
extension ObjectID: Equatable {
public static func ==(lhs: ObjectID, rhs: ObjectID) -> Bool {
return lhs.id == rhs.id
}
}
extension ObjectID: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
| 695d9356217e1d0b6ebeba83916d2a17 | 14.807692 | 65 | 0.596107 | false | false | false | false |
KYawn/myiOS | refs/heads/master | Questions/Questions/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// Questions
//
// Created by K.Yawn Xoan on 3/23/15.
// Copyright (c) 2015 K.Yawn Xoan. All rights reserved.
//
import UIKit
class ViewController: UIViewController,NSXMLParserDelegate{
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBOutlet weak var btnSubmit: UIButton!
@IBOutlet weak var tfInputAnswer: UITextField!
@IBOutlet weak var lAnswerD: UILabel!
@IBOutlet weak var lAnswerC: UILabel!
@IBOutlet weak var lAnswerB: UILabel!
@IBOutlet weak var lAnswerA: UILabel!
@IBOutlet weak var lQuestion: UILabel!
var questions:Array<Question> = []
var currentQuestion:Question
var currentShowQuestion:Question
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var parser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("questions", ofType: "xml")!))
parser?.delegate = self
parser?.parse()
}
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {
if elementName == "question"{
currentQuestion = Question()
questions.append(currentQuestion)
currentQuestion.question = attributeDict["text"]! as String
currentQuestion.right = attributeDict["right"]! as String
} else if elementName == "answer"{
var tag = attributeDict["tag"]! as String
if tag == "A"{
currentQuestion.answerA = attributeDict["text"]! as String
}else if tag == "B"{
currentQuestion.answerB = attributeDict["text"]! as String
}else if tag == "C"{
currentQuestion.answerC = attributeDict["text"]! as String
}else if tag == "D"{
currentQuestion.answerD = attributeDict["text"]! as String
}
}
}
func parserDidEndDocument(parser: NSXMLParser!) {
// println("Size of array:\(questions.count)")
var q = questions[0]
lQuestion.text = currentShowQuestion.question
lAnswerA.text = currentShowQuestion.answerA
lAnswerB.text = currentShowQuestion.answerB
lAnswerC.text = currentShowQuestion.answerC
lAnswerD.text = currentShowQuestion.answerD
}
@IBAction func btnPressed(sender: UIButton) {
if tfInputAnswer.text == currentShowQuestion.right{
println("right")
}else{
println("wrong")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| acc56135f074190d3faf84f96c621142 | 31.706522 | 181 | 0.609837 | false | false | false | false |
midoks/Swift-Learning | refs/heads/master | GitHubStar/GitHubStar/GitHubStar/Controllers/common/repos/GsRepoDetailViewController.swift | apache-2.0 | 1 | //
// GsRepoDViewController.swift
// GitHubStar
//
// Created by midoks on 16/1/28.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
import SwiftyJSON
//项目详情页
class GsRepoDetailViewController: GsHomeViewController {
var _tableData:JSON = JSON.parse("")
var _repoBranchNum = 1
var _repoReadmeData:JSON = JSON.parse("")
var _fixedUrl = ""
var isStar = false
var asynGetStar = false
var _rightButton:GsRepoButton?
deinit {
print("deinit GsRepoDetailViewController")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.removeNotify()
//GitHubApi.instance.close()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.registerNotify()
self.initView()
}
override func viewDidLoad() {
super.viewDidLoad()
_rightButton = GsRepoButton()
self.navigationItem.rightBarButtonItem = _rightButton?.createButton(target: self)
self.navigationItem.rightBarButtonItem?.isEnabled = false
self.initView()
}
func initShareButton(){
print("test")
}
func initView(){
if _tableData != nil {
initHeadView()
initHeadIconView()
}
}
func initHeadView(){
self.setAvatar(url: _tableData["owner"]["avatar_url"].stringValue)
self.setName(name: _tableData["name"].stringValue)
self.setDesc(desc: _tableData["description"].stringValue)
}
func initHeadIconView(){
var v = Array<GsIconView>()
let stargazerts = GsIconView()
stargazerts.key.text = _tableData["stargazers_count"].stringValue
stargazerts.desc.text = "Stargazers"
v.append(stargazerts)
let watchers = GsIconView()
//let subscribers_count = _tableData["subscribers_count"].int
watchers.key.text = _tableData["subscribers_count"].stringValue
watchers.desc.text = "Watchers"
v.append(watchers)
let forks = GsIconView()
forks.key.text = _tableData["forks_count"].stringValue
forks.desc.text = "Forks"
v.append(forks)
self.setIconView(icon: v)
_headView.listClick = {(type) -> () in
switch type {
case 0:
let stargazers = GsUserListViewController()
stargazers.title = self.sysLang(key: "Stargazerts")
let url = "/repos/" + self._tableData["full_name"].stringValue + "/stargazers"
stargazers.setUrlData(url: url)
self.push(v: stargazers)
break
case 1:
let watchers = GsUserListViewController()
watchers.title = self.sysLang(key: "Watchers")
//watchers_count
watchers.setUrlData(url: "/repos/" + self._tableData["full_name"].stringValue + "/subscribers")
self.push(v: watchers)
break
case 2:
let forks = GsRepoForksViewController()
forks.title = self.sysLang(key: "Forks")
forks.setUrlData(url: "/repos/" + self._tableData["full_name"].stringValue + "/forks")
self.push(v: forks)
break
default:break
}
}
}
//MARK: - Private Method -
func setTableData(data:JSON){
self.endRefresh()
self._tableData = data
self.initView()
self.reloadData()
}
func setUrlData(url:String){
_fixedUrl = url
}
func setUrlWithData(data:JSON){
_fixedUrl = data["full_name"].stringValue
//print(data["owner"]["avatar_url"].stringValue, data["name"].stringValue)
self.setAvatar(url: data["owner"]["avatar_url"].stringValue)
self.setName(name: data["name"].stringValue)
}
func setPUrlWithData(data:JSON){
_fixedUrl = data["parent"]["full_name"].stringValue
self.setAvatar(url: data["owner"]["avatar_url"].stringValue)
self.setName(name: data["name"].stringValue)
}
override func refreshUrl(){
super.refreshUrl()
if _fixedUrl != "" {
self.startRefresh()
GitHubApi.instance.getRepo(name: _fixedUrl, callback: { (data) in
self.endRefresh()
self._tableData = data
self.initView()
self.reloadData()
})
}
}
func reloadData(){
self.asynTask {
self._tableView?.reloadData()
self.postNotify()
}
}
}
extension GsRepoDetailViewController {
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.initView()
}
}
//MARK: - UITableViewDelegate & UITableViewDataSource -
extension GsRepoDetailViewController {
private func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if _tableData.count == 0 {
return 0
}
if _tableData["homepage"].stringValue != "" {
return 5
}
return 4
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 0
} else if section == 1 {
var i1 = 4
let v = self._tableData["parent"]
if v.count>0 {
i1 += 1
}
return i1
} else if section == 2 {
var i2 = 1
if self._tableData["has_issues"].boolValue || _tableData["open_issues"].intValue > 0 {
i2 += 1
}
if self._tableData.count > 0 {
i2 += 1
}
return i2
} else if section == 3 {
return 3
} else if section == 4{
return 1
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 1 {
if indexPath.row == 0 {
let cell = GsRepo2RowCell(style: .default, reuseIdentifier: nil)
cell.row1.setImage(UIImage(named: "repo_access"), for: .normal)
let v1 = _tableData["private"].boolValue ? sysLang(key: "Private") : sysLang(key: "Public")
cell.row1.setTitle(v1, for: .normal)
cell.row2.setImage(UIImage(named: "repo_language"), for: .normal)
let lang = _tableData["language"].stringValue == "" ? "N/A" : _tableData["language"].stringValue
cell.row2.setTitle(lang, for: .normal)
return cell
} else if indexPath.row == 1 {
let cell = GsRepo2RowCell(style: .default, reuseIdentifier: nil)
cell.row1.setImage(UIImage(named: "repo_issues"), for: .normal)
cell.row1.setTitle(_tableData["open_issues"].stringValue + sysLang(key: " Issues"), for: .normal
)
cell.row2.setImage(UIImage(named: "repo_branch"), for: .normal)
cell.row2.setTitle(String(_repoBranchNum) + sysLang(key: " Branches"), for: .normal)
return cell
} else if indexPath.row == 2 {
let cell = GsRepo2RowCell(style: .default, reuseIdentifier: nil)
cell.row1.setImage(UIImage(named: "repo_date"), for: .normal)
let date = _tableData["created_at"].stringValue
cell.row1.setTitle(gitTimeYmd(ctime: date), for: .normal)
cell.row2.setImage(UIImage(named: "repo_size"), for: .normal)
_ = _tableData["size"].float
cell.row2.setTitle(gitSize(s: 1, i: _tableData["size"].int!), for: .normal)
return cell
} else if indexPath.row == 3 {
let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
cell.textLabel?.text = sysLang(key: "Owner")
cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
cell.imageView?.image = UIImage(named: "repo_owner")
cell.detailTextLabel?.text = _tableData["owner"]["login"].stringValue
cell.accessoryType = .disclosureIndicator
return cell
} else if indexPath.row == 4 {
let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
cell.imageView?.image = UIImage(named: "repo_branch")
cell.textLabel?.text = sysLang(key: "Forked from")
cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
cell.detailTextLabel?.text = _tableData["parent"]["owner"]["login"].stringValue
cell.accessoryType = .disclosureIndicator
return cell
}
} else if indexPath.section == 2 {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
if indexPath.row == 0 {
cell.textLabel?.text = sysLang(key: "Events")
cell.imageView?.image = UIImage(named: "repo_events")
} else {
if _tableData["has_issues"].boolValue || _tableData["open_issues"].intValue > 0 {
if indexPath.row == 1 {
cell.textLabel?.text = sysLang(key: "Issues")
cell.imageView?.image = UIImage(named: "repo_issues")
} else if indexPath.row == 2 {
cell.textLabel?.text = sysLang(key: "Readme")
cell.imageView?.image = UIImage(named: "repo_readme")
}
} else {
cell.textLabel?.text = sysLang(key: "Readme")
cell.imageView?.image = UIImage(named: "repo_readme")
}
}
cell.accessoryType = .disclosureIndicator
return cell
} else if indexPath.section == 3 {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
if indexPath.row == 0 {
cell.textLabel?.text = "Commits"
cell.imageView?.image = UIImage(named: "repo_commits")
} else if indexPath.row == 1 {
cell.textLabel?.text = "Pull Requests"
cell.imageView?.image = UIImage(named: "repo_pullrequests")
} else if indexPath.row == 2 {
cell.textLabel?.text = "Source"
cell.imageView?.image = UIImage(named: "repo_source")
}
cell.accessoryType = .disclosureIndicator
return cell
} else if indexPath.section == 4 {
let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
cell.imageView?.image = UIImage(named: "repo_website")
cell.textLabel?.text = "Website"
cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
cell.accessoryType = .disclosureIndicator
return cell
}
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1 {
if indexPath.row == 3 {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let author = GsUserHomeViewController()
author.setUrlWithData(data: _tableData["owner"])
self.push(v: author)
} else if indexPath.row == 4 {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let forked_from = GsRepoDetailViewController()
forked_from.setPUrlWithData(data: _tableData)
self.push(v: forked_from)
}
} else {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
if indexPath.section == 2 {
let cell = tableView.cellForRow(at: indexPath as IndexPath)
let cellText = cell?.textLabel?.text
if cellText == sysLang(key: "Events") {
let event = GsEventsViewController()
event.setUrlData(url: "/repos/" + _tableData["full_name"].stringValue + "/events")
self.push(v: event)
} else if cellText == sysLang(key: "Issues") {
let issue = GsIssuesViewController()
let url = GitHubApi.instance.buildUrl(path: "/repos/" + _tableData["full_name"].stringValue + "/issues")
issue.setUrlData(url: url)
self.push(v: issue)
} else if cellText == sysLang(key: "Readme") {
let repoReadme = GsRepoReadmeViewController()
repoReadme.setReadmeData(data: _repoReadmeData)
self.push(v: repoReadme)
}
} else if indexPath.section == 3 {
if indexPath.row == 0 {
//go to commit list info page,if have only one branch.
// if _repoBranchNum == 1 {
// let repoCommitMaster = GsCommitsListViewController()
// let url = GitHubApi.instance().buildUrl("/repos/" + _tableData["full_name"].stringValue + "/commits?sha=master")
// repoCommitMaster.setUrlData(url)
// self.push(repoCommitMaster)
// } else { //go to commit branch page
let repoCommits = GsCommitsViewController()
let url = GitHubApi.instance.buildUrl(path: "/repos/" + _tableData["full_name"].stringValue + "/branches")
repoCommits.setUrlData( url: url )
self.push(v: repoCommits)
//}
} else if indexPath.row == 1 {
let repoPull = GsPullListViewController()
repoPull.setUrlData( url: "/repos/" + _tableData["full_name"].stringValue + "/pulls" )
self.push(v: repoPull)
} else if indexPath.row == 2 {
let repoSource = GsRepoSourceViewController()
repoSource.setUrlData( url: "/repos/" + _tableData["full_name"].stringValue + "/branches" )
self.push(v: repoSource)
}
} else if indexPath.section == 4 {
if indexPath.row == 0 {
let url = _tableData["homepage"].stringValue
UIApplication.shared.openURL(NSURL(string: url)! as URL)
}
}
}
}
}
//MARK: - 通知相关方法 -
extension GsRepoDetailViewController{
func registerNotify(){
let center = NotificationCenter.default
center.addObserver(self, selector: Selector(("getRepoBranch:")), name: NSNotification.Name(rawValue: "getRepoBranch"), object: nil)
center.addObserver(self, selector: Selector(("getRepoReadme:")), name: NSNotification.Name(rawValue: "getRepoReadme"), object: nil)
center.addObserver(self, selector: Selector(("getRepoStarStatus:")), name: NSNotification.Name(rawValue: "getRepoStarStatus"), object: nil)
}
func removeNotify(){
let center = NotificationCenter.default
center.removeObserver(self, name: NSNotification.Name(rawValue: "getRepoBranch"), object: nil)
center.removeObserver(self, name: NSNotification.Name(rawValue: "getRepoReadme"), object: nil)
center.removeObserver(self, name: NSNotification.Name(rawValue: "getRepoStarStatus"), object: nil)
}
//添加通知
func postNotify(){
let center = NotificationCenter.default
center.post(name: NSNotification.Name(rawValue: "getRepoBranch"), object: nil)
center.post(name: NSNotification.Name(rawValue: "getRepoReadme"), object: nil)
if self.isLogin() {
center.post(name: NSNotification.Name(rawValue: "getRepoStarStatus"), object: nil)
}
}
//获取项目分支数据
func getRepoBranch(notify:NSNotification){
let branchValue = self._tableData["full_name"].stringValue
let repoBranch = "/repos/" + branchValue + "/branches"
//print(repoBranch)
GitHubApi.instance.urlGet(url: repoBranch) { (data, response, error) -> Void in
if data != nil {
var count = self.gitJsonParse(data: data!).count
if response != nil {
let rep = response as! HTTPURLResponse
if rep.allHeaderFields["Link"] != nil {
let r = self.gitParseLink(urlLink: rep.allHeaderFields["Link"] as! String)
if r.lastPage != "" {
let pageCount = r.lastNum - 1
GitHubApi.instance.webGet(absoluteUrl: r.lastPage, callback: { (data, response, error) -> Void in
if data != nil {
count = pageCount*30 + self.gitJsonParse(data: data!).count
}
self._repoBranchNum = count
self._tableView?.reloadData()
self.asynIsLoadSuccessToEnableEdit()
})
}
} else {
self._repoBranchNum = count
self._tableView?.reloadData()
}
}
}
}
}
//get repo readme
func getRepoReadme(notify:NSNotification){
let repoReadme = "/repos/" + _tableData["full_name"].stringValue + "/readme"
GitHubApi.instance.urlGet(url: repoReadme) { (data, response, error) -> Void in
if data != nil {
let _dataJson = self.gitJsonParse(data: data!)
self._repoReadmeData = _dataJson
self._tableView?.reloadData()
}
}
}
//get repo star status
func getRepoStarStatus(notify:NSNotification){
self.isStar = false
self.asynGetStar = false
let args = "/user/starred/" + _tableData["full_name"].stringValue
let url = GitHubApi.instance.buildUrl(path: args)
//print(url)
GitHubApi.instance.webGet(absoluteUrl: url, callback: { (data, response, error) in
self.asynGetStar = true
self.asynIsLoadSuccessToEnableEdit()
if data != nil {
//print(response)
let resp = response as! HTTPURLResponse
if resp.statusCode == 204 {
if !self.isStar {
self.isStar = true
self.setStarStatus(status: true)
}
}
}
})
}
func asynIsLoadSuccessToEnableEdit(){
if (self.asynGetStar){
MDTask.shareInstance.asynTaskFront(callback: {
self.navigationItem.rightBarButtonItem?.isEnabled = true
})
}
}
}
class GsRepoButton: NSObject {
var _target: GsRepoDetailViewController?
func createButton(target: GsRepoDetailViewController) -> UIBarButtonItem {
_target = target
let button = UIButton()
button.frame = CGRect(x: 0.0, y: 0.0, width: 30.0, height: 30.0)
button.setImage(UIImage(named: "repo_share"), for: .normal)
button.addTarget(self, action: Selector(("buttonTouched:")), for: UIControlEvents.touchUpInside)
return UIBarButtonItem(customView: button)
}
func buttonTouched(sender: AnyObject) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
if _target!.isStar {
let unstar = UIAlertAction(title: "Unstar This Repo", style: .default) { (UIAlertAction) in
let args = "/user/starred/" + self._target!._tableData["full_name"].stringValue
let url = GitHubApi.instance.buildUrl(path: args)
GitHubApi.instance.delete(url: url, callback: { (data, response, error) in
if data != nil {
let resp = response as! HTTPURLResponse
if resp.statusCode == 204 {
self._target?.isStar = false
self._target?.removeStarStatus()
self._target?.showTextWithTime(msg: "SUCCESS", time: 2)
} else {
self._target?.isStar = true
self._target?.showTextWithTime(msg: "FAIL", time: 2)
}
}
self._target!.asynIsLoadSuccessToEnableEdit()
})
}
alert.addAction(unstar)
} else {
let star = UIAlertAction(title: "Star This Repo", style: .default) { (UIAlertAction) in
let args = "/user/starred/" + self._target!._tableData["full_name"].stringValue
let url = GitHubApi.instance.buildUrl(path: args)
GitHubApi.instance.put(url: url, callback: { (data, response, error) in
if data != nil {
let resp = response as! HTTPURLResponse
if resp.statusCode == 204 {
self._target?.isStar = true
self._target?.setStarStatus(status: true)
self._target?.showTextWithTime(msg: "SUCCESS", time: 2)
} else {
self._target?.isStar = false
self._target?.showTextWithTime(msg: "FAIL", time: 2)
}
}
self._target!.asynIsLoadSuccessToEnableEdit()
})
}
alert.addAction(star)
}
let cancal = UIAlertAction(title: "Cancel", style: .cancel) { (UIAlertAction) in
}
alert.addAction(cancal)
_target!.present(alert, animated: true) {
}
}
}
| 8440a880802ee8c360312279704e41d9 | 37.334395 | 158 | 0.504694 | false | false | false | false |
AaronMT/firefox-ios | refs/heads/main | Client/Frontend/Browser/TabScrollController.swift | mpl-2.0 | 10 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
private let ToolbarBaseAnimationDuration: CGFloat = 0.2
class TabScrollingController: NSObject {
enum ScrollDirection {
case up
case down
}
enum ToolbarState {
case collapsed
case visible
case animating
}
weak var tab: Tab? {
willSet {
self.scrollView?.delegate = nil
self.scrollView?.removeGestureRecognizer(panGesture)
}
didSet {
self.scrollView?.addGestureRecognizer(panGesture)
scrollView?.delegate = self
}
}
weak var header: UIView?
weak var footer: UIView?
weak var urlBar: URLBarView?
weak var readerModeBar: ReaderModeBarView?
weak var snackBars: UIView?
var footerBottomConstraint: Constraint?
var headerTopConstraint: Constraint?
var toolbarsShowing: Bool { return headerTopOffset == 0 }
fileprivate var isZoomedOut: Bool = false
fileprivate var lastZoomedScale: CGFloat = 0
fileprivate var isUserZoom: Bool = false
fileprivate var headerTopOffset: CGFloat = 0 {
didSet {
headerTopConstraint?.update(offset: headerTopOffset)
header?.superview?.setNeedsLayout()
}
}
fileprivate var footerBottomOffset: CGFloat = 0 {
didSet {
footerBottomConstraint?.update(offset: footerBottomOffset)
footer?.superview?.setNeedsLayout()
}
}
fileprivate lazy var panGesture: UIPanGestureRecognizer = {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
panGesture.maximumNumberOfTouches = 1
panGesture.delegate = self
return panGesture
}()
fileprivate var scrollView: UIScrollView? { return tab?.webView?.scrollView }
fileprivate var contentOffset: CGPoint { return scrollView?.contentOffset ?? .zero }
fileprivate var contentSize: CGSize { return scrollView?.contentSize ?? .zero }
fileprivate var scrollViewHeight: CGFloat { return scrollView?.frame.height ?? 0 }
fileprivate var topScrollHeight: CGFloat {
guard let headerHeight = header?.frame.height else { return 0 }
guard let readerModeHeight = readerModeBar?.frame.height else { return headerHeight }
return headerHeight + readerModeHeight
}
fileprivate var bottomScrollHeight: CGFloat { return footer?.frame.height ?? 0 }
fileprivate var snackBarsFrame: CGRect { return snackBars?.frame ?? .zero }
fileprivate var lastContentOffset: CGFloat = 0
fileprivate var scrollDirection: ScrollDirection = .down
fileprivate var toolbarState: ToolbarState = .visible
override init() {
super.init()
}
func showToolbars(animated: Bool, completion: ((_ finished: Bool) -> Void)? = nil) {
if toolbarState == .visible {
completion?(true)
return
}
toolbarState = .visible
let durationRatio = abs(headerTopOffset / topScrollHeight)
let actualDuration = TimeInterval(ToolbarBaseAnimationDuration * durationRatio)
self.animateToolbarsWithOffsets(
animated,
duration: actualDuration,
headerOffset: 0,
footerOffset: 0,
alpha: 1,
completion: completion)
}
func hideToolbars(animated: Bool, completion: ((_ finished: Bool) -> Void)? = nil) {
if toolbarState == .collapsed {
completion?(true)
return
}
toolbarState = .collapsed
let durationRatio = abs((topScrollHeight + headerTopOffset) / topScrollHeight)
let actualDuration = TimeInterval(ToolbarBaseAnimationDuration * durationRatio)
self.animateToolbarsWithOffsets(
animated,
duration: actualDuration,
headerOffset: -topScrollHeight,
footerOffset: bottomScrollHeight,
alpha: 0,
completion: completion)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "contentSize" {
if !checkScrollHeightIsLargeEnoughForScrolling() && !toolbarsShowing {
showToolbars(animated: true, completion: nil)
}
}
}
func updateMinimumZoom() {
guard let scrollView = scrollView else {
return
}
self.isZoomedOut = roundNum(scrollView.zoomScale) == roundNum(scrollView.minimumZoomScale)
self.lastZoomedScale = self.isZoomedOut ? 0 : scrollView.zoomScale
}
func setMinimumZoom() {
guard let scrollView = scrollView else {
return
}
if self.isZoomedOut && roundNum(scrollView.zoomScale) != roundNum(scrollView.minimumZoomScale) {
scrollView.zoomScale = scrollView.minimumZoomScale
}
}
func resetZoomState() {
self.isZoomedOut = false
self.lastZoomedScale = 0
}
fileprivate func roundNum(_ num: CGFloat) -> CGFloat {
return round(100 * num) / 100
}
}
private extension TabScrollingController {
func tabIsLoading() -> Bool {
return tab?.loading ?? true
}
func isBouncingAtBottom() -> Bool {
guard let scrollView = scrollView else { return false }
return scrollView.contentOffset.y > (scrollView.contentSize.height - scrollView.frame.size.height) && scrollView.contentSize.height > scrollView.frame.size.height
}
@objc func handlePan(_ gesture: UIPanGestureRecognizer) {
if tabIsLoading() {
return
}
if let containerView = scrollView?.superview {
let translation = gesture.translation(in: containerView)
let delta = lastContentOffset - translation.y
if delta > 0 {
scrollDirection = .down
} else if delta < 0 {
scrollDirection = .up
}
lastContentOffset = translation.y
if checkRubberbandingForDelta(delta) && checkScrollHeightIsLargeEnoughForScrolling() {
let bottomIsNotRubberbanding = contentOffset.y + scrollViewHeight < contentSize.height
let topIsRubberbanding = contentOffset.y <= 0
if (toolbarState != .collapsed || topIsRubberbanding) && bottomIsNotRubberbanding {
scrollWithDelta(delta)
}
if headerTopOffset == -topScrollHeight && footerBottomOffset == bottomScrollHeight {
toolbarState = .collapsed
} else if headerTopOffset == 0 {
toolbarState = .visible
} else {
toolbarState = .animating
}
}
if gesture.state == .ended || gesture.state == .cancelled {
lastContentOffset = 0
}
}
}
func checkRubberbandingForDelta(_ delta: CGFloat) -> Bool {
return !((delta < 0 && contentOffset.y + scrollViewHeight > contentSize.height &&
scrollViewHeight < contentSize.height) ||
contentOffset.y < delta)
}
func scrollWithDelta(_ delta: CGFloat) {
if scrollViewHeight >= contentSize.height {
return
}
var updatedOffset = headerTopOffset - delta
headerTopOffset = clamp(updatedOffset, min: -topScrollHeight, max: 0)
if isHeaderDisplayedForGivenOffset(updatedOffset) {
scrollView?.contentOffset = CGPoint(x: contentOffset.x, y: contentOffset.y - delta)
}
updatedOffset = footerBottomOffset + delta
footerBottomOffset = clamp(updatedOffset, min: 0, max: bottomScrollHeight)
let alpha = 1 - abs(headerTopOffset / topScrollHeight)
urlBar?.updateAlphaForSubviews(alpha)
readerModeBar?.updateAlphaForSubviews(alpha)
}
func isHeaderDisplayedForGivenOffset(_ offset: CGFloat) -> Bool {
return offset > -topScrollHeight && offset < 0
}
func clamp(_ y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
if y >= max {
return max
} else if y <= min {
return min
}
return y
}
func animateToolbarsWithOffsets(_ animated: Bool, duration: TimeInterval, headerOffset: CGFloat, footerOffset: CGFloat, alpha: CGFloat, completion: ((_ finished: Bool) -> Void)?) {
guard let scrollView = scrollView else { return }
let initialContentOffset = scrollView.contentOffset
// If this function is used to fully animate the toolbar from hidden to shown, keep the page from scrolling by adjusting contentOffset,
// Otherwise when the toolbar is hidden and a link navigated, showing the toolbar will scroll the page and
// produce a ~50px page jumping effect in response to tap navigations.
let isShownFromHidden = headerTopOffset == -topScrollHeight && headerOffset == 0
let animation: () -> Void = {
if isShownFromHidden {
scrollView.contentOffset = CGPoint(x: initialContentOffset.x, y: initialContentOffset.y + self.topScrollHeight)
}
self.headerTopOffset = headerOffset
self.footerBottomOffset = footerOffset
self.urlBar?.updateAlphaForSubviews(alpha)
self.readerModeBar?.updateAlphaForSubviews(alpha)
self.header?.superview?.layoutIfNeeded()
}
if animated {
UIView.animate(withDuration: duration, delay: 0, options: .allowUserInteraction, animations: animation, completion: completion)
} else {
animation()
completion?(true)
}
}
func checkScrollHeightIsLargeEnoughForScrolling() -> Bool {
return (UIScreen.main.bounds.size.height + 2 * UIConstants.ToolbarHeight) < scrollView?.contentSize.height ?? 0
}
}
extension TabScrollingController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension TabScrollingController: UIScrollViewDelegate {
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if tabIsLoading() || isBouncingAtBottom() {
return
}
if (decelerate || (toolbarState == .animating && !decelerate)) && checkScrollHeightIsLargeEnoughForScrolling() {
if scrollDirection == .up {
showToolbars(animated: true)
} else if scrollDirection == .down {
hideToolbars(animated: true)
}
}
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
// Only mess with the zoom level if the user did not initate the zoom via a zoom gesture
if self.isUserZoom {
return
}
//scrollViewDidZoom will be called multiple times when a rotation happens.
// In that case ALWAYS reset to the minimum zoom level if the previous state was zoomed out (isZoomedOut=true)
if isZoomedOut {
scrollView.zoomScale = scrollView.minimumZoomScale
} else if roundNum(scrollView.zoomScale) > roundNum(self.lastZoomedScale) && self.lastZoomedScale != 0 {
//When we have manually zoomed in we want to preserve that scale.
//But sometimes when we rotate a larger zoomScale is appled. In that case apply the lastZoomedScale
scrollView.zoomScale = self.lastZoomedScale
}
}
func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
self.isUserZoom = true
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
self.isUserZoom = false
}
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
if toolbarState == .collapsed {
showToolbars(animated: true)
return false
}
return true
}
}
| f9979fb0e19c3f6258e81420c5e272e5 | 36.210843 | 184 | 0.63696 | false | false | false | false |
bixubot/AcquainTest | refs/heads/master | ChatRoom/ChatRoom/CustomFoldingCell.swift | mit | 1 | //
// CustomFoldingCell.swift
// ChatRoom
//
// Created by Mutian on 4/28/17.
// Copyright © 2017 Binwei Xu. All rights reserved.
//
import UIKit
import Firebase
class CustomFoldingCell: FoldingCell {
@IBOutlet weak var closeNumberLabel: UILabel!
@IBOutlet weak var openNumberLabel: UILabel!
var number: Int = 0 {
didSet {
closeNumberLabel.text = String(number)
openNumberLabel.text = String(number)
}
}
override func awakeFromNib() {
foregroundView.layer.cornerRadius = 10
foregroundView.layer.masksToBounds = true
super.awakeFromNib()
}
override func animationDuration(_ itemIndex:NSInteger, type:AnimationType)-> TimeInterval {
let durations = [0.26, 0.2, 0.2]
return durations[itemIndex]
}
}
// MARK: Actions
extension CustomFoldingCell {
@IBAction func buttonHandler(_ sender: AnyObject) {
print("tap")
}
}
| 651e5dcbdf01e413002de9a6655d5545 | 22.093023 | 95 | 0.623364 | false | false | false | false |
fsproru/ScoutReport | refs/heads/master | ScoutReport/FeedViewController.swift | mit | 1 | import UIKit
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
let refreshControl = UIRefreshControl()
var posts: [InstagramPost] = []
var instagramClient: InstagramClientType = InstagramClient()
var presenter: PresenterType = Presenter()
override func viewDidLoad() {
setupTableView()
setupRefreshControl()
authenticateWithInstagramIfNeeded()
}
override func viewWillAppear(animated: Bool) {
fetchContentIfPossible()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("instagramPostCell") {
if let imageURL = NSURL(string: posts[indexPath.row].imageURLString), imageData = NSData(contentsOfURL: imageURL) {
cell.imageView?.image = UIImage(data: imageData)
}
return cell
}
return UITableViewCell()
}
func fetchContentIfPossible() {
if let instagramUsername = Suspect.chosenSuspect?.instagramUsername where Suspect.chosenSuspect?.instagramAccessToken != nil {
instagramClient.getContent(username: instagramUsername,
success: { [weak self] instagramPosts in
self?.refreshPosts(instagramPosts)
},
failure: { error in
}
)
}
}
private func authenticateWithInstagramIfNeeded() {
if Suspect.chosenSuspect?.instagramAccessToken == nil {
let instagramAuthViewController = UIStoryboard.loadViewController(storyboardName: "Feed", identifier: "instagramAuthViewController") as! InstagramAuthViewController
presenter.present(underlyingViewController: self, viewControllerToPresent: instagramAuthViewController, animated: true, completion: nil)
}
}
private func refreshPosts(instagramPosts: [InstagramPost]) {
posts = instagramPosts
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
if self.refreshControl.refreshing {
self.refreshControl.endRefreshing()
}
})
}
private func setupTableView() {
tableView.delegate = self
tableView.dataSource = self
}
private func setupRefreshControl() {
refreshControl.addTarget(self, action: "fetchContentIfPossible", forControlEvents: .ValueChanged)
tableView.addSubview(refreshControl)
}
} | 789ef1161a4fd0f15ab01ae33ab6782e | 36.671233 | 176 | 0.662423 | false | false | false | false |
nsagora/validation-toolkit | refs/heads/main | Sources/Constraints/Standard/RequiredConstraint.swift | mit | 1 | import Foundation
/**
A `Constraint` that check whether the input collection is empty.
```swift
enum Failure: Error {
case required
case invalidEmail
}
```
```swift
let constraint = RequiredConstraint<String, Failure>(error: .required)
let result = constraint.evaluate(with: "[email protected]")
```
*/
public struct RequiredConstraint<T: Collection, E: Error>: Constraint {
private let predicate = RequiredPredicate<T>()
private let errorBuilder: (T) -> E
/**
Returns a new `RequiredConstraint` instance.
```swift
enum Failure: Error {
case required
case invalidEmail
}
```
```swift
let constraint = RequiredConstraint<String, Failure>(error: .required)
let result = constraint.evaluate(with: "[email protected]")
```
- parameter error: An `Error` that describes why the evaluation has failed.
*/
public init(error: E) {
self.errorBuilder = { _ in return error }
}
/**
Returns a new `RequiredConstraint` instance.
```swift
enum Failure: Error {
case required
case invalidEmail
}
```
```swift
let constraint = RequiredConstraint<String, Failure> { _ in .required }
let result = constraint.evaluate(with: "[email protected]")
```
- parameter error: A generic closure that dynamically builds an `Error` to describe why the evaluation has failed.
*/
public init(errorBuilder: @escaping (T) -> E) {
self.errorBuilder = errorBuilder
}
/**
Returns a new `RequiredConstraint` instance.
```swift
enum Failure: Error {
case required
case invalidEmail
}
```
```swift
let constraint = RequiredConstraint<String, Failure> { .required }
let result = constraint.evaluate(with: "[email protected]")
```
- parameter error: A generic closure that dynamically builds an `Error` to describe why the evaluation has failed.
*/
public init(errorBuilder: @escaping () -> E) {
self.errorBuilder = { _ in return errorBuilder() }
}
/**
Evaluates whether the input collection is empty or not.
- parameter input: The input collection to be validated.
- returns: `.success` if the input is valid,`.failure` containing the `Summary` with the provided `Error`.
*/
public func evaluate(with input: T) -> Result<Void, Summary<E>> {
let result = predicate.evaluate(with: input)
if result {
return .success(())
}
let error = errorBuilder(input)
let summary = Summary(errors: [error])
return .failure(summary)
}
}
| 8e0fa587d4d79ec9d7d35e03e4faa71e | 26.196078 | 119 | 0.604182 | false | false | false | false |
danieldias25/SDCollectionView-Swift | refs/heads/master | Example/Example/SDPresentationView.swift | mit | 1 | //
// PresentationView.swift
// ScrollTest
//
// Created by Daniel Dias on 19/10/17.
// Copyright © 2017 Daniel.Dias. All rights reserved.
//
import UIKit
class SDPresentationView: UIView {
var imageView: UIImageView?
var blackView: UIView?
var x:CGFloat = 0.0
var y:CGFloat = 0.0
override init(frame:CGRect) {
super.init(frame:frame)
}
init(frame:CGRect ,AndImage image:UIImage, AndSize size: CGSize, AndScale scale: CGFloat){
self.blackView = UIView(frame: frame)
self.blackView?.backgroundColor = UIColor.black
self.blackView?.alpha = 0.0
self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
self.imageView?.transform = CGAffineTransform(scaleX: scale, y: scale)
self.x = (frame.size.width - (self.imageView?.frame.size.width)!)/2.0
self.y = (frame.size.height - (self.imageView?.frame.size.height)!)/2.0
let height = self.imageView?.frame.size.height
let width = self.imageView?.frame.size.width
self.imageView?.frame = CGRect(x: self.x, y: self.y, width: width!, height: height!)
self.imageView?.backgroundColor = UIColor.clear
self.imageView?.image = image
super.init(frame: frame)
self.backgroundColor = UIColor.clear
self.addSubview(self.blackView!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 0
}) { (true) in
self.removeFromSuperview()
}
}
func presentImage() {
let x = (frame.size.width - CGFloat(1))/2.0
let y = (frame.size.height - CGFloat(1))/2.0
let animateView = UIView(frame: CGRect(x: x, y: y, width: 1.00, height: 1.00))
animateView.backgroundColor = UIColor.white
animateView.alpha = 0.85
self.addSubview(animateView)
let horizontal = (self.imageView?.frame.size.width)! + CGFloat(5)
let vertical = (self.imageView?.frame.size.height)! + CGFloat(5)
UIView.animate(withDuration: 0.5, animations: {
animateView.transform = CGAffineTransform(scaleX: horizontal, y: 1)
}, completion: { (true) in
UIView.animate(withDuration: 0.5, animations: {
animateView.transform = CGAffineTransform(scaleX: horizontal, y: vertical)
}, completion: { (true) in
self.imageView?.alpha = 0
self.addSubview(self.imageView!)
UIView.animate(withDuration: 0.2, animations: {
self.imageView?.alpha = 1
}, completion: nil)
})
})
}
}
| 29482dd00f0316d618f1aab3db76b3de | 30.690722 | 103 | 0.56799 | false | false | false | false |
BradLarson/GPUImage2 | refs/heads/develop | GPUImage-Swift/examples/Linux-RPi/SimpleVideoFilter/Source/main.swift | apache-2.0 | 4 | import GPUImage
// For now, rendering requires the window to be created first
let renderWindow = RPiRenderWindow(width:1280, height:720)
let camera = V4LCamera(size:Size(width:1280.0, height:720.0))
let edgeDetection = SobelEdgeDetection()
camera --> edgeDetection --> renderWindow
var terminate:Int = 0
camera.startCapture()
while (terminate == 0) {
camera.grabFrame()
} | 5fcba08716f13b7f8d0f4acec74708ba | 24.133333 | 61 | 0.757979 | false | false | false | false |
quran/quran-ios | refs/heads/main | Tests/BatchDownloaderTests/DownloadingObserverCollectionTests.swift | apache-2.0 | 1 | //
// DownloadingObserverCollectionTests.swift
//
//
// Created by Mohamed Afifi on 2022-02-02.
//
@testable import BatchDownloader
import XCTest
class DownloadingObserverCollectionTests: XCTestCase {
private var observers: DownloadingObserverCollection<AudioDownload>!
private var recorder: DownloadObserversRecorder<AudioDownload>!
private let item1 = AudioDownload(name: "item1")
private let item2 = AudioDownload(name: "item2")
private let item3 = AudioDownload(name: "item3")
override func setUpWithError() throws {
observers = DownloadingObserverCollection()
recorder = DownloadObserversRecorder(observer: observers)
}
private func waitForProgressUpdates() {
// wait for the main thread dispatch async as completion is called on main thread
wait(for: DispatchQueue.main)
}
func testStartingDownloadCompletedSuccessfully() {
XCTAssertEqual(recorder.diffSinceLastCalled, [])
// prepare response
let response = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
response.progress.totalUnitCount = 1
// start downloading
observers.observe([item1, item2, item3], responses: [:])
observers.startDownloading(item: item2, response: response)
XCTAssertEqual(recorder.diffSinceLastCalled, [
.itemsUpdated([item1, item2, item3]),
.itemsUpdated([item1, item2, item3]),
])
waitForProgressUpdates()
// at the start, we get 0%
XCTAssertEqual(recorder.diffSinceLastCalled, [
.progress(item2, 1, 0),
])
response.progress.completedUnitCount = 0.5
response.progress.completedUnitCount = 1
waitForProgressUpdates()
// get 50% then 100%
XCTAssertEqual(recorder.diffSinceLastCalled, [
.progress(item2, 1, 0.5),
.progress(item2, 1, 1.0),
])
response.fulfill()
waitForProgressUpdates()
XCTAssertEqual(recorder.diffSinceLastCalled, [
.itemsUpdated([item1, item2, item3]),
.completed(item2, 1),
])
}
func testStartingDownloadFailedToComplete() {
// start downloading and immediately fail it
let response = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
response.progress.totalUnitCount = 1
observers.observe([item1, item2, item3], responses: [:])
observers.startDownloading(item: item3, response: response)
response.reject(FileSystemError(error: CocoaError(.fileWriteOutOfSpace)))
waitForProgressUpdates()
XCTAssertEqual(recorder.diffSinceLastCalled, [
.itemsUpdated([item1, item2, item3]),
.itemsUpdated([item1, item2, item3]),
.progress(item3, 2, 0),
// failed
.itemsUpdated([item1, item2, item3]),
.failed(item3, 2, FileSystemError.noDiskSpace as NSError),
])
}
func testObserveMethod() {
let response1 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
let response2 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
let response3 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
for response in [response1, response2, response3] {
response.progress.totalUnitCount = 1
}
observers.observe([item1, item2, item3], responses: [
item1: response1,
item2: response2,
item3: response3,
])
waitForProgressUpdates()
XCTAssertEqual(Set(recorder.diffSinceLastCalled), [
.itemsUpdated([item1, item2, item3]),
.progress(item1, 0, 0),
.progress(item2, 1, 0),
.progress(item3, 2, 0),
])
}
func testStopDownloading() {
let response = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
response.progress.totalUnitCount = 1
observers.observe([item1, item2, item3], responses: [item1: response])
observers.stopDownloading(item1)
observers.stopDownloading(item2)
waitForProgressUpdates()
XCTAssertEqual(recorder.diffSinceLastCalled, [
.itemsUpdated([item1, item2, item3]),
.cancel(response: response),
.itemsUpdated([item1, item2, item3]),
.itemsUpdated([item1, item2, item3]),
])
// if promise fulfilled, we don't get notified
response.fulfill()
waitForProgressUpdates()
XCTAssertTrue(recorder.diffSinceLastCalled.isEmpty)
}
func testStopDownloadingThenRedownloading() {
let response = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
response.progress.totalUnitCount = 1
observers.observe([item1, item2, item3], responses: [item1: response])
observers.stopDownloading(item1)
observers.preparingDownloading(item1)
observers.startDownloading(item: item1, response: response)
response.fulfill()
waitForProgressUpdates()
XCTAssertEqual(recorder.diffSinceLastCalled, [
.itemsUpdated([item1, item2, item3]),
.cancel(response: response),
.itemsUpdated([item1, item2, item3]),
.itemsUpdated([item1, item2, item3]),
.progress(item1, 0, 0),
// completed
.itemsUpdated([item1, item2, item3]),
.completed(item1, 0),
])
}
func testCantRestartDownloadImmediately() {
let response = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
response.progress.totalUnitCount = 1
observers.observe([item1, item2, item3], responses: [item1: response])
observers.stopDownloading(item1)
observers.startDownloading(item: item1, response: response)
waitForProgressUpdates()
XCTAssertEqual(recorder.diffSinceLastCalled, [
.itemsUpdated([item1, item2, item3]),
.cancel(response: response),
.itemsUpdated([item1, item2, item3]),
.cancel(response: response),
])
}
func testRemoveAllResponses() {
let response1 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
let response2 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
let response3 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil)
for response in [response1, response2, response3] {
response.progress.totalUnitCount = 1
}
observers.observe([item1, item2, item3], responses: [
item1: response1,
item2: response2,
item3: response3,
])
waitForProgressUpdates()
// start the diff now
_ = recorder.diffSinceLastCalled
observers.removeAll()
waitForProgressUpdates()
XCTAssertEqual(recorder.diffSinceLastCalled, [
.itemsUpdated([]),
])
response1.fulfill()
XCTAssertEqual(recorder.diffSinceLastCalled, [])
}
}
| 600fb6e7d7f9e63d98de24bcc6c0653b | 34.676617 | 91 | 0.631293 | false | true | false | false |
gssdromen/CedFilterView | refs/heads/master | FilterTest/Extension/FloatExtension.swift | gpl-3.0 | 1 | //
// FloatExtension.swift
// SecondHandHouseBroker
//
// Created by Cedric Wu on 3/3/16.
// Copyright © 2016 FangDuoDuo. All rights reserved.
//
import Foundation
extension Float {
func toString() -> String {
return String(self)
}
func toAreaFormat() -> String {
let dou = NSString(format: "%.2f", self)
let array = dou.components(separatedBy: ".")
if array.count == 2 {
if array[1] == "00" {
return array[0]
} else if array[1].hasSuffix("0") {
return dou.substring(to: dou.length - 1)
} else {
return dou as String
}
} else {
return ""
}
}
func toPriceFormat() -> String {
let dou = NSString(format: "%.2f", self)
let array = dou.components(separatedBy: ".")
if array.count == 2 {
if array[1] == "00" {
return array[0]
} else if array[1].hasSuffix("0") {
return dou.substring(to: dou.length - 1)
} else {
return dou as String
}
} else {
return ""
}
}
func toCountDownSecondFromat() -> String {
let dou = NSString(format: "%.1f", self)
return dou as String
}
}
| 70a6e8b48c7aa6c017b59d234a4768c2 | 23.981132 | 56 | 0.483384 | false | false | false | false |
alblue/swift | refs/heads/master | test/APINotes/versioned.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -print-regular-comments -swift-version 5 | %FileCheck -check-prefix=CHECK-SWIFT-5 %s
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -print-regular-comments -swift-version 4 | %FileCheck -check-prefix=CHECK-SWIFT-4 %s
// CHECK-SWIFT-5: func jumpTo(x: Double, y: Double, z: Double)
// CHECK-SWIFT-4: func jumpTo(x: Double, y: Double, z: Double)
// CHECK-SWIFT-5: func accept(_ ptr: UnsafeMutablePointer<Double>)
// CHECK-SWIFT-4: func acceptPointer(_ ptr: UnsafeMutablePointer<Double>?)
// CHECK-SWIFT-5: func normallyUnchanged()
// CHECK-SWIFT-5: @available(swift, obsoleted: 4.2, renamed: "normallyUnchanged()")
// CHECK-SWIFT-5-NEXT: func normallyUnchangedButChangedInSwift4()
// CHECK-SWIFT-4: @available(swift, obsoleted: 3, renamed: "normallyUnchangedButChangedInSwift4()")
// CHECK-SWIFT-4-NEXT: func normallyUnchanged()
// CHECK-SWIFT-4: func normallyUnchangedButChangedInSwift4()
// CHECK-SWIFT-5: func normallyChanged()
// CHECK-SWIFT-5-NEXT: @available(swift, obsoleted: 4.2, renamed: "normallyChanged()")
// CHECK-SWIFT-5-NEXT: func normallyChangedButSpecialInSwift4()
// CHECK-SWIFT-5-NEXT: @available(swift, obsoleted: 3, renamed: "normallyChanged()")
// CHECK-SWIFT-5-NEXT: func normallyChangedOriginal()
// CHECK-SWIFT-4: @available(swift, introduced: 4.2, renamed: "normallyChangedButSpecialInSwift4()")
// CHECK-SWIFT-4-NEXT: func normallyChanged()
// CHECK-SWIFT-4-NEXT: func normallyChangedButSpecialInSwift4()
// CHECK-SWIFT-4-NEXT: @available(swift, obsoleted: 3, renamed: "normallyChangedButSpecialInSwift4()")
// CHECK-SWIFT-4-NEXT: func normallyChangedOriginal()
// CHECK-SWIFT-5: @available(swift, obsoleted: 4.2, renamed: "NormallyUnchangedWrapper")
// CHECK-SWIFT-5-NEXT: typealias NormallyUnchangedButChangedInSwift4Wrapper = NormallyUnchangedWrapper
// CHECK-SWIFT-5: struct NormallyUnchangedWrapper {
// CHECK-SWIFT-4: typealias NormallyUnchangedButChangedInSwift4Wrapper = NormallyUnchangedWrapper
// CHECK-SWIFT-4-NEXT: struct NormallyUnchangedWrapper {
// CHECK-SWIFT-5: @available(swift, obsoleted: 4.2, renamed: "NormallyChangedWrapper")
// CHECK-SWIFT-5-NEXT: typealias NormallyChangedButSpecialInSwift4Wrapper = NormallyChangedWrapper
// CHECK-SWIFT-5: @available(swift, obsoleted: 3, renamed: "NormallyChangedWrapper")
// CHECK-SWIFT-5-NEXT: typealias NormallyChangedOriginalWrapper = NormallyChangedWrapper
// CHECK-SWIFT-5: struct NormallyChangedWrapper {
// CHECK-SWIFT-4: typealias NormallyChangedButSpecialInSwift4Wrapper = NormallyChangedWrapper
// CHECK-SWIFT-4-NEXT: @available(swift, obsoleted: 3, renamed: "NormallyChangedButSpecialInSwift4Wrapper")
// CHECK-SWIFT-4-NEXT: typealias NormallyChangedOriginalWrapper = NormallyChangedButSpecialInSwift4Wrapper
// CHECK-SWIFT-4-NEXT: struct NormallyChangedWrapper {
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 5 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-5 %s
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 4 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-4 %s
// RUN: %target-swift-frontend -emit-silgen -F %S/Inputs/custom-frameworks -swift-version 4 %s -DSILGEN 2>&1 | %FileCheck -check-prefix=CHECK-SILGEN -check-prefix=CHECK-SILGEN-4 %s
// RUN: %target-swift-frontend -emit-silgen -F %S/Inputs/custom-frameworks -swift-version 5 %s -DSILGEN 2>&1 | %FileCheck -check-prefix=CHECK-SILGEN -check-prefix=CHECK-SILGEN-5 %s
import APINotesFrameworkTest
#if !SILGEN
func testRenamedTopLevelDiags() {
var value = 0.0
// CHECK-DIAGS-5-NOT: versioned.swift:[[@LINE+1]]:
accept(&value)
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:3: error: 'accept' has been renamed to 'acceptPointer(_:)'
// CHECK-DIAGS-4: note: 'accept' was introduced in Swift 4.2
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]:
acceptPointer(&value)
// CHECK-DIAGS-5: versioned.swift:[[@LINE-1]]:3: error: 'acceptPointer' has been renamed to 'accept(_:)'
// CHECK-DIAGS-5: note: 'acceptPointer' was obsoleted in Swift 4.2
acceptDoublePointer(&value)
// CHECK-DIAGS: versioned.swift:[[@LINE-1]]:3: error: 'acceptDoublePointer' has been renamed to
// CHECK-DIAGS-5-SAME: 'accept(_:)'
// CHECK-DIAGS-4-SAME: 'acceptPointer(_:)'
// CHECK-DIAGS: note: 'acceptDoublePointer' was obsoleted in Swift 3
oldAcceptDoublePointer(&value)
// CHECK-DIAGS: versioned.swift:[[@LINE-1]]:3: error: 'oldAcceptDoublePointer' has been renamed to
// CHECK-DIAGS-5-SAME: 'accept(_:)'
// CHECK-DIAGS-4-SAME: 'acceptPointer(_:)'
// CHECK-DIAGS: note: 'oldAcceptDoublePointer' has been explicitly marked unavailable here
_ = SomeCStruct()
// CHECK-DIAGS: versioned.swift:[[@LINE-1]]:7: error: 'SomeCStruct' has been renamed to
// CHECK-DIAGS-5-SAME: 'VeryImportantCStruct'
// CHECK-DIAGS-4-SAME: 'ImportantCStruct'
// CHECK-DIAGS: note: 'SomeCStruct' was obsoleted in Swift 3
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]:
_ = ImportantCStruct()
// CHECK-DIAGS-5: versioned.swift:[[@LINE-1]]:7: error: 'ImportantCStruct' has been renamed to 'VeryImportantCStruct'
// CHECK-DIAGS-5: note: 'ImportantCStruct' was obsoleted in Swift 4.2
// CHECK-DIAGS-5-NOT: versioned.swift:[[@LINE+1]]:
_ = VeryImportantCStruct()
// CHECK-DIAGS-4-NOTE: versioned.swift:[[@LINE-1]]:
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]:
let s = InnerInSwift5()
// CHECK-DIAGS-5: versioned.swift:[[@LINE-1]]:11: error: 'InnerInSwift5' has been renamed to 'Outer.Inner'
// CHECK-DIAGS-5: note: 'InnerInSwift5' was obsoleted in Swift 4.2
_ = s.value
// CHECK-DIAGS-5-NOT: versioned.swift:[[@LINE-1]]:
// CHECK-DIAGS-5-NOT: versioned.swift:[[@LINE+1]]:
let t = Outer.Inner()
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE-1]]:
_ = s.value
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE-1]]:
}
func testAKA(structValue: ImportantCStruct, aliasValue: ImportantCAlias) {
let _: Int = structValue
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'ImportantCStruct' to specified type 'Int'
let _: Int = aliasValue
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'ImportantCAlias' (aka 'Int32') to specified type 'Int'
let optStructValue: Optional = structValue
let _: Int = optStructValue
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'ImportantCStruct?' to specified type 'Int'
let optAliasValue: Optional = aliasValue
let _: Int = optAliasValue
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'ImportantCAlias?' (aka 'Optional<Int32>') to specified type 'Int'
}
func testRenamedEnumConstants() {
_ = AnonymousEnumValue // okay
// CHECK-DIAGS-5: [[@LINE+1]]:7: error: 'AnonymousEnumRenamed' has been renamed to 'AnonymousEnumRenamedSwiftUnversioned'
_ = AnonymousEnumRenamed
// CHECK-DIAGS-4: [[@LINE-1]]:7: error: 'AnonymousEnumRenamed' has been renamed to 'AnonymousEnumRenamedSwift4'
// CHECK-DIAGS-5-NOT: :[[@LINE+1]]:7:
_ = AnonymousEnumRenamedSwiftUnversioned
// CHECK-DIAGS-4: [[@LINE-1]]:7: error: 'AnonymousEnumRenamedSwiftUnversioned' has been renamed to 'AnonymousEnumRenamedSwift4'
// CHECK-DIAGS-5: [[@LINE+1]]:7: error: 'AnonymousEnumRenamedSwift4' has been renamed to 'AnonymousEnumRenamedSwiftUnversioned'
_ = AnonymousEnumRenamedSwift4
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:7:
}
func testRenamedUnknownEnum() {
_ = UnknownEnumValue // okay
// CHECK-DIAGS-5: [[@LINE+1]]:7: error: 'UnknownEnumRenamed' has been renamed to 'UnknownEnumRenamedSwiftUnversioned'
_ = UnknownEnumRenamed
// CHECK-DIAGS-4: [[@LINE-1]]:7: error: 'UnknownEnumRenamed' has been renamed to 'UnknownEnumRenamedSwift4'
// CHECK-DIAGS-5-NOT: :[[@LINE+1]]:7:
_ = UnknownEnumRenamedSwiftUnversioned
// CHECK-DIAGS-4: [[@LINE-1]]:7: error: 'UnknownEnumRenamedSwiftUnversioned' has been renamed to 'UnknownEnumRenamedSwift4'
// CHECK-DIAGS-5: [[@LINE+1]]:7: error: 'UnknownEnumRenamedSwift4' has been renamed to 'UnknownEnumRenamedSwiftUnversioned'
_ = UnknownEnumRenamedSwift4
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:7:
}
func testRenamedTrueEnum() {
// CHECK-DIAGS: [[@LINE+1]]:7: error: use of unresolved identifier 'TrueEnumValue'
_ = TrueEnumValue
// CHECK-DIAGS: [[@LINE+1]]:7: error: type 'TrueEnum' has no member 'TrueEnumValue'
_ = TrueEnum.TrueEnumValue
// CHECK-DIAGS: [[@LINE+1]]:16: error: 'Value' has been renamed to 'value'
_ = TrueEnum.Value
_ = TrueEnum.value // okay
// CHECK-DIAGS: [[@LINE+1]]:7: error: use of unresolved identifier 'TrueEnumRenamed'
_ = TrueEnumRenamed
// CHECK-DIAGS: [[@LINE+1]]:7: error: type 'TrueEnum' has no member 'TrueEnumRenamed'
_ = TrueEnum.TrueEnumRenamed
// CHECK-DIAGS-5: [[@LINE+1]]:16: error: 'Renamed' has been renamed to 'renamedSwiftUnversioned'
_ = TrueEnum.Renamed
// CHECK-DIAGS-4: [[@LINE-1]]:16: error: 'Renamed' has been renamed to 'renamedSwift4'
// CHECK-DIAGS: [[@LINE+1]]:7: error: type 'TrueEnum' has no member 'renamed'
_ = TrueEnum.renamed
// CHECK-DIAGS-5-NOT: :[[@LINE+1]]:16:
_ = TrueEnum.renamedSwiftUnversioned
// CHECK-DIAGS-4: [[@LINE-1]]:16: error: 'renamedSwiftUnversioned' has been renamed to 'renamedSwift4'
// CHECK-DIAGS-5: [[@LINE+1]]:16: error: 'renamedSwift4' has been renamed to 'renamedSwiftUnversioned'
_ = TrueEnum.renamedSwift4
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:16:
// CHECK-DIAGS: [[@LINE+1]]:7: error: use of unresolved identifier 'TrueEnumAliasRenamed'
_ = TrueEnumAliasRenamed
// CHECK-DIAGS: [[@LINE+1]]:7: error: type 'TrueEnum' has no member 'TrueEnumAliasRenamed'
_ = TrueEnum.TrueEnumAliasRenamed
// CHECK-DIAGS-5: [[@LINE+1]]:16: error: 'AliasRenamed' has been renamed to 'aliasRenamedSwiftUnversioned'
_ = TrueEnum.AliasRenamed
// CHECK-DIAGS-4: [[@LINE-1]]:16: error: 'AliasRenamed' has been renamed to 'aliasRenamedSwift4'
// CHECK-DIAGS: [[@LINE+1]]:7: error: type 'TrueEnum' has no member 'aliasRenamed'
_ = TrueEnum.aliasRenamed
// CHECK-DIAGS-5-NOT: :[[@LINE+1]]:16:
_ = TrueEnum.aliasRenamedSwiftUnversioned
// CHECK-DIAGS-4: [[@LINE-1]]:16: error: 'aliasRenamedSwiftUnversioned' has been renamed to 'aliasRenamedSwift4'
// CHECK-DIAGS-5: [[@LINE+1]]:16: error: 'aliasRenamedSwift4' has been renamed to 'aliasRenamedSwiftUnversioned'
_ = TrueEnum.aliasRenamedSwift4
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:16:
}
func testRenamedOptionyEnum() {
// CHECK-DIAGS: [[@LINE+1]]:7: error: use of unresolved identifier 'OptionyEnumValue'
_ = OptionyEnumValue
// CHECK-DIAGS: [[@LINE+1]]:7: error: type 'OptionyEnum' has no member 'OptionyEnumValue'
_ = OptionyEnum.OptionyEnumValue
// CHECK-DIAGS: [[@LINE+1]]:19: error: 'Value' has been renamed to 'value'
_ = OptionyEnum.Value
_ = OptionyEnum.value // okay
// CHECK-DIAGS: [[@LINE+1]]:7: error: use of unresolved identifier 'OptionyEnumRenamed'
_ = OptionyEnumRenamed
// CHECK-DIAGS: [[@LINE+1]]:7: error: type 'OptionyEnum' has no member 'OptionyEnumRenamed'
_ = OptionyEnum.OptionyEnumRenamed
// CHECK-DIAGS-5: [[@LINE+1]]:19: error: 'Renamed' has been renamed to 'renamedSwiftUnversioned'
_ = OptionyEnum.Renamed
// CHECK-DIAGS-4: [[@LINE-1]]:19: error: 'Renamed' has been renamed to 'renamedSwift4'
// CHECK-DIAGS: [[@LINE+1]]:7: error: type 'OptionyEnum' has no member 'renamed'
_ = OptionyEnum.renamed
// CHECK-DIAGS-5-NOT: :[[@LINE+1]]:19:
_ = OptionyEnum.renamedSwiftUnversioned
// CHECK-DIAGS-4: [[@LINE-1]]:19: error: 'renamedSwiftUnversioned' has been renamed to 'renamedSwift4'
// CHECK-DIAGS-5: [[@LINE+1]]:19: error: 'renamedSwift4' has been renamed to 'renamedSwiftUnversioned'
_ = OptionyEnum.renamedSwift4
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:19:
}
#endif
#if !swift(>=5)
func useSwift4Name(_: ImportantCStruct) {}
// CHECK-SILGEN-4: sil hidden @$s9versioned13useSwift4NameyySo11SomeCStructVF
func useNewlyNested(_: InnerInSwift5) {}
// CHECK-SILGEN-4: sil hidden @$s9versioned14useNewlyNestedyySo13InnerInSwift5VF
#endif
func useSwift5Name(_: VeryImportantCStruct) {}
// CHECK-SILGEN: sil hidden @$s9versioned13useSwift5NameyySo11SomeCStructVF
#if swift(>=5)
func testSwiftWrapperInSwift5() {
_ = EnclosingStruct.Identifier.member
let _: EnclosingStruct.Identifier = .member
}
#else
func testSwiftWrapperInSwift4() {
_ = EnclosingStruct.Identifier.member
let _: EnclosingStruct.Identifier = .member
}
#endif
| c5434b748cf5e23519e46885b46f4f42 | 45.394928 | 248 | 0.720031 | false | false | false | false |
PodRepo/firefox-ios | refs/heads/master | Client/Frontend/Browser/BrowserScrollController.swift | mpl-2.0 | 3 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
private let ToolbarBaseAnimationDuration: CGFloat = 0.2
class BrowserScrollingController: NSObject {
enum ScrollDirection {
case Up
case Down
}
enum ToolbarState {
case Collapsed
case Visible
case Animating
}
weak var browser: Browser? {
willSet {
self.scrollView?.delegate = nil
self.scrollView?.removeGestureRecognizer(panGesture)
}
didSet {
self.scrollView?.addGestureRecognizer(panGesture)
scrollView?.delegate = self
}
}
weak var header: UIView?
weak var footer: UIView?
weak var urlBar: URLBarView?
weak var snackBars: UIView?
var footerBottomConstraint: Constraint?
var headerTopConstraint: Constraint?
var toolbarsShowing: Bool { return headerTopOffset == 0 }
private var headerTopOffset: CGFloat = 0 {
didSet {
headerTopConstraint?.updateOffset(headerTopOffset)
header?.superview?.setNeedsLayout()
}
}
private var footerBottomOffset: CGFloat = 0 {
didSet {
footerBottomConstraint?.updateOffset(footerBottomOffset)
footer?.superview?.setNeedsLayout()
}
}
private lazy var panGesture: UIPanGestureRecognizer = {
let panGesture = UIPanGestureRecognizer(target: self, action: "handlePan:")
panGesture.maximumNumberOfTouches = 1
panGesture.delegate = self
return panGesture
}()
private var scrollView: UIScrollView? { return browser?.webView?.scrollView }
private var contentOffset: CGPoint { return scrollView?.contentOffset ?? CGPointZero }
private var contentSize: CGSize { return scrollView?.contentSize ?? CGSizeZero }
private var scrollViewHeight: CGFloat { return scrollView?.frame.height ?? 0 }
private var headerFrame: CGRect { return header?.frame ?? CGRectZero }
private var footerFrame: CGRect { return footer?.frame ?? CGRectZero }
private var snackBarsFrame: CGRect { return snackBars?.frame ?? CGRectZero }
private var lastContentOffset: CGFloat = 0
private var scrollDirection: ScrollDirection = .Down
private var toolbarState: ToolbarState = .Visible
override init() {
super.init()
}
func showToolbars(animated animated: Bool, completion: ((finished: Bool) -> Void)? = nil) {
toolbarState = .Visible
let durationRatio = abs(headerTopOffset / headerFrame.height)
let actualDuration = NSTimeInterval(ToolbarBaseAnimationDuration * durationRatio)
self.animateToolbarsWithOffsets(
animated: animated,
duration: actualDuration,
headerOffset: 0,
footerOffset: 0,
alpha: 1,
completion: completion)
}
func hideToolbars(animated animated: Bool, completion: ((finished: Bool) -> Void)? = nil) {
toolbarState = .Collapsed
let durationRatio = abs((headerFrame.height + headerTopOffset) / headerFrame.height)
let actualDuration = NSTimeInterval(ToolbarBaseAnimationDuration * durationRatio)
self.animateToolbarsWithOffsets(
animated: animated,
duration: actualDuration,
headerOffset: -headerFrame.height,
footerOffset: footerFrame.height - snackBarsFrame.height,
alpha: 0,
completion: completion)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "contentSize" {
if !checkScrollHeightIsLargeEnoughForScrolling() && !toolbarsShowing {
showToolbars(animated: true, completion: nil)
}
}
}
}
private extension BrowserScrollingController {
func browserIsLoading() -> Bool {
return browser?.loading ?? true
}
@objc func handlePan(gesture: UIPanGestureRecognizer) {
if browserIsLoading() {
return
}
if let containerView = scrollView?.superview {
let translation = gesture.translationInView(containerView)
let delta = lastContentOffset - translation.y
if delta > 0 {
scrollDirection = .Down
} else if delta < 0 {
scrollDirection = .Up
}
lastContentOffset = translation.y
if checkRubberbandingForDelta(delta) && checkScrollHeightIsLargeEnoughForScrolling() {
if toolbarState != .Collapsed || contentOffset.y <= 0 {
scrollWithDelta(delta)
}
if headerTopOffset == -headerFrame.height {
toolbarState = .Collapsed
} else if headerTopOffset == 0 {
toolbarState = .Visible
} else {
toolbarState = .Animating
}
}
if gesture.state == .Ended || gesture.state == .Cancelled {
lastContentOffset = 0
}
}
}
func checkRubberbandingForDelta(delta: CGFloat) -> Bool {
return !((delta < 0 && contentOffset.y + scrollViewHeight > contentSize.height &&
scrollViewHeight < contentSize.height) ||
contentOffset.y < delta)
}
func scrollWithDelta(delta: CGFloat) {
if scrollViewHeight >= contentSize.height {
return
}
var updatedOffset = headerTopOffset - delta
headerTopOffset = clamp(updatedOffset, min: -headerFrame.height, max: 0)
if isHeaderDisplayedForGivenOffset(updatedOffset) {
scrollView?.contentOffset = CGPoint(x: contentOffset.x, y: contentOffset.y - delta)
}
updatedOffset = footerBottomOffset + delta
footerBottomOffset = clamp(updatedOffset, min: 0, max: footerFrame.height - snackBarsFrame.height)
let alpha = 1 - abs(headerTopOffset / headerFrame.height)
urlBar?.updateAlphaForSubviews(alpha)
}
func isHeaderDisplayedForGivenOffset(offset: CGFloat) -> Bool {
return offset > -headerFrame.height && offset < 0
}
func clamp(y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
if y >= max {
return max
} else if y <= min {
return min
}
return y
}
func animateToolbarsWithOffsets(animated animated: Bool, duration: NSTimeInterval, headerOffset: CGFloat,
footerOffset: CGFloat, alpha: CGFloat, completion: ((finished: Bool) -> Void)?) {
let animation: () -> Void = {
self.headerTopOffset = headerOffset
self.footerBottomOffset = footerOffset
self.urlBar?.updateAlphaForSubviews(alpha)
self.header?.superview?.layoutIfNeeded()
}
if animated {
UIView.animateWithDuration(duration, animations: animation, completion: completion)
} else {
animation()
completion?(finished: true)
}
}
func checkScrollHeightIsLargeEnoughForScrolling() -> Bool {
return (UIScreen.mainScreen().bounds.size.height + 2 * UIConstants.ToolbarHeight) < scrollView?.contentSize.height
}
}
extension BrowserScrollingController: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension BrowserScrollingController: UIScrollViewDelegate {
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if browserIsLoading() {
return
}
if (decelerate || (toolbarState == .Animating && !decelerate)) && checkScrollHeightIsLargeEnoughForScrolling() {
if scrollDirection == .Up {
showToolbars(animated: true)
} else if scrollDirection == .Down {
hideToolbars(animated: true)
}
}
}
func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool {
showToolbars(animated: true)
return true
}
}
| ac32b00ac9abcb1b79316668fefae1d1 | 33.966942 | 157 | 0.63082 | false | false | false | false |
xedin/swift | refs/heads/master | test/Sema/diag_use_before_declaration.swift | apache-2.0 | 1 | // XFAIL: enable-astscope-lookup
// RUN: %target-typecheck-verify-swift
// SR-5163
func sr5163() {
func foo(_ x: Int) -> Int? { return 1 }
func fn() {
let a = foo(c) // expected-error {{use of local variable 'c' before its declaration}}
guard let b = a else { return }
let c = b // expected-note {{'c' declared here}}
}
}
// SR-6726
var foo: Int?
func test() {
guard let bar = foo else {
return
}
let foo = String(bar) // expected-warning {{initialization of immutable value 'foo' was never used; consider replacing with assignment to '_' or removing it}}
}
// SR-7660
class C {
var variable: Int?
func f() {
guard let _ = variable else { return }
let variable = 1 // expected-warning {{initialization of immutable value 'variable' was never used; consider replacing with assignment to '_' or removing it}}
}
}
// SR-7517
func testExample() {
let app = app2 // expected-error {{use of local variable 'app2' before its declaration}}
let app2 = app // expected-note {{'app2' declared here}}
}
// SR-8447
func test_circular() {
let obj = sr8447 // expected-error {{use of local variable 'sr8447' before its declaration}}
let _ = obj.prop, sr8447 // expected-note {{'sr8447' declared here}} expected-error {{type annotation missing in pattern}}
}
//===----------------------------------------------------------------------===//
// Nested scope
//===----------------------------------------------------------------------===//
func nested_scope_1() {
do {
do {
let _ = x // expected-error {{use of local variable 'x' before its declaration}}
let x = 111 // expected-note {{'x' declared here}}
}
let x = 11
}
let x = 1
}
func nested_scope_2() {
do {
let x = 11
do {
let _ = x
let x = 111 // expected-warning {{initialization of immutable value 'x' was never used; consider replacing with assignment to '_' or removing it}}
}
}
let x = 1 // expected-warning {{initialization of immutable value 'x' was never used; consider replacing with assignment to '_' or removing it}}
}
func nested_scope_3() {
let x = 1
do {
do {
let _ = x
let x = 111 // expected-warning {{initialization of immutable value 'x' was never used; consider replacing with assignment to '_' or removing it}}
}
let x = 11 // expected-warning {{initialization of immutable value 'x' was never used; consider replacing with assignment to '_' or removing it}}
}
}
//===----------------------------------------------------------------------===//
// Type scope
//===----------------------------------------------------------------------===//
class Ty {
var v : Int?
func fn() {
let _ = v
let v = 1 // expected-warning {{initialization of immutable value 'v' was never used; consider replacing with assignment to '_' or removing it}}
}
}
//===----------------------------------------------------------------------===//
// File scope
//===----------------------------------------------------------------------===//
let g = 0
func file_scope_1() {
let _ = g
let g = 1 // expected-warning {{initialization of immutable value 'g' was never used; consider replacing with assignment to '_' or removing it}}
}
func file_scope_2() {
let _ = gg // expected-error {{use of local variable 'gg' before its declaration}}
let gg = 1 // expected-note {{'gg' declared here}}
}
//===----------------------------------------------------------------------===//
// Module scope
//===----------------------------------------------------------------------===//
func module_scope_1() {
let _ = print // Legal use of func print declared in Swift Standard Library
let print = "something" // expected-warning {{initialization of immutable value 'print' was never used; consider replacing with assignment to '_' or removing it}}
}
func module_scope_2() {
let _ = another_print // expected-error {{use of local variable 'another_print' before its declaration}}
let another_print = "something" // expected-note {{'another_print' declared here}}
}
| bfece7499236ecf51e4f52fdca6f69f5 | 31.782258 | 164 | 0.548585 | false | false | false | false |
TheBudgeteers/CartTrackr | refs/heads/master | CartTrackr/CartTrackr/Item.swift | mit | 1 | //
// Item.swift
// CartTrackr
//
// Created by Christina Lee on 4/10/17.
// Copyright © 2017 Christina Lee. All rights reserved.
//
import Foundation
class Item {
var price : String
var originalPrice : Float
var cost : Float
var description : String
var quantity : String {
didSet {
self.cost = (self.originalPrice * Float(self.quantity)!)
}
}
init(price: String, description: String, quantity: String) {
self.price = price
self.originalPrice = Float(price)!
self.cost = (Float(price)! * Float(quantity)!)
self.description = description
self.quantity = quantity
}
}
//MARK: Format extension
extension String {
func format() -> String {
return String(format: "%.2f" , self)
}
}
| 2a3d018f79336b9435347aa21b09efbb | 20.051282 | 68 | 0.589525 | false | false | false | false |
0Mooshroom/Learning-Swift | refs/heads/master | 7_闭包.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
//: 闭包表达式
let names = ["Chris","Alex","Ewa","Barry","Daniella"]
// >>>>> 1
func backward(_ s1: String, _ s2: String) -> Bool{
return s1 > s2
}
var reverseNames_1 = names.sorted(by: backward)
// >>>>> 2
var reverseNames_2 = names.sorted { (s1: String, s2: String) -> Bool in
return s1 > s2
}
// >>>>> 3
var reverseNames_3 = names.sorted(by: { s1, s2 in return s1 > s2 })
// >>>>> 4
var reveseNames_4 = names.sorted(by: { s1, s2 in s1 > s2 })
// >>>>> 5
var reverseNames_5 = names.sorted(by: { $0 > $1 })
// >>>>> 6
var reverseNames_6 = names.sorted(by: >)
//: 尾随闭包
// 尾随闭包是一个被书写在函数形式参数的括号外面(后面)的闭包表达式
func fetchMooshroomName(closure:() -> Void) {
closure()
}
fetchMooshroomName(closure: {
})
var reverseNames_7 = names.sorted() { $0 > $1 }
var reverseNames_8 = names.sorted { $0 > $1 }
let digitNames = [
0: "Zero",1: "One",2: "Two", 3: "Three",4: "Four",
5: "Five",6: "Six",7: "Seven",8: "Eight",9: "Nine"
]
let numbers = [16,58,510]
let strings = numbers.map {
(number) -> String in
var number = number
var output = ""
repeat {
output = digitNames[number % 10]! + output
number /= 10
} while number > 0
return output
}
strings
//: 捕获值
struct CatchValue {
static func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
}
let incrementByTen = CatchValue.makeIncrementer(forIncrement: 10)
print(incrementByTen())
print(incrementByTen())
print(incrementByTen())
print(incrementByTen())
//: 闭包是引用类型
//
//: 逃逸闭包
// 非逃逸: 我们平时使用的Masonry 和 Snapkit的添加约束的方法是非逃逸的。因为闭包马上就执行了。
// 逃逸: 网络请求结束后的回调闭包则是逃逸的,因为发起请求后过了一段时间后这个闭包才执行。
//: 自动闭包 | 21efacd9165ee4605189650182c7039b | 19.666667 | 72 | 0.610005 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | refs/heads/master | Source/StackPaginationManipulator.swift | apache-2.0 | 3 | //
// StackPaginationManipulator.swift
// edX
//
// Created by Akiva Leffert on 4/28/16.
// Copyright © 2016 edX. All rights reserved.
//
// Use with PaginationController to set up a paginating stack view
// Before using this, *STRONGLY* consider if you can accomplish what you're
// doing with a scroll view. Stackviews do not scale to lots of items
public class StackPaginationManipulator: ScrollingPaginationViewManipulator {
let scrollView: UIScrollView?
private let stackView: TZStackView
init(stackView : TZStackView, containingScrollView scrollView: UIScrollView) {
self.scrollView = scrollView
self.stackView = stackView
}
func setFooter(footer: UIView, visible: Bool) {
if(visible && !self.stackView.arrangedSubviews.contains(footer)) {
self.stackView.addArrangedSubview(footer)
}
else if(!visible && self.stackView.arrangedSubviews.contains(footer)) {
self.stackView.removeArrangedSubview(footer)
footer.removeFromSuperview()
}
}
var canPaginate: Bool {
return self.stackView.window != nil
}
}
extension PaginationController {
convenience init<P: Paginator where P.Element == A>(paginator: P, stackView: TZStackView, containingScrollView: UIScrollView) {
self.init(paginator: paginator, manipulator: StackPaginationManipulator(stackView: stackView, containingScrollView: containingScrollView))
}
} | 08d223ed0b880cd3915066bc7b8925ba | 31.577778 | 146 | 0.71058 | false | false | false | false |
MHaroonBaig/Swift-Beautify | refs/heads/master | Picker/SideBarTableViewController.swift | apache-2.0 | 2 | //
// SideBarTableViewController.swift
// BlurrySideBar
//
// Created by Training on 01/09/14.
// Copyright (c) 2014 Training. All rights reserved.
//
import UIKit
protocol SideBarTableViewControllerDelegate{
func sideBarControlDidSelectRow(indexPath:NSIndexPath)
}
class SideBarTableViewController: UITableViewController {
var delegate:SideBarTableViewControllerDelegate?
var tableData:Array<String> = []
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
// Configure the cell...
cell!.backgroundColor = UIColor.clearColor()
cell!.textLabel.textColor = UIColor.darkTextColor()
let selectedView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
selectedView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
cell!.selectedBackgroundView = selectedView
}
cell!.textLabel.text = tableData[indexPath.row]
var value = tableData[indexPath.row]
switch (value){
case "Turquoise":
cell!.backgroundColor = UIColor(red: 0.102, green: 0.737, blue: 0.612, alpha: 1.0)
break
case "Greensea":
cell!.backgroundColor = UIColor(red:0.086, green:0.627, blue:0.522, alpha:1)
break
case "Emerland":
cell!.backgroundColor = colorWithHexString("2ecc71")
break
case "Nephritis":
cell!.backgroundColor = colorWithHexString("27ae60")
break
case "Peterriver":
cell!.backgroundColor = colorWithHexString("3498db")
break
case "Belizehole":
cell!.backgroundColor = colorWithHexString("2980b9")
break
case "Amethyst":
cell!.backgroundColor = colorWithHexString("9b59b6")
break
case "Wisteria":
cell!.backgroundColor = colorWithHexString("8e44ad")
break
case "Wetasphalt":
cell!.backgroundColor = colorWithHexString("34495e")
break
case "Midnightblue":
cell!.backgroundColor = colorWithHexString("2c3e50")
break
case "Sunflower":
cell!.backgroundColor = colorWithHexString("f1c40f")
break
case "Orange":
cell!.backgroundColor = colorWithHexString("f39c12")
break
case "Carrot":
cell!.backgroundColor = colorWithHexString("e67e22")
break
case "Pumpkin":
cell!.backgroundColor = colorWithHexString("d35400")
break
case "Alizarin":
cell!.backgroundColor = colorWithHexString("e74c3c")
break
case "Pomegranate":
cell!.backgroundColor = colorWithHexString("c0392b")
break
case "Clouds":
cell!.backgroundColor = colorWithHexString("ecf0f1")
break
case "Silver":
cell!.backgroundColor = colorWithHexString("bdc3c7")
break
case "Concrete":
cell!.backgroundColor = colorWithHexString("95a5a6")
break
case "Asbestos":
cell!.backgroundColor = colorWithHexString("7f8c8d")
break
case "Wistful":
cell!.backgroundColor = colorWithHexString("AEA8D3")
break
case "Snuff":
cell!.backgroundColor = colorWithHexString("DCC6E0")
break
default:
cell!.backgroundColor = UIColor.clearColor()
break
}
return cell!
}
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (countElements(cString) != 6) {
return UIColor.grayColor()
}
var rString = (cString as NSString).substringToIndex(2)
var gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
var bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 65.0
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.sideBarControlDidSelectRow(indexPath)
}
}
| 021915062d452ce5724fb72a13832539 | 34.209877 | 135 | 0.604137 | false | false | false | false |
huangboju/GesturePassword | refs/heads/master | GesturePassword/Classes/LockAdapter.swift | mit | 1 | //
// LockMediator.swift
// GesturePassword
//
// Created by 黄伯驹 on 2018/5/5.
// Copyright © 2018 xiAo_Ju. All rights reserved.
//
public protocol LockViewPresentable: class {
var lockMainView: LockView { get }
}
public protocol SetPatternDelegate: LockViewPresentable {
var password: String { set get }
func firstDrawedState()
func tooShortState()
func mismatchState()
func successState()
}
protocol VerifyPatternDelegate: LockViewPresentable {
func successState()
func errorState(_ remainTimes: Int)
func overTimesState()
}
struct LockAdapter {}
/// SetPatternDelegate
extension LockAdapter {
static func setPattern(with controller: SetPatternDelegate) {
let password = controller.lockMainView.password
if password.count < LockCenter.passwordMinCount {
controller.tooShortState()
return
}
if controller.password.isEmpty {
controller.password = password
controller.firstDrawedState()
return
}
guard controller.password == password else {
controller.mismatchState()
return
}
controller.successState()
}
static func reset(with controller: SetPatternDelegate) {
controller.lockMainView.reset()
controller.password = ""
}
}
/// VerifyPatternDelegate
extension LockAdapter {
static func verifyPattern(with controller: VerifyPatternDelegate) {
let inputPassword = controller.lockMainView.password
let localPassword = LockCenter.password()
if inputPassword == localPassword {
// 成功了删除一些之前的错误
LockCenter.removeErrorTimes()
controller.successState()
return
}
var errorTimes = LockCenter.errorTimes()
errorTimes -= 1
LockCenter.setErrorTimes(errorTimes)
guard errorTimes == 0 else {
controller.errorState(errorTimes)
return
}
controller.overTimesState()
}
}
| 0f952c5591902fe2c4f24a9d084228ec | 23.626506 | 71 | 0.644325 | false | false | false | false |
google/swift-structural | refs/heads/main | Sources/StructuralExamples/StudentGrade.swift | apache-2.0 | 1 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import StructuralCore
public struct StudentGrades {
let classId: Int
var grades: [Double]
public init(classId: Int, grades: [Double]) {
self.classId = classId
self.grades = grades
}
}
extension StudentGrades: Structural {
public typealias StructuralRepresentation = StructuralStruct<
StructuralCons<
StructuralProperty<Int>,
StructuralCons<
StructuralProperty<[Double]>,
StructuralEmpty
>
>
>
public var structuralRepresentation: StructuralRepresentation {
get {
return StructuralStruct(
StudentGrades.self,
StructuralCons(
StructuralProperty("classId", classId, isMutable: false),
StructuralCons(
StructuralProperty("grades", grades, isMutable: true),
StructuralEmpty())))
}
_modify {
var av = StructuralStruct(
StudentGrades.self,
StructuralCons(
StructuralProperty("classId", classId, isMutable: false),
StructuralCons(
StructuralProperty("grades", grades, isMutable: true),
StructuralEmpty())))
// Use swap to avoid copies.
grades = []
defer { swap(&av.body.next.value.value, &grades) }
yield &av
}
}
public init(structuralRepresentation: StructuralRepresentation) {
self.classId = structuralRepresentation.body.value.value
self.grades = structuralRepresentation.body.next.value.value
}
}
extension StudentGrades: MyEquatable {}
extension StudentGrades: MyHashable {}
extension StudentGrades: MyDebugString {}
| c08fecd351fe01519e28d84ea008e42a | 31.594595 | 78 | 0.616086 | false | false | false | false |
Yurssoft/QuickFile | refs/heads/master | QuickFile/Additional_Classes/YSTabBarController.swift | mit | 1 | //
// YSTabBarController.swift
// YSGGP
//
// Created by Yurii Boiko on 10/21/16.
// Copyright © 2016 Yurii Boiko. All rights reserved.
//
import UIKit
class YSTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
var driveTopViewController: YSDriveTopViewController? = nil
for navigationVC in childViewControllers {
for topVC in navigationVC.childViewControllers {
if let drTopVC = topVC as? YSDriveTopViewController {
driveTopViewController = drTopVC
}
}
}
let coordinator = YSDriveTopCoordinator()
YSAppDelegate.appDelegate().driveTopCoordinator = coordinator
coordinator.start(driveTopVC: driveTopViewController!)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
YSAppDelegate.appDelegate().playerCoordinator.start(tabBarController: self)
}
}
| 826c1eaaea63935caa695de3dd6f7728 | 30.741935 | 83 | 0.66565 | false | false | false | false |
feialoh/FFImageDrawingTool | refs/heads/master | FFImageDrawingTool/MainViewController.swift | mit | 1 | //
// MainViewController.swift
// FFImageDrawingTool
//
// Created by feialoh on 31/03/16.
// Copyright © 2016 Feialoh Francis. All rights reserved.
//
import UIKit
class MainViewController: UIViewController,ImageSelectorDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIScrollViewDelegate {
@IBOutlet weak var selectedImage: UIImageView!
@IBOutlet weak var imageContainerScrollView: UIScrollView!
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
imagePicker.allowsEditing = false
imageContainerScrollView.minimumZoomScale = 1.0
imageContainerScrollView.maximumZoomScale = 2.0
imageContainerScrollView.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func imagePickerAction(_ sender: UIButton) {
let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
let cameraAction = UIAlertAction(title: "Take Photo", style: UIAlertAction.Style.default)
{
UIAlertAction in
self.openCamera()
}
let photoLibraryAction = UIAlertAction(title: "Photo Library", style: UIAlertAction.Style.default)
{
UIAlertAction in
self.openLibrary()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel)
{
UIAlertAction in
}
// Add the actions
imagePicker.delegate = self
alert.addAction(photoLibraryAction)
alert.addAction(cameraAction)
alert.addAction(cancelAction)
// Present the controller
if UIDevice.current.userInterfaceIdiom == .phone
{
self.present(alert, animated: true, completion: nil)
}
else
{
if let popoverController = alert.popoverPresentationController {
popoverController.sourceView = sender
popoverController.sourceRect = sender.bounds
}
self.present(alert, animated: true, completion: nil)
}
}
/*===============================================================================*/
// MARK: - Image picker helper methods
/*===============================================================================*/
//To open camera
func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.camera))
{
imagePicker.sourceType = UIImagePickerController.SourceType.camera
self .present(imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertView(title: "Camera is unavailable", message: "Error", delegate: [], cancelButtonTitle: "Ok")
alert.show()
}
}
//To open photo library
func openLibrary()
{
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
if UIDevice.current.userInterfaceIdiom == .phone
{
self.present(imagePicker, animated: true, completion: nil)
}
else
{
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
self.present(imagePicker, animated: true, completion: nil)
}
}
/*===============================================================================*/
// MARK: - Custom Image view delegate methods
/*===============================================================================*/
func selectedWithImage(_ chosenImage: UIImage, parent: AnyObject) {
selectedImage.image = chosenImage
imageContainerScrollView.zoomScale = 1
imageContainerScrollView.minimumZoomScale = 1.0
imageContainerScrollView.maximumZoomScale = 2.0
}
/*
// 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.
}
*/
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return selectedImage
}
/*===============================================================================*/
// MARK: - UIImagePickerControllerDelegate
/*===============================================================================*/
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: { () -> Void in
})
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// Local variable inserted by Swift 4.2 migrator.
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
let chosenImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as! UIImage //2
picker.dismiss(animated: true, completion: { () -> Void in
})
let imageView = self.storyboard?.instantiateViewController(withIdentifier: "ImageView") as! ImageViewController
imageView.delegate = self
imageView.selectedImage = chosenImage
imageView.viewType = "Picker"
self.present(imageView, animated: true, completion: nil)
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
return input.rawValue
}
| 39b8e175dd03f7436a54f961bfdce457 | 34.604396 | 153 | 0.602006 | false | false | false | false |
ACChe/eidolon | refs/heads/master | Kiosk/Auction Listings/WebViewController.swift | mit | 7 | import DZNWebViewController
let modalHeight: CGFloat = 660
class WebViewController: DZNWebViewController {
var showToolbar = true
convenience init(url: NSURL) {
self.init()
self.URL = url
}
override func viewDidLoad() {
super.viewDidLoad()
let webView = view as! UIWebView
webView.scalesPageToFit = true
self.navigationItem.rightBarButtonItem = nil
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated:false)
navigationController?.setToolbarHidden(!showToolbar, animated:false)
}
}
class ModalWebViewController: WebViewController {
var closeButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
closeButton = UIButton()
view.addSubview(closeButton)
closeButton.titleLabel?.font = UIFont.sansSerifFontWithSize(14)
closeButton.setTitleColor(.artsyMediumGrey(), forState:.Normal)
closeButton.setTitle("CLOSE", forState:.Normal)
closeButton.constrainWidth("140", height: "72")
closeButton.alignTop("0", leading:"0", bottom:nil, trailing:nil, toView:view)
closeButton.addTarget(self, action:"closeTapped:", forControlEvents:.TouchUpInside)
var height = modalHeight
if let nav = navigationController {
if !nav.navigationBarHidden { height -= CGRectGetHeight(nav.navigationBar.frame) }
if !nav.toolbarHidden { height -= CGRectGetHeight(nav.toolbar.frame) }
}
preferredContentSize = CGSizeMake(815, height)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.view.superview?.layer.cornerRadius = 0;
}
func closeTapped(sender: AnyObject) {
presentingViewController?.dismissViewControllerAnimated(true, completion:nil)
}
}
| 2655b81e76248dad3bdb4fd0b97bab45 | 31.229508 | 94 | 0.68413 | false | false | false | false |
planvine/Line-Up-iOS-SDK | refs/heads/master | Pod/Classes/Line-Up_ExtCoreData.swift | mit | 1 | /**
* Copyright (c) 2016 Line-Up
*
* 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 CoreData
extension LineUp {
//MARK: - CoreData methods
/**
* Get the event (PVEvent) with id: 'id' from CoreData.
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getEventFromCoreData(id: NSNumber) -> PVEvent? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVEvent, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"eventID = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVEvent)!
}
} catch { return nil }
return nil
}
class func getVenueFromCoreData(id: NSNumber) -> PVVenue? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVVenue, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"venueID = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVVenue)!
}
} catch { return nil }
return nil
}
/**
* Get the performance (PVPerformance) with id: 'id' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
public class func getPerformanceFromCoreData(id: NSNumber) -> PVPerformance? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVPerformance, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"performanceID = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVPerformance)!
}
} catch { return nil }
return nil
}
/**
* It returns true if the performance with id: 'id' has tickets, false otherwise
*/
class func performanceHasTickets(id: NSNumber) -> Bool {
var perf : PVPerformance? = getPerformanceFromCoreData(id)
if perf == nil {
perf = getPerformance(id)
}
if perf != nil && perf!.hasTickets == true {
return true
}
return false
}
/**
* Get the user (PVUser) with accessToken: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
public class func getUserWithTokenFromCoreData(userToken: String) -> PVUser? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVUser, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"accessToken = %@",userToken)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVUser)!
}
} catch { return nil }
return nil
}
/**
* Get the ticket (PVTicket) with id: 'id' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
public class func getTicketFromCoreData(id: NSNumber) -> PVTicket? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVTicket, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"id = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVTicket)!
}
} catch { return nil }
return nil
}
/**
* Get the receipts (array of PVReceipt) for the usen with token: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getTicketsReceiptsFromCoreData(userToken: String) -> [PVReceipt]? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVReceipt, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"user.accessToken = %@",userToken)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
guard objects.count > 0 else {
return nil
}
return objects as? Array<PVReceipt>
} catch {
return nil
}
}
/**
* Get the receipt (PVReceipt) with id: 'id' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getReceiptFromCoreData(id: NSNumber) -> PVReceipt? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVReceipt, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"id = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
guard objects.count > 0 else {
return nil
}
return (objects.lastObject as? PVReceipt)
} catch {
return nil
}
}
/**
* Get list of tickets (array of PVTicket) available for the performance with id: 'performanceId' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getTicketsFromCoreDataOfPerformance(performanceId: NSNumber) -> [PVTicket] {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVPerformance, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"performanceID = %@",performanceId)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 && (objects.lastObject as! PVPerformance).tickets != nil && (objects.lastObject as! PVPerformance).tickets!.allObjects.count > 0{
return (objects.lastObject as? PVPerformance)!.tickets!.allObjects as! Array<PVTicket>
}
} catch { return Array() }
return Array()
}
/**
* Get list of credit cards (array of PVCard for the user with Line-Up token: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getCardsFromCoreData(userToken: String) -> (NSFetchRequest, [PVCard]?) {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
let sortDescriptor1 = NSSortDescriptor(key: "selectedCard", ascending: false)
let sortDescriptor2 = NSSortDescriptor(key: "brand", ascending: false)
let sortDescriptor3 = NSSortDescriptor(key: "expYear", ascending: false)
let sortDescriptor4 = NSSortDescriptor(key: "expMonth", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor1,sortDescriptor2,sortDescriptor3,sortDescriptor4]
fetchRequest.predicate = NSPredicate(format: "user.accessToken = %@",userToken)
do {
return (fetchRequest,try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) as? Array<PVCard>)
} catch {
return (fetchRequest,nil)
}
}
/**
* Get list of credit cards (array of PVCard for the user with Line-Up token: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getCardFromCoreData(id: String) -> PVCard? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"id = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVCard)!
}
} catch { return nil }
return nil
}
/**
* Delete all the credit cards from CoreData except the cards in 'listOfCards'
*/
public class func deleteCardsFromCoreDataExcept(listOfCards: Array<PVCard>, userToken: String) {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
let sortDescriptor1 = NSSortDescriptor(key: "selectedCard", ascending: false)
let sortDescriptor2 = NSSortDescriptor(key: "brand", ascending: false)
let sortDescriptor3 = NSSortDescriptor(key: "expYear", ascending: false)
let sortDescriptor4 = NSSortDescriptor(key: "expMonth", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor1,sortDescriptor2,sortDescriptor3,sortDescriptor4]
var listOfIds: Array<String> = Array()
for card in listOfCards {
if card.id != nil {
listOfIds.append(card.id!)
}
}
fetchRequest.predicate = NSPredicate(format: "user.accessToken = %@ && NOT id IN %@",userToken, listOfIds)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
for managedObject in objects {
PVCoreData.managedObjectContext.deleteObject(managedObject as! NSManagedObject)
}
try PVCoreData.managedObjectContext.save()
} catch { }
}
/**
* Set the card (PVCard) as selected card (default one) on the device (CoreData)
*/
public class func setSelectedCard(card: PVCard) {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
do {
let objects : Array<PVCard> = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) as! Array<PVCard>
for obj in objects {
if obj.id != card.id {
obj.selectedCard = false
} else {
obj.selectedCard = true
}
}
try PVCoreData.managedObjectContext.save()
} catch { }
}
}
| 36cf39ac119b6c4f5806f267e145bace | 46.637363 | 162 | 0.665283 | false | false | false | false |
m-alani/contests | refs/heads/master | leetcode/pascalsTriangleII.swift | mit | 1 | //
// pascalsTriangleII.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/pascals-triangle-ii/
// Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code
//
class Solution {
func getRow(_ rowIndex: Int) -> [Int] {
var row = Array(repeating: 0, count: rowIndex + 1)
var num = Double(rowIndex), den = 1.0, idx = 1
row[0] = 1
// Cover the edge case of index = 0
if rowIndex == 0 { return row }
// Find the values for the first half
while num >= den {
row[idx] = Int(Double(row[idx-1]) * num / den)
num -= 1
den += 1
idx += 1
}
// Mirror the values to the second half
let half = row.count / 2
row[row.count-half...rowIndex] = ArraySlice(row[0..<half].reversed())
return row
}
}
| 87384abc65b2a02ccf395d9f578c27ad | 27.28125 | 117 | 0.61326 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/TXTReader/BookDetail/Models/BookShelfInfo.swift | mit | 1 | //
// BokShelfInfo.swift
// zhuishushenqi
//
// Created by Nory Cao on 2017/3/6.
// Copyright © 2017年 QS. All rights reserved.
//
import UIKit
class BookShelfInfo: NSObject {
static let books = BookShelfInfo()
private override init() {
}
let bookShelfInfo = "bookShelfInfo"
let readHistoryKey = "readHistoryKey"
let bookshelfSaveKey = "bookshelfSaveKey"
var readHistory:[BookDetail]{
get{
var data:[BookDetail]? = []
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last?.appending("/\(readHistoryKey.md5())")
if let filePath = path {
let file:NSDictionary? = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? NSDictionary
data = file?[readHistoryKey] as? [BookDetail]
}
return data ?? []
}
set{
let dict = [readHistoryKey:newValue]
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last?.appending("/\(readHistoryKey.md5())")
if let filePath = path {
do {
let url = URL(string: filePath)
try FileManager.default.removeItem(at: url!)
} catch _{}
NSKeyedArchiver.archiveRootObject(dict, toFile: filePath)
}
}
}
public func delete(book:BookDetail) {
}
}
| 486d28e2efbde2c528874f4eb07d8223 | 28.529412 | 145 | 0.571049 | false | false | false | false |
aryaxt/SwiftInjection | refs/heads/master | SwiftInjection/DIBindingProvider.swift | mit | 1 | //
// DIBindingInfo.swift
// SwiftInjection
//
// Created by Aryan Ghassemi on 4/24/16.
// Copyright © 2016 Aryan Ghassemi. All rights reserved.
//
import Foundation
internal class DIBindingProvider {
private var namedBindings = [String: DINamedBinding]()
private static let defaultBindingName = "default"
func addBinding(closure: @escaping ()->Any, named: String? = nil, asSingleton: Bool) {
let named = named ?? DIBindingProvider.defaultBindingName
namedBindings[named] = DINamedBinding(closure: closure, asSingleton: asSingleton)
}
func provideInstance(named: String? = nil) -> Any {
let named = named ?? DIBindingProvider.defaultBindingName
guard let namedBinding = namedBindings[named] else { fatalError("Did not find binding named \(named)") }
return namedBinding.provideInstance()
}
func provideAllInstances() -> [Any] {
return namedBindings.values.map { $0.provideInstance() }
}
}
| 69bbe0f6262e98a537fdbf8e5cf466d1 | 28.741935 | 106 | 0.734273 | false | false | false | false |
andrewgrant/TodoApp | refs/heads/master | Shared/TodoEntry.swift | mit | 1 | //
// TodoEntry.swift
// TodoApp
//
// Created by Andrew Grant on 6/23/15.
// Copyright (c) 2015 Andrew Grant. All rights reserved.
//
import Foundation
class TodoEntry : TodoItem {
var title : String!
var parentUuid : String?
var completed = false
var priority : Int = 0
init (title : String) {
self.title = title
super.init()
}
required init(record: RemoteRecord) {
super.init(record: record)
}
override func decodeSelf(record : RemoteRecord) {
self.title = record["title"] as! String
self.parentUuid = record["parentUuid"] as? String
self.completed = record["completed"] as! Bool
self.priority = record["priority"] as! Int
}
override func encodeSelf(record : RemoteRecord) {
super.encodeSelf(record)
record["title"] = self.title
record["parentUuid"] = self.parentUuid
record["completed"] = self.completed
record["priority"] = self.priority
}
}
| da7ac36ae52583f075c214aaf1f3e0f5 | 22.727273 | 57 | 0.591954 | false | false | false | false |
cfilipov/MuscleBook | refs/heads/master | MuscleBook/DebugMenuViewController.swift | gpl-3.0 | 1 | /*
Muscle Book
Copyright (C) 2016 Cristian Filipov
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 UIKit
import Eureka
import JSQNotificationObserverKit
class DebugMenuViewController : FormViewController {
private let db = DB.sharedInstance
private let mainQueue = NSOperationQueue.mainQueue()
private var observer: CocoaObserver? = nil
override func viewDidLoad() {
super.viewDidLoad()
let notification = CocoaNotification(name: UIApplicationDidReceiveMemoryWarningNotification)
observer = CocoaObserver(notification, queue: self.mainQueue, handler: { (notification: NSNotification) in
self.tableView?.reloadData()
})
title = "Debug Menu"
form
+++ Section() {
$0.header = HeaderFooterView(title: "Warning")
$0.footer = HeaderFooterView(title: "Don't mess with the debug settings unless you know what you are doing.\n\nSome of the options here may cause data loss or other craziness.")
}
+++ Section()
<<< LabelRow() {
$0.title = "Timers"
}.cellSetup { cell, row in
cell.accessoryType = .DisclosureIndicator
}.onCellSelection { cell, row in
let vc = DebugTimersViewController()
self.showViewController(vc, sender: nil)
}
<<< LabelRow() {
$0.title = "Color Palette"
}.cellSetup { cell, row in
cell.accessoryType = .DisclosureIndicator
}.onCellSelection { cell, row in
let vc = ColorPaletteViewController()
self.showViewController(vc, sender: nil)
}
<<< LabelRow() {
$0.title = "Anatomy"
}.cellSetup { cell, row in
cell.accessoryType = .DisclosureIndicator
}.onCellSelection { cell, row in
let vc = AnatomyDebugViewController2()
self.showViewController(vc, sender: nil)
}
// <<< LabelRow("import_csv") {
// $0.title = "Import CSV"
// $0.disabled = "$import_csv != nil"
// $0.hidden = Dropbox.authorizedClient == nil ? true : false
// }.onCellSelection(onImportCSV)
//
// <<< LabelRow("sync_dropbox") {
// $0.title = "Sync Dropbox"
// $0.disabled = "$sync_dropbox != nil"
// $0.hidden = Dropbox.authorizedClient == nil ? true : false
// }.onCellSelection(onSyncWithDropbox)
+++ Section()
<<< ButtonRow() {
$0.title = "Recalculate All Workouts"
$0.cellUpdate { cell, _ in
cell.textLabel?.textColor = UIColor.redColor()
}
$0.onCellSelection { _, _ in
WarnAlert(message: "Are you sure? This will be slow and the UI will be unresponsive while calculating.") {
try! self.db.recalculateAll()
}
}
}
<<< ButtonRow() {
$0.title = "Export Exercises"
$0.cellUpdate { cell, _ in
cell.textLabel?.textColor = UIColor.redColor()
}
$0.onCellSelection { _, _ in
let url = NSFileManager
.defaultManager()
.URLsForDirectory(
.CachesDirectory,
inDomains: .UserDomainMask
)[0]
.URLByAppendingPathComponent("exercises.yaml")
try! self.db.exportYAML(Exercise.self, toURL: url)
let vc = UIActivityViewController(
activityItems: [url],
applicationActivities: nil
)
self.presentViewController(vc, animated: true, completion: nil)
}
}
}
// private func onSyncWithDropbox(cell: LabelCell, row: LabelRow) {
// WarnAlert(message: "Are you sure you want to sync?") { _ in
// row.value = "Syncing..."
// row.reload()
// Workset.importFromDropbox("/WorkoutLog.yaml") { status in
// guard .Success == status else {
// Alert(message: "Failed to sync with dropbox")
// return
// }
// row.value = nil
// row.disabled = false
// row.reload()
// Alert(message: "Sync Complete")
// }
// }
// }
// private func onImportCSV(cell: LabelCell, row: LabelRow) {
// guard db.count(Workset) == 0 else {
// Alert(message: "Cannot import data, you already have data.")
// return
// }
// WarnAlert(message: "Import Data from Dropbox?") { _ in
// row.value = "Importing..."
// row.reload()
// Workset.downloadFromDropbox("/WorkoutLog.csv") { url in
// guard let url = url else {
// row.value = nil
// row.reload()
// Alert(message: "Failed to import CSV data")
// return
// }
// row.value = "Importing..."
// row.reload()
// do {
// let importCount = try self.db.importCSV(Workset.self, fromURL: url)
// row.value = nil
// row.disabled = false
// row.reload()
// Alert("Import Complete", message: "\(importCount) records imported.") { _ in
//// let vc = VerifyWorksetsViewController()
//// self.presentModalViewController(vc)
// }
// } catch {
// row.value = nil
// row.reload()
// Alert(message: "Failed to import CSV data")
// return
// }
// }
// }
// }
}
| e4dfcbaf248d8157da01bbe584ed2e9b | 35.398876 | 189 | 0.528014 | false | false | false | false |
ElijahButers/Swift | refs/heads/master | Show Local IP/showip/ViewController.swift | gpl-3.0 | 33 | //
// ViewController.swift
// showip
//
// Created by Carlos Butron on 4/2/15.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// 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 UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
getIFAddresses()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getIFAddresses() -> [String] {
var addresses = [String]()
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0 {
// For each interface ...
for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) {
let flags = Int32(ptr.memory.ifa_flags)
var addr = ptr.memory.ifa_addr.memory
// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
// Convert interface address to a human readable string:
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST) == 0) {
if let address = String.fromCString(hostname) {
addresses.append(address)
}
}
}
}
}
freeifaddrs(ifaddr)
}
println("Local IP \(addresses)")
return addresses
}
}
| 2d07d839984e1325991855d784efb0a7 | 37.5 | 121 | 0.5718 | false | false | false | false |
guillermo-ag-95/App-Development-with-Swift-for-Students | refs/heads/master | 1 - Getting Started/4 - Control Flow/lab/Lab - Control Flow.playground/Pages/2. Exercise - If and If-Else Statements.xcplaygroundpage/Contents.swift | mit | 1 | /*:
## Exercise - If and If-Else Statements
Imagine you're creating a machine that will count your money for you and tell you how wealthy you are based on how much money you have. A variable `dollars` has been given to you with a value of 0. Write an if statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0. Observe what is printed to the console.
*/
var dollars = 0
if dollars == 0 {
print("Sorry, kid. You're broke!")
}
/*:
`dollars` has been updated below to have a value of 10. Write an an if-else statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0, but prints "You've got some spending money!" otherwise. Observe what is printed to the console.
*/
dollars = 10
if dollars == 0 {
print("Sorry, kid. You're broke!")
} else {
print("You've got some spending money!")
}
/*:
`dollars` has been updated below to have a value of 105. Write an an if-else-if statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0, prints "You've got some spending money!" if `dollars` is less than 100, and prints "Looks to me like you're rich!" otherwise. Observe what is printed to the console.
*/
dollars = 105
if dollars == 0 {
print("Sorry, kid. You're broke!")
} else if dollars < 100 {
print("You've got some spending money!")
} else {
print("Looks to me like you're rich!")
}
//: [Previous](@previous) | page 2 of 9 | [Next: App Exercise - Fitness Decisions](@next)
| be9aef1aa8d1dc3f4f81cfb453196b8d | 43.69697 | 331 | 0.687458 | false | false | false | false |
GYLibrary/A_Y_T | refs/heads/master | DGElasticPullToRefresh/DGElasticPullToRefreshConstants.swift | mit | 13 | /*
The MIT License (MIT)
Copyright (c) 2015 Danil Gontovnik
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 CoreGraphics
public struct DGElasticPullToRefreshConstants {
struct KeyPaths {
static let ContentOffset = "contentOffset"
static let ContentInset = "contentInset"
static let Frame = "frame"
static let PanGestureRecognizerState = "panGestureRecognizer.state"
}
public static var WaveMaxHeight: CGFloat = 70.0
public static var MinOffsetToPull: CGFloat = 95.0
public static var LoadingContentInset: CGFloat = 50.0
public static var LoadingViewSize: CGFloat = 30.0
} | 05dcaa127bccf5d2de515d1bdea54b23 | 36.930233 | 78 | 0.768712 | false | false | false | false |
zmeyc/telegram-bot-swift | refs/heads/master | Sources/TelegramBotSDK/BotName.swift | apache-2.0 | 1 | //
// BotName.swift
//
// This source file is part of the Telegram Bot SDK for Swift (unofficial).
//
// Copyright (c) 2015 - 2020 Andrey Fidrya and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See AUTHORS.txt for the list of the project authors
//
import Foundation
public class BotName {
let underscoreBotSuffix = "_bot"
let botSuffix = "bot"
public var withoutSuffix: String
public init(username: String) {
let lowercase = username.lowercased()
if lowercase.hasSuffix(underscoreBotSuffix) {
withoutSuffix = String(username.dropLast(underscoreBotSuffix.count))
} else if lowercase.hasSuffix(botSuffix) {
withoutSuffix = String(username.dropLast(botSuffix.count))
} else {
withoutSuffix = username
}
}
}
extension BotName: Equatable {
}
public func ==(lhs: BotName, rhs: BotName) -> Bool {
return lhs.withoutSuffix == rhs.withoutSuffix
}
extension BotName: Comparable {
}
public func <(lhs: BotName, rhs: BotName) -> Bool {
return lhs.withoutSuffix < rhs.withoutSuffix
}
| a0b8a0fc400c0ece1099a68fefe7a022 | 24.217391 | 75 | 0.69569 | false | false | false | false |
3squared/ios-charts | refs/heads/master | Charts/Classes/Charts/BarLineChartViewBase.swift | apache-2.0 | 1 | //
// BarLineChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
/// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
public class BarLineChartViewBase: ChartViewBase, UIGestureRecognizerDelegate
{
/// the maximum number of entried to which values will be drawn
internal var _maxVisibleValueCount = 100
/// flag that indicates if auto scaling on the y axis is enabled
private var _autoScaleMinMaxEnabled = false
private var _autoScaleLastLowestVisibleXIndex: Int!
private var _autoScaleLastHighestVisibleXIndex: Int!
private var _pinchZoomEnabled = false
private var _doubleTapToZoomEnabled = true
private var _dragEnabled = true
private var _scaleXEnabled = true
private var _scaleYEnabled = true
/// the color for the background of the chart-drawing area (everything behind the grid lines).
public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
public var borderColor = UIColor.blackColor()
public var borderLineWidth: CGFloat = 1.0
/// flag indicating if the grid background should be drawn or not
public var drawGridBackgroundEnabled = true
/// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis.
public var drawBordersEnabled = false
/// Sets the minimum offset (padding) around the chart, defaults to 10
public var minOffset = CGFloat(10.0)
/// the object representing the labels on the y-axis, this object is prepared
/// in the pepareYLabels() method
internal var _leftAxis: ChartYAxis!
internal var _rightAxis: ChartYAxis!
/// the object representing the labels on the x-axis
internal var _xAxis: ChartXAxis!
internal var _leftYAxisRenderer: ChartYAxisRenderer!
internal var _rightYAxisRenderer: ChartYAxisRenderer!
internal var _leftAxisTransformer: ChartTransformer!
internal var _rightAxisTransformer: ChartTransformer!
internal var _xAxisRenderer: ChartXAxisRenderer!
internal var _tapGestureRecognizer: UITapGestureRecognizer!
internal var _doubleTapGestureRecognizer: UITapGestureRecognizer!
#if !os(tvOS)
internal var _pinchGestureRecognizer: UIPinchGestureRecognizer!
#endif
internal var _panGestureRecognizer: UIPanGestureRecognizer!
/// flag that indicates if a custom viewport offset has been set
private var _customViewPortEnabled = false
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
deinit
{
stopDeceleration()
}
internal override func initialize()
{
super.initialize()
_leftAxis = ChartYAxis(position: .Left)
_rightAxis = ChartYAxis(position: .Right)
_xAxis = ChartXAxis()
_leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler)
_rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler)
_leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer)
_rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer)
_xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer)
_highlighter = ChartHighlighter(chart: self)
_tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:"))
_doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:"))
_doubleTapGestureRecognizer.numberOfTapsRequired = 2
_panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:"))
_panGestureRecognizer.delegate = self
self.addGestureRecognizer(_tapGestureRecognizer)
self.addGestureRecognizer(_doubleTapGestureRecognizer)
self.addGestureRecognizer(_panGestureRecognizer)
_doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled
_panGestureRecognizer.enabled = _dragEnabled
#if !os(tvOS)
_pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:"))
_pinchGestureRecognizer.delegate = self
self.addGestureRecognizer(_pinchGestureRecognizer)
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect)
if (_dataNotSet)
{
return
}
let context = UIGraphicsGetCurrentContext()
calcModulus()
if (_xAxisRenderer !== nil)
{
_xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus)
}
if (renderer !== nil)
{
renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus)
}
// execute all drawing commands
drawGridBackground(context: context)
if (_leftAxis.isEnabled)
{
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum)
}
if (_rightAxis.isEnabled)
{
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum)
}
_xAxisRenderer?.renderAxisLine(context: context)
_leftYAxisRenderer?.renderAxisLine(context: context)
_rightYAxisRenderer?.renderAxisLine(context: context)
if (_autoScaleMinMaxEnabled)
{
let lowestVisibleXIndex = self.lowestVisibleXIndex,
highestVisibleXIndex = self.highestVisibleXIndex
if (_autoScaleLastLowestVisibleXIndex == nil || _autoScaleLastLowestVisibleXIndex != lowestVisibleXIndex ||
_autoScaleLastHighestVisibleXIndex == nil || _autoScaleLastHighestVisibleXIndex != highestVisibleXIndex)
{
calcMinMax()
calculateOffsets()
_autoScaleLastLowestVisibleXIndex = lowestVisibleXIndex
_autoScaleLastHighestVisibleXIndex = highestVisibleXIndex
}
}
// make sure the graph values and grid cannot be drawn outside the content-rect
CGContextSaveGState(context)
CGContextClipToRect(context, _viewPortHandler.contentRect)
if (_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context)
}
if (_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context)
}
if (_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context)
}
_xAxisRenderer?.renderGridLines(context: context)
_leftYAxisRenderer?.renderGridLines(context: context)
_rightYAxisRenderer?.renderGridLines(context: context)
renderer?.drawData(context: context)
// if highlighting is enabled
if (valuesToHighlight())
{
renderer?.drawHighlighted(context: context, indices: _indicesToHightlight)
}
// Removes clipping rectangle
CGContextRestoreGState(context)
renderer!.drawExtras(context: context)
_xAxisRenderer.renderAxisLabels(context: context)
_leftYAxisRenderer.renderAxisLabels(context: context)
_rightYAxisRenderer.renderAxisLabels(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
// drawLegend()
if (!_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context)
}
if (!_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context)
}
if (!_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context)
}
drawMarkers(context: context)
drawDescription(context: context)
}
internal func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum)
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum)
}
internal func prepareOffsetMatrix()
{
_rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted)
_leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted)
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return
}
calcMinMax()
_leftAxis?._defaultValueFormatter = _defaultValueFormatter
_rightAxis?._defaultValueFormatter = _defaultValueFormatter
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum)
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum)
_xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals)
if (_legend !== nil)
{
_legendRenderer?.computeLegend(_data)
}
calculateOffsets()
setNeedsDisplay()
}
internal override func calcMinMax()
{
if (_autoScaleMinMaxEnabled)
{
_data.calcMinMax(start: lowestVisibleXIndex, end: highestVisibleXIndex)
}
var minLeft = _data.getYMin(.Left)
var maxLeft = _data.getYMax(.Left)
var minRight = _data.getYMin(.Right)
var maxRight = _data.getYMax(.Right)
let leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft))
let rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight))
// in case all values are equal
if (leftRange == 0.0)
{
maxLeft = maxLeft + 1.0
if (!_leftAxis.isStartAtZeroEnabled)
{
minLeft = minLeft - 1.0
}
}
if (rightRange == 0.0)
{
maxRight = maxRight + 1.0
if (!_rightAxis.isStartAtZeroEnabled)
{
minRight = minRight - 1.0
}
}
let topSpaceLeft = leftRange * Double(_leftAxis.spaceTop)
let topSpaceRight = rightRange * Double(_rightAxis.spaceTop)
let bottomSpaceLeft = leftRange * Double(_leftAxis.spaceBottom)
let bottomSpaceRight = rightRange * Double(_rightAxis.spaceBottom)
_chartXMax = Double(_data.xVals.count - 1)
_deltaX = CGFloat(abs(_chartXMax - _chartXMin))
// Consider sticking one of the edges of the axis to zero (0.0)
if _leftAxis.isStartAtZeroEnabled
{
if minLeft < 0.0 && maxLeft < 0.0
{
// If the values are all negative, let's stay in the negative zone
_leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft))
_leftAxis.axisMaximum = 0.0
}
else if minLeft >= 0.0
{
// We have positive values only, stay in the positive zone
_leftAxis.axisMinimum = 0.0
_leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft))
}
else
{
// Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time)
_leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft))
_leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft))
}
}
else
{
// Use the values as they are
_leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)
_leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)
}
if _rightAxis.isStartAtZeroEnabled
{
if minRight < 0.0 && maxRight < 0.0
{
// If the values are all negative, let's stay in the negative zone
_rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight))
_rightAxis.axisMaximum = 0.0
}
else if minRight >= 0.0
{
// We have positive values only, stay in the positive zone
_rightAxis.axisMinimum = 0.0
_rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight))
}
else
{
// Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time)
_rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight))
_rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight))
}
}
else
{
_rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)
_rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)
}
_leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum)
_rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum)
}
internal override func calculateOffsets()
{
if (!_customViewPortEnabled)
{
var offsetLeft = CGFloat(0.0)
var offsetRight = CGFloat(0.0)
var offsetTop = CGFloat(0.0)
var offsetBottom = CGFloat(0.0)
// setup offsets for legend
if (_legend !== nil && _legend.isEnabled)
{
if (_legend.position == .RightOfChart
|| _legend.position == .RightOfChartCenter)
{
offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0
}
if (_legend.position == .LeftOfChart
|| _legend.position == .LeftOfChartCenter)
{
offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0
}
else if (_legend.position == .BelowChartLeft
|| _legend.position == .BelowChartRight
|| _legend.position == .BelowChartCenter)
{
// It's possible that we do not need this offset anymore as it
// is available through the extraOffsets, but changing it can mean
// changing default visibility for existing apps.
let yOffset = _legend.textHeightMax
offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent)
}
else if (_legend.position == .AboveChartLeft
|| _legend.position == .AboveChartRight
|| _legend.position == .AboveChartCenter)
{
// It's possible that we do not need this offset anymore as it
// is available through the extraOffsets, but changing it can mean
// changing default visibility for existing apps.
let yOffset = _legend.textHeightMax
offsetTop += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent)
}
}
// offsets for y-labels
if (leftAxis.needsOffset)
{
offsetLeft += leftAxis.requiredSize().width
}
if (rightAxis.needsOffset)
{
offsetRight += rightAxis.requiredSize().width
}
if (xAxis.isEnabled && xAxis.isDrawLabelsEnabled)
{
let xlabelheight = xAxis.labelHeight * 2.0
// offsets for x-labels
if (xAxis.labelPosition == .Bottom)
{
offsetBottom += xlabelheight
}
else if (xAxis.labelPosition == .Top)
{
offsetTop += xlabelheight
}
else if (xAxis.labelPosition == .BothSided)
{
offsetBottom += xlabelheight
offsetTop += xlabelheight
}
}
offsetTop += self.extraTopOffset
offsetRight += self.extraRightOffset
offsetBottom += self.extraBottomOffset
offsetLeft += self.extraLeftOffset
_viewPortHandler.restrainViewPort(
offsetLeft: max(self.minOffset, offsetLeft),
offsetTop: max(self.minOffset, offsetTop),
offsetRight: max(self.minOffset, offsetRight),
offsetBottom: max(self.minOffset, offsetBottom))
}
prepareOffsetMatrix()
prepareValuePxMatrix()
}
/// calculates the modulus for x-labels and grid
internal func calcModulus()
{
if (_xAxis === nil || !_xAxis.isEnabled)
{
return
}
if (!_xAxis.isAxisModulusCustom)
{
_xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a)))
}
if (_xAxis.axisLabelModulus < 1)
{
_xAxis.axisLabelModulus = 1
}
}
public override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
let dataSetIndex = highlight.dataSetIndex
var xPos = CGFloat(e.xIndex)
var yPos = CGFloat(e.value)
if (self.isKindOfClass(BarChartView))
{
let bd = _data as! BarChartData
let space = bd.groupSpace
let setCount = _data.dataSetCount
let i = e.xIndex
if self is HorizontalBarChartView
{
// calculate the x-position, depending on datasetcount
let y = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0
yPos = y
if let entry = e as? BarChartDataEntry
{
if entry.values != nil && highlight.range !== nil
{
xPos = CGFloat(highlight.range!.to)
}
else
{
xPos = CGFloat(e.value)
}
}
}
else
{
let x = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0
xPos = x
if let entry = e as? BarChartDataEntry
{
if entry.values != nil && highlight.range !== nil
{
yPos = CGFloat(highlight.range!.to)
}
else
{
yPos = CGFloat(e.value)
}
}
}
}
// position of the marker depends on selected value index and value
var pt = CGPoint(x: xPos, y: yPos * _animator.phaseY)
getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt)
return pt
}
/// draws the grid background
internal func drawGridBackground(context context: CGContext?)
{
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextSaveGState(context)
}
if (drawGridBackgroundEnabled)
{
// draw the grid background
CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor)
CGContextFillRect(context, _viewPortHandler.contentRect)
}
if (drawBordersEnabled)
{
CGContextSetLineWidth(context, borderLineWidth)
CGContextSetStrokeColorWithColor(context, borderColor.CGColor)
CGContextStrokeRect(context, _viewPortHandler.contentRect)
}
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextRestoreGState(context)
}
}
/// - returns: the Transformer class that contains all matrices and is
/// responsible for transforming values into pixels on the screen and
/// backwards.
public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer
{
if (which == .Left)
{
return _leftAxisTransformer
}
else
{
return _rightAxisTransformer
}
}
// MARK: - Gestures
private enum GestureScaleAxis
{
case Both
case X
case Y
}
private var _isDragging = false
private var _isScaling = false
private var _gestureScaleAxis = GestureScaleAxis.Both
private var _closestDataSetToTouch: ChartDataSet!
private var _panGestureReachedEdge: Bool = false
private weak var _outerScrollView: UIScrollView?
private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity
private var _decelerationLastTime: NSTimeInterval = 0.0
private var _decelerationDisplayLink: CADisplayLink!
private var _decelerationVelocity = CGPoint()
@objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
let h = getHighlightByTouchPoint(recognizer.locationInView(self))
if (h === nil || h!.isEqual(self.lastHighlighted))
{
self.highlightValue(highlight: nil, callDelegate: true)
self.lastHighlighted = nil
}
else
{
self.lastHighlighted = h
self.highlightValue(highlight: h, callDelegate: true)
}
}
}
@objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
if (!_dataNotSet && _doubleTapToZoomEnabled)
{
var location = recognizer.locationInView(self)
location.x = location.x - _viewPortHandler.offsetLeft
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom)
}
self.zoom(isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y)
}
}
}
#if !os(tvOS)
@objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
stopDeceleration()
if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled))
{
_isScaling = true
if (_pinchZoomEnabled)
{
_gestureScaleAxis = .Both
}
else
{
let x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x)
let y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y)
if (x > y)
{
_gestureScaleAxis = .X
}
else
{
_gestureScaleAxis = .Y
}
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended ||
recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isScaling)
{
_isScaling = false
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
let isZoomingOut = (recognizer.scale < 1)
let canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX
if (_isScaling)
{
if (canZoomMoreX || (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y && _scaleYEnabled))
{
var location = recognizer.locationInView(self)
location.x = location.x - _viewPortHandler.offsetLeft
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom)
}
let scaleX = (_gestureScaleAxis == .Both || _gestureScaleAxis == .X) && _scaleXEnabled ? recognizer.scale : 1.0
let scaleY = (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y) && _scaleYEnabled ? recognizer.scale : 1.0
var matrix = CGAffineTransformMakeTranslation(location.x, location.y)
matrix = CGAffineTransformScale(matrix, scaleX, scaleY)
matrix = CGAffineTransformTranslate(matrix,
-location.x, -location.y)
matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if (delegate !== nil)
{
delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY)
}
}
recognizer.scale = 1.0
}
}
}
#endif
@objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began && recognizer.numberOfTouches() > 0)
{
stopDeceleration()
if ((!_dataNotSet && _dragEnabled && !self.hasNoDragOffset) || !self.isFullyZoomedOut)
{
_isDragging = true
_closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self))
let translation = recognizer.translationInView(self)
let didUserDrag = (self is HorizontalBarChartView) ? translation.y != 0.0 : translation.x != 0.0
// Check to see if user dragged at all and if so, can the chart be dragged by the given amount
if (didUserDrag && !performPanChange(translation: translation))
{
if (_outerScrollView !== nil)
{
// We can stop dragging right now, and let the scroll view take control
_outerScrollView = nil
_isDragging = false
}
}
else
{
if (_outerScrollView !== nil)
{
// Prevent the parent scroll view from scrolling
_outerScrollView?.scrollEnabled = false
}
}
_lastPanPoint = recognizer.translationInView(self)
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isDragging)
{
let originalTranslation = recognizer.translationInView(self)
let translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y)
performPanChange(translation: translation)
_lastPanPoint = originalTranslation
}
else if (isHighlightPerDragEnabled)
{
let h = getHighlightByTouchPoint(recognizer.locationInView(self))
let lastHighlighted = self.lastHighlighted
if ((h === nil && lastHighlighted !== nil) ||
(h !== nil && lastHighlighted === nil) ||
(h !== nil && lastHighlighted !== nil && !h!.isEqual(lastHighlighted)))
{
self.lastHighlighted = h
self.highlightValue(highlight: h, callDelegate: true)
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isDragging)
{
if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled)
{
stopDeceleration()
_decelerationLastTime = CACurrentMediaTime()
_decelerationVelocity = recognizer.velocityInView(self)
_decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop"))
_decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
_isDragging = false
}
if (_outerScrollView !== nil)
{
_outerScrollView?.scrollEnabled = true
_outerScrollView = nil
}
}
}
private func performPanChange(var translation translation: CGPoint) -> Bool
{
if (isAnyAxisInverted && _closestDataSetToTouch !== nil
&& getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
if (self is HorizontalBarChartView)
{
translation.x = -translation.x
}
else
{
translation.y = -translation.y
}
}
let originalMatrix = _viewPortHandler.touchMatrix
var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y)
matrix = CGAffineTransformConcat(originalMatrix, matrix)
matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if (delegate !== nil)
{
delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y)
}
// Did we managed to actually drag or did we reach the edge?
return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty
}
public func stopDeceleration()
{
if (_decelerationDisplayLink !== nil)
{
_decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
_decelerationDisplayLink = nil
}
}
@objc private func decelerationLoop()
{
let currentTime = CACurrentMediaTime()
_decelerationVelocity.x *= self.dragDecelerationFrictionCoef
_decelerationVelocity.y *= self.dragDecelerationFrictionCoef
let timeInterval = CGFloat(currentTime - _decelerationLastTime)
let distance = CGPoint(
x: _decelerationVelocity.x * timeInterval,
y: _decelerationVelocity.y * timeInterval
)
if (!performPanChange(translation: distance))
{
// We reached the edge, stop
_decelerationVelocity.x = 0.0
_decelerationVelocity.y = 0.0
}
_decelerationLastTime = currentTime
if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001)
{
stopDeceleration()
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool
{
if (!super.gestureRecognizerShouldBegin(gestureRecognizer))
{
return false
}
if (gestureRecognizer == _panGestureRecognizer)
{
if (_dataNotSet || !_dragEnabled || !self.hasNoDragOffset ||
(self.isFullyZoomedOut && !self.isHighlightPerDragEnabled))
{
return false
}
}
else
{
#if !os(tvOS)
if (gestureRecognizer == _pinchGestureRecognizer)
{
if (_dataNotSet || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled))
{
return false
}
}
#endif
}
return true
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
{
#if !os(tvOS)
if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) ||
(gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer)))
{
return true
}
#endif
if (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && (
gestureRecognizer == _panGestureRecognizer
))
{
var scrollView = self.superview
while (scrollView !== nil && !scrollView!.isKindOfClass(UIScrollView))
{
scrollView = scrollView?.superview
}
var foundScrollView = scrollView as? UIScrollView
if (foundScrollView !== nil && !foundScrollView!.scrollEnabled)
{
foundScrollView = nil
}
var scrollViewPanGestureRecognizer: UIGestureRecognizer!
if (foundScrollView !== nil)
{
for scrollRecognizer in foundScrollView!.gestureRecognizers!
{
if (scrollRecognizer.isKindOfClass(UIPanGestureRecognizer))
{
scrollViewPanGestureRecognizer = scrollRecognizer as! UIPanGestureRecognizer
break
}
}
}
if (otherGestureRecognizer === scrollViewPanGestureRecognizer)
{
_outerScrollView = foundScrollView
return true
}
}
return false
}
/// MARK: Viewport modifiers
/// Zooms in by 1.4, into the charts center. center.
public func zoomIn()
{
let matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0))
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms out by 0.7, from the charts center. center.
public func zoomOut()
{
let matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0))
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms in or out by the given scale factor. x and y are the coordinates
/// (in pixels) of the zoom center.
///
/// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter x:
/// - parameter y:
public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat)
{
let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
public func fitScreen()
{
let matrix = _viewPortHandler.fitScreen()
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen
public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat)
{
_viewPortHandler.setMinimumScaleX(scaleX)
_viewPortHandler.setMinimumScaleY(scaleY)
}
/// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zomming out allowed).
/// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling.
public func setVisibleXRangeMaximum(maxXRange: CGFloat)
{
let xScale = _deltaX / maxXRange
_viewPortHandler.setMinimumScaleX(xScale)
}
/// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed).
/// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling.
public func setVisibleXRangeMinimum(minXRange: CGFloat)
{
let xScale = _deltaX / minXRange
_viewPortHandler.setMaximumScaleX(xScale)
}
/// Limits the maximum and minimum value count that can be visible by pinching and zooming.
/// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed
/// at once without scrolling
public func setVisibleXRange(minXRange minXRange: CGFloat, maxXRange: CGFloat)
{
let maxScale = _deltaX / minXRange
let minScale = _deltaX / maxXRange
_viewPortHandler.setMinMaxScaleX(minScaleX: minScale, maxScaleX: maxScale)
}
/// Sets the size of the area (range on the y-axis) that should be maximum visible at once.
///
/// - parameter yRange:
/// - parameter axis: - the axis for which this limit should apply
public func setVisibleYRangeMaximum(maxYRange: CGFloat, axis: ChartYAxis.AxisDependency)
{
let yScale = getDeltaY(axis) / maxYRange
_viewPortHandler.setMinimumScaleY(yScale)
}
/// Moves the left side of the current viewport to the specified x-index.
/// This also refreshes the chart by calling setNeedsDisplay().
public func moveViewToX(xIndex: Int)
{
if (_viewPortHandler.hasChartDimens)
{
var pt = CGPoint(x: CGFloat(xIndex), y: 0.0)
getTransformer(.Left).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); })
}
}
/// Centers the viewport to the specified y-value on the y-axis.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY
var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0)
getTransformer(axis).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); })
}
}
/// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xIndex:
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
public func moveViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY
var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0)
getTransformer(axis).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); })
}
}
/// This will move the center of the current viewport to the specified x-index and y-value.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xIndex:
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
public func centerViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY
let xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX
var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0)
getTransformer(axis).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); })
}
}
/// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this.
/// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`.
public func setViewPortOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
_customViewPortEnabled = true
if (NSThread.isMainThread())
{
self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom)
prepareOffsetMatrix()
prepareValuePxMatrix()
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom)
})
}
}
/// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically.
public func resetViewPortOffsets()
{
_customViewPortEnabled = false
calculateOffsets()
}
// MARK: - Accessors
/// - returns: the delta-y value (y-value range) of the specified axis.
public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat
{
if (axis == .Left)
{
return CGFloat(leftAxis.axisRange)
}
else
{
return CGFloat(rightAxis.axisRange)
}
}
/// - returns: the position (in pixels) the provided Entry has inside the chart view
public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value))
getTransformer(axis).pointValueToPixel(&vals)
return vals
}
/// the number of maximum visible drawn values on the chart
/// only active when `setDrawValues()` is enabled
public var maxVisibleValueCount: Int
{
get
{
return _maxVisibleValueCount
}
set
{
_maxVisibleValueCount = newValue
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var dragEnabled: Bool
{
get
{
return _dragEnabled
}
set
{
if (_dragEnabled != newValue)
{
_dragEnabled = newValue
}
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var isDragEnabled: Bool
{
return dragEnabled
}
/// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging).
public func setScaleEnabled(enabled: Bool)
{
if (_scaleXEnabled != enabled || _scaleYEnabled != enabled)
{
_scaleXEnabled = enabled
_scaleYEnabled = enabled
#if !os(tvOS)
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
public var scaleXEnabled: Bool
{
get
{
return _scaleXEnabled
}
set
{
if (_scaleXEnabled != newValue)
{
_scaleXEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
public var scaleYEnabled: Bool
{
get
{
return _scaleYEnabled
}
set
{
if (_scaleYEnabled != newValue)
{
_scaleYEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
public var isScaleXEnabled: Bool { return scaleXEnabled; }
public var isScaleYEnabled: Bool { return scaleYEnabled; }
/// flag that indicates if double tap zoom is enabled or not
public var doubleTapToZoomEnabled: Bool
{
get
{
return _doubleTapToZoomEnabled
}
set
{
if (_doubleTapToZoomEnabled != newValue)
{
_doubleTapToZoomEnabled = newValue
_doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled
}
}
}
/// **default**: true
/// - returns: true if zooming via double-tap is enabled false if not.
public var isDoubleTapToZoomEnabled: Bool
{
return doubleTapToZoomEnabled
}
/// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled
public var highlightPerDragEnabled = true
/// If set to true, highlighting per dragging over a fully zoomed out chart is enabled
/// You might want to disable this when using inside a `UIScrollView`
///
/// **default**: true
public var isHighlightPerDragEnabled: Bool
{
return highlightPerDragEnabled
}
/// **default**: true
/// - returns: true if drawing the grid background is enabled, false if not.
public var isDrawGridBackgroundEnabled: Bool
{
return drawGridBackgroundEnabled
}
/// **default**: false
/// - returns: true if drawing the borders rectangle is enabled, false if not.
public var isDrawBordersEnabled: Bool
{
return drawBordersEnabled
}
/// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart.
public func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight?
{
if (_dataNotSet || _data === nil)
{
print("Can't select by touch. No data set.", terminator: "\n")
return nil
}
return _highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y))
}
/// - returns: the x and y values in the chart at the given touch point
/// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to
/// coordinates / values in the chart. This is the opposite method to
/// `getPixelsForValues(...)`.
public func getValueByTouchPoint(var pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint
{
getTransformer(axis).pixelToValue(&pt)
return pt
}
/// Transforms the given chart values into pixels. This is the opposite
/// method to `getValueByTouchPoint(...)`.
public func getPixelForValue(x: Double, y: Double, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var pt = CGPoint(x: CGFloat(x), y: CGFloat(y))
getTransformer(axis).pointValueToPixel(&pt)
return pt
}
/// - returns: the y-value at the given touch position (must not necessarily be
/// a value contained in one of the datasets)
public func getYValueByTouchPoint(pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat
{
return getValueByTouchPoint(pt: pt, axis: axis).y
}
/// - returns: the Entry object displayed at the touched position of the chart
public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry!
{
let h = getHighlightByTouchPoint(pt)
if (h !== nil)
{
return _data!.getEntryForHighlight(h!)
}
return nil
}
/// - returns: the DataSet object displayed at the touched position of the chart
public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleBubbleChartDataSet!
{
let h = getHighlightByTouchPoint(pt)
if (h !== nil)
{
return _data.getDataSetByIndex(h!.dataSetIndex) as! BarLineScatterCandleBubbleChartDataSet!
}
return nil
}
/// - returns: the lowest x-index (value on the x-axis) that is still visible on he chart.
public var lowestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)
getTransformer(.Left).pixelToValue(&pt)
return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0)
}
/// - returns: the highest x-index (value on the x-axis) that is still visible on the chart.
public var highestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)
getTransformer(.Left).pixelToValue(&pt)
return (_data != nil && Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x)
}
/// - returns: the current x-scale factor
public var scaleX: CGFloat
{
if (_viewPortHandler === nil)
{
return 1.0
}
return _viewPortHandler.scaleX
}
/// - returns: the current y-scale factor
public var scaleY: CGFloat
{
if (_viewPortHandler === nil)
{
return 1.0
}
return _viewPortHandler.scaleY
}
/// if the chart is fully zoomed out, return true
public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; }
/// - returns: the left y-axis object. In the horizontal bar-chart, this is the
/// top axis.
public var leftAxis: ChartYAxis
{
return _leftAxis
}
/// - returns: the right y-axis object. In the horizontal bar-chart, this is the
/// bottom axis.
public var rightAxis: ChartYAxis { return _rightAxis; }
/// - returns: the y-axis object to the corresponding AxisDependency. In the
/// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis
{
if (axis == .Left)
{
return _leftAxis
}
else
{
return _rightAxis
}
}
/// - returns: the object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
public var xAxis: ChartXAxis
{
return _xAxis
}
/// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled with 2 fingers, if false, x and y axis can be scaled separately
public var pinchZoomEnabled: Bool
{
get
{
return _pinchZoomEnabled
}
set
{
if (_pinchZoomEnabled != newValue)
{
_pinchZoomEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
/// **default**: false
/// - returns: true if pinch-zoom is enabled, false if not
public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; }
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the x-axis.
public func setDragOffsetX(offset: CGFloat)
{
_viewPortHandler.setDragOffsetX(offset)
}
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the y-axis.
public func setDragOffsetY(offset: CGFloat)
{
_viewPortHandler.setDragOffsetY(offset)
}
/// - returns: true if both drag offsets (x and y) are zero or smaller.
public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; }
/// The X axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of ChartXAxisRenderer
/// - returns: The current set X axis renderer
public var xAxisRenderer: ChartXAxisRenderer
{
get { return _xAxisRenderer }
set { _xAxisRenderer = newValue }
}
/// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of ChartYAxisRenderer
/// - returns: The current set left Y axis renderer
public var leftYAxisRenderer: ChartYAxisRenderer
{
get { return _leftYAxisRenderer }
set { _leftYAxisRenderer = newValue }
}
/// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of ChartYAxisRenderer
/// - returns: The current set right Y axis renderer
public var rightYAxisRenderer: ChartYAxisRenderer
{
get { return _rightYAxisRenderer }
set { _rightYAxisRenderer = newValue }
}
public override var chartYMax: Double
{
return max(leftAxis.axisMaximum, rightAxis.axisMaximum)
}
public override var chartYMin: Double
{
return min(leftAxis.axisMinimum, rightAxis.axisMinimum)
}
/// - returns: true if either the left or the right or both axes are inverted.
public var isAnyAxisInverted: Bool
{
return _leftAxis.isInverted || _rightAxis.isInverted
}
/// flag that indicates if auto scaling on the y axis is enabled.
/// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes
public var autoScaleMinMaxEnabled: Bool
{
get { return _autoScaleMinMaxEnabled; }
set { _autoScaleMinMaxEnabled = newValue; }
}
/// **default**: false
/// - returns: true if auto scaling on the y axis is enabled.
public var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled; }
/// Sets a minimum width to the specified y axis.
public func setYAxisMinWidth(which: ChartYAxis.AxisDependency, width: CGFloat)
{
if (which == .Left)
{
_leftAxis.minWidth = width
}
else
{
_rightAxis.minWidth = width
}
}
/// **default**: 0.0
/// - returns: the (custom) minimum width of the specified Y axis.
public func getYAxisMinWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.minWidth
}
else
{
return _rightAxis.minWidth
}
}
/// Sets a maximum width to the specified y axis.
/// Zero (0.0) means there's no maximum width
public func setYAxisMaxWidth(which: ChartYAxis.AxisDependency, width: CGFloat)
{
if (which == .Left)
{
_leftAxis.maxWidth = width
}
else
{
_rightAxis.maxWidth = width
}
}
/// Zero (0.0) means there's no maximum width
///
/// **default**: 0.0 (no maximum specified)
/// - returns: the (custom) maximum width of the specified Y axis.
public func getYAxisMaxWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.maxWidth
}
else
{
return _rightAxis.maxWidth
}
}
/// - returns the width of the specified y axis.
public func getYAxisWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.requiredSize().width
}
else
{
return _rightAxis.requiredSize().width
}
}
}
/// Default formatter that calculates the position of the filled line.
internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter
{
private weak var _chart: BarLineChartViewBase!
internal init(chart: BarLineChartViewBase)
{
_chart = chart
}
internal func getFillLinePosition(dataSet dataSet: LineChartDataSet, data: LineChartData, chartMaxY: Double, chartMinY: Double) -> CGFloat
{
var fillMin = CGFloat(0.0)
if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0)
{
fillMin = 0.0
}
else
{
if (!_chart.getAxis(dataSet.axisDependency).isStartAtZeroEnabled)
{
var max: Double, min: Double
if (data.yMax > 0.0)
{
max = 0.0
}
else
{
max = chartMaxY
}
if (data.yMin < 0.0)
{
min = 0.0
}
else
{
min = chartMinY
}
fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max)
}
else
{
fillMin = 0.0
}
}
return fillMin
}
}
| ee71262c70269b6447c9513a1f1e34e2 | 35.26337 | 238 | 0.575973 | false | false | false | false |
ITzTravelInTime/TINU | refs/heads/development | TINU/FilesystemObserver.swift | gpl-2.0 | 1 | /*
TINU, the open tool to create bootable macOS installers.
Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime)
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import Foundation
public class FileSystemObserver {
private var fileHandle: CInt?
private var eventSource: DispatchSourceProtocol?
private var observingStarted: Bool = false
private let path: String
private let handler: () -> Void
public var isObserving: Bool{
return fileHandle != nil && eventSource != nil && observingStarted
}
deinit {
stop()
}
public required init(path: String, changeHandler: @escaping ()->Void, startObservationNow: Bool = true) {
assert(!path.isEmpty, "The filesystem object to observe must have a path!")
self.path = path
self.handler = changeHandler
if startObservationNow{
start()
}
}
public convenience init(url: URL, changeHandler: @escaping ()->Void, startObservationNow: Bool = true) {
self.init(path: url.path, changeHandler: { changeHandler() }, startObservationNow: startObservationNow)
}
public func stop() {
self.eventSource?.cancel()
if fileHandle != nil{
close(fileHandle!)
}
self.eventSource = nil
self.fileHandle = nil
self.observingStarted = false
}
public func start() {
if fileHandle != nil || eventSource != nil{
stop()
}
self.fileHandle = open(path, O_EVTONLY)
self.eventSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: self.fileHandle!, eventMask: .all, queue: DispatchQueue.global(qos: .utility))
self.eventSource!.setEventHandler {
self.handler()
}
self.eventSource!.resume()
self.observingStarted = true
}
}
| c6d9233e33b102b996d3ee02953e908f | 26.578313 | 157 | 0.736129 | false | false | false | false |
FlexMonkey/Filterpedia | refs/heads/master | Filterpedia/customFilters/ModelIOGenerators.swift | gpl-3.0 | 1 | //
// ModelIOGenerators.swift
// Filterpedia
//
// Created by Simon Gladman on 25/03/2016.
// Copyright © 2016 Simon Gladman. All rights reserved.
//
import ModelIO
import CoreImage
// MARK: ModelIO Color from Temperature
// See: https://en.wikipedia.org/wiki/Color_temperature
class ModelIOColorFromTemperature: CIFilter
{
var inputSize = CIVector(x: 640, y: 640)
var inputTemperature: CGFloat = 1700
override var outputImage: CIImage!
{
let swatch = MDLColorSwatchTexture(
colorTemperatureGradientFrom: inputTemperature.toFloat(),
toColorTemperature: inputTemperature.toFloat(),
name: "",
textureDimensions: [Int32(inputSize.X), Int32(inputSize.Y)])
let swatchImage = swatch.imageFromTexture()!.takeRetainedValue()
return CIImage(CGImage: swatchImage)
}
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "ModelIO Color From Temperature",
"inputSize": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIVector",
kCIAttributeDisplayName: "Size",
kCIAttributeDefault: CIVector(x: 640, y: 640),
kCIAttributeType: kCIAttributeTypeOffset],
"inputTemperature": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1700,
kCIAttributeDescription: "Black-body color temperature (°K)",
kCIAttributeDisplayName: "Temperature",
kCIAttributeMin: 1500,
kCIAttributeSliderMin: 1500,
kCIAttributeSliderMax: 15000,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
}
// MARK: ModelIO Color Scalar Noise
class ModelIOColorScalarNoise: CIFilter
{
var inputSize = CIVector(x: 640, y: 640)
var inputSmoothness: CGFloat = 0.5
let makeOpaqueKernel = CIColorKernel(string: "kernel vec4 xyz(__sample pixel) { return vec4(pixel.rgb, 1.0); }")
override var outputImage: CIImage!
{
let noise = MDLNoiseTexture(scalarNoiseWithSmoothness: inputSmoothness.toFloat(),
name: "",
textureDimensions: [Int32(inputSize.X), Int32(inputSize.Y)],
channelCount: 4,
channelEncoding: MDLTextureChannelEncoding.UInt8,
grayscale: false)
let noiseImage = noise.imageFromTexture()!.takeRetainedValue()
let final = CIImage(CGImage: noiseImage)
return makeOpaqueKernel?.applyWithExtent(final.extent, arguments: [final])
}
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "ModelIO Color Scalar Noise",
"inputSize": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIVector",
kCIAttributeDisplayName: "Size",
kCIAttributeDefault: CIVector(x: 640, y: 640),
kCIAttributeType: kCIAttributeTypeOffset],
"inputSmoothness": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.5,
kCIAttributeDisplayName: "Smoothness",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
}
// MARK: ModelIO Sky Generator
class ModelIOSkyGenerator: CIFilter
{
var inputSize = CIVector(x: 640, y: 640)
{
didSet
{
sky = nil
}
}
var inputTurbidity:CGFloat = 0.75
var inputSunElevation: CGFloat = 0.70
var inputUpperAtmosphereScattering: CGFloat = 0.2
var inputGroundAlbedo: CGFloat = 0.5
var inputContrast: CGFloat = 1
var inputExposure: CGFloat = 0.5
var inputSaturation: CGFloat = 0.0
var sky: MDLSkyCubeTexture?
override var outputImage: CIImage!
{
if let sky = sky
{
sky.turbidity = inputTurbidity.toFloat()
sky.sunElevation = inputSunElevation.toFloat()
sky.upperAtmosphereScattering = inputUpperAtmosphereScattering.toFloat()
sky.groundAlbedo = inputGroundAlbedo.toFloat()
}
else
{
sky = MDLSkyCubeTexture(name: nil,
channelEncoding: MDLTextureChannelEncoding.UInt8,
textureDimensions: [Int32(inputSize.X), Int32(inputSize.Y)],
turbidity: inputTurbidity.toFloat(),
sunElevation: inputSunElevation.toFloat(),
upperAtmosphereScattering: inputUpperAtmosphereScattering.toFloat(),
groundAlbedo: inputGroundAlbedo.toFloat())
}
sky!.contrast = inputContrast.toFloat()
sky!.exposure = inputExposure.toFloat()
sky!.saturation = inputSaturation.toFloat()
sky!.updateTexture()
let skyImage = sky!.imageFromTexture()!.takeRetainedValue()
return CIImage(CGImage: skyImage)
.imageByCroppingToRect(CGRect(x: 0, y: 0, width: inputSize.X, height: inputSize.Y))
}
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "ModelIO Sky Generator",
"inputSize": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIVector",
kCIAttributeDisplayName: "Size",
kCIAttributeDefault: CIVector(x: 640, y: 640),
kCIAttributeType: kCIAttributeTypeOffset],
"inputTurbidity": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.75,
kCIAttributeDisplayName: "Turbidity",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputSunElevation": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.75,
kCIAttributeDisplayName: "Sun Elevation",
kCIAttributeMin: 0.5,
kCIAttributeSliderMin: 0.5,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputUpperAtmosphereScattering": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.2,
kCIAttributeDisplayName: "Upper Atmosphere Scattering",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputGroundAlbedo": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.5,
kCIAttributeDisplayName: "Ground Albedo",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputContrast": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Contrast",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 2,
kCIAttributeType: kCIAttributeTypeScalar],
"inputExposure": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.5,
kCIAttributeDisplayName: "Exposure",
kCIAttributeMin: 0,
kCIAttributeSliderMin: -1,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputSaturation": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.5,
kCIAttributeDisplayName: "Saturation",
kCIAttributeMin: 0,
kCIAttributeSliderMin: -2,
kCIAttributeSliderMax: 2,
kCIAttributeType: kCIAttributeTypeScalar],
]
}
}
| 2f7f7a3ef0f9198947c9379dd2b0fb85 | 35.212766 | 116 | 0.586486 | false | false | false | false |
Noirozr/UIColorExtension | refs/heads/master | nipponColor.swift | mit | 1 | //
// nipponColor.swift
// Surf
//
// Created by Noirozr on 15/3/26.
// Copyright (c) 2015年 Yongjia Liu. All rights reserved.
//
import UIKit
//http://nipponcolors.com
extension UIColor {
class func MOMOColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 245.0/255.0, green: 150.0/255.0, blue: 170.0/255.0, alpha: alpha)
}
class func KUWAZOMEColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 100.0/255.0, green: 54.0/255.0, blue: 60.0/255.0, alpha: alpha)
}
class func IKKONZOMEColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 244.0/255.0, green: 167.0/255.0, blue: 185.0/255.0, alpha: alpha)
}
class func TAIKOHColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 248.0/255.0, green: 195.0/255.0, blue: 205.0/255.0, alpha: alpha)
}
class func SUOHColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 142.0/255.0, green: 53.0/255.0, blue: 74.0/255.0, alpha: alpha)
}
class func KOHBAIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 225.0/255.0, green: 107.0/255.0, blue: 140.0/255.0, alpha: alpha)
}
class func NADESHIKOColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 220.0/255.0, green: 159.0/255.0, blue: 180.0/255.0, alpha: alpha)
}
class func KARAKURENAIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 208.0/255.0, green: 16.0/255.0, blue: 76.0/255.0, alpha: alpha)
}
class func UMENEZUMIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 158.0/255.0, green: 122.0/255.0, blue: 122.0/255.0, alpha: alpha)
}
class func SAKURAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 254.0/255.0, green: 223.0/255.0, blue: 225.0/255.0, alpha: alpha)
}
class func NAKABENIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 219.0/255.0, green: 77.0/255.0, blue: 109.0/255.0, alpha: alpha)
}
class func IMAYOHColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 208.0/255.0, green: 90.0/255.0, blue: 110.0/255.0, alpha: alpha)
}
class func USUBENIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 232.0/255.0, green: 122.0/255.0, blue: 144.0/255.0, alpha: alpha)
}
class func ICHIGOColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 181.0/255.0, green: 73.0/255.0, blue: 91.0/255.0, alpha: alpha)
}
class func JINZAMOMIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 235.0/255.0, green: 122.0/255.0, blue: 119.0/255.0, alpha: alpha)
}
class func SAKURANEZUMIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 177.0/255.0, green: 150.0/255.0, blue: 147.0/255.0, alpha: alpha)
}
class func KOKIAKEColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 134.0/255.0, green: 71.0/255.0, blue: 63.0/255.0, alpha: alpha)
}
class func CYOHSYUNColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 191.0/255.0, green: 103.0/255.0, blue: 102.0/255.0, alpha: alpha)
}
class func TOKIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 238.0/255.0, green: 169.0/255.0, blue: 169.0/255.0, alpha: alpha)
}
class func KURENAIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 203.0/255.0, green: 27.0/255.0, blue: 69.0/255.0, alpha: alpha)
}
class func ENJIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 159.0/255.0, green: 53.0/255.0, blue: 58.0/255.0, alpha: alpha)
}
class func EBICHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 115.0/255.0, green: 67.0/255.0, blue: 56.0/255.0, alpha: alpha)
}
class func KURIUMEColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 144.0/255.0, green: 72.0/255.0, blue: 64.0/255.0, alpha: alpha)
}
class func HAIZAKURAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 215.0/255.0, green: 196.0/255.0, blue: 187.0/255.0, alpha: alpha)
}
class func SHINSYUColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 171.0/255.0, green: 59.0/255.0, blue: 58.0/255.0, alpha: alpha)
}
class func AKABENIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 203.0/255.0, green: 64.0/255.0, blue: 66.0/255.0, alpha: alpha)
}
class func SUOHKOHColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 169.0/255.0, green: 99.0/255.0, blue: 96.0/255.0, alpha: alpha)
}
class func AZUKIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 149.0/255.0, green: 74.0/255.0, blue: 69.0/255.0, alpha: alpha)
}
class func SANGOSYUColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 241.0/255.0, green: 124.0/255.0, blue: 103.0/255.0, alpha: alpha)
}
class func MIZUGAKIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 185.0/255.0, green: 136.0/255.0, blue: 125.0/255.0, alpha: alpha)
}
class func BENIKABAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 181.0/255.0, green: 68.0/255.0, blue: 52.0/255.0, alpha: alpha)
}
class func AKEBONOColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 241.0/255.0, green: 148.0/255.0, blue: 131.0/255.0, alpha: alpha)
}
class func BENITOBIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 153.0/255.0, green: 70.0/255.0, blue: 57.0/255.0, alpha: alpha)
}
class func KUROTOBIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 85.0/255.0, green: 66.0/255.0, blue: 54.0/255.0, alpha: alpha)
}
class func GINSYUColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 199.0/255.0, green: 62.0/255.0, blue: 58.0/255.0, alpha: alpha)
}
class func AKEColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 204.0/255.0, green: 84.0/255.0, blue: 58.0/255.0, alpha: alpha)
}
class func KAKISHIBUColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 163.0/255.0, green: 94.0/255.0, blue: 71.0/255.0, alpha: alpha)
}
class func HIWADAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 133.0/255.0, green: 72.0/255.0, blue: 54.0/255.0, alpha: alpha)
}
class func SHIKANCHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 181.0/255.0, green: 93.0/255.0, blue: 76.0/255.0, alpha: alpha)
}
class func ENTANColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 215.0/255.0, green: 84.0/255.0, blue: 85.0/255.0, alpha: alpha)
}
class func SYOJYOHIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 232.0/255.0, green: 48.0/255.0, blue: 21.0/255.0, alpha: alpha)
}
class func BENIHIWADAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 136.0/255.0, green: 76.0/255.0, blue: 58.0/255.0, alpha: alpha)
}
class func ARAISYUColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 251.0/255.0, green: 150.0/255.0, blue: 110.0/255.0, alpha: alpha)
}
class func EDOCHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 175.0/255.0, green: 95.0/255.0, blue: 60.0/255.0, alpha: alpha)
}
class func TERIGAKIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 196.0/255.0, green: 98.0/255.0, blue: 67.0/255.0, alpha: alpha)
}
class func BENGARAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 154.0/255.0, green: 80.0/255.0, blue: 52.0/255.0, alpha: alpha)
}
class func KURIKAWACHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 106.0/255.0, green: 64.0/255.0, blue: 40.0/255.0, alpha: alpha)
}
class func BENIHIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 247.0/255.0, green: 92.0/255.0, blue: 47.0/255.0, alpha: alpha)
}
class func TOBIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 114.0/255.0, green: 72.0/255.0, blue: 50.0/255.0, alpha: alpha)
}
class func KABACHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 179.0/255.0, green: 92.0/255.0, blue: 55.0/255.0, alpha: alpha)
}
class func ENSYUCHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 202.0/255.0, green: 120.0/255.0, blue: 83.0/255.0, alpha: alpha)
}
class func SOHIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 237.0/255.0, green: 120.0/255.0, blue: 74.0/255.0, alpha: alpha)
}
class func OHNIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 240.0/255.0, green: 94.0/255.0, blue: 28.0/255.0, alpha: alpha)
}
class func TOKIGARACHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 219.0/255.0, green: 142.0/255.0, blue: 113.0/255.0, alpha: alpha)
}
class func KARACHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 180.0/255.0, green: 113.0/255.0, blue: 87.0/255.0, alpha: alpha)
}
class func MOMOSHIOCHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 114.0/255.0, green: 73.0/255.0, blue: 56.0/255.0, alpha: alpha)
}
class func KOKIKUCHINASHIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 251.0/255.0, green: 153.0/255.0, blue: 102.0/255.0, alpha: alpha)
}
class func KABAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 193.0/255.0, green: 105.0/255.0, blue: 60.0/255.0, alpha: alpha)
}
class func SODENKARACHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 160.0/255.0, green: 103.0/255.0, blue: 75.0/255.0, alpha: alpha)
}
class func SHISHIColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 240.0/255.0, green: 169.0/255.0, blue: 134.0/255.0, alpha: alpha)
}
class func SUZUMECHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 143.0/255.0, green: 90.0/255.0, blue: 60.0/255.0, alpha: alpha)
}
class func AKAKOHColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 227.0/255.0, green: 145.0/255.0, blue: 110.0/255.0, alpha: alpha)
}
class func KOGECHAColor(alpha: CGFloat = 1.0) -> UIColor {
return UIColor.init(red: 86.0/255.0, green: 68.0/255.0, blue: 46.0/255.0, alpha: alpha)
}
}
| 87901e2a86e49087b76196f58c6a411e | 40.348315 | 98 | 0.605616 | false | false | false | false |
velvetroom/columbus | refs/heads/master | Source/View/CreateSearch/VCreateSearchBaseListCell.swift | mit | 1 | import MapKit
final class VCreateSearchBaseListCell:UICollectionViewCell
{
private weak var label:UILabel!
let attributesTitle:[NSAttributedStringKey:Any]
let attributesTitleHighlighted:[NSAttributedStringKey:Any]
let attributesSubtitle:[NSAttributedStringKey:Any]
let attributesSubtitleHighlighted:[NSAttributedStringKey:Any]
let breakLine:NSAttributedString
private var text:NSAttributedString?
override init(frame:CGRect)
{
let colourLabelTitle:UIColor = UIColor(white:0, alpha:0.7)
let colourLabelSubtitle:UIColor = UIColor(white:0, alpha:0.4)
let colourLabelHighlighted:UIColor = UIColor.colourBackgroundDark
attributesTitle = [
NSAttributedStringKey.font : UIFont.regular(size:VCreateSearchBaseListCell.Constants.titleFontSize),
NSAttributedStringKey.foregroundColor : colourLabelTitle]
attributesTitleHighlighted = [
NSAttributedStringKey.font : UIFont.bold(size:VCreateSearchBaseListCell.Constants.titleFontSize),
NSAttributedStringKey.foregroundColor : colourLabelHighlighted]
attributesSubtitle = [
NSAttributedStringKey.font : UIFont.regular(size:VCreateSearchBaseListCell.Constants.subtitleFontSize),
NSAttributedStringKey.foregroundColor : colourLabelSubtitle]
attributesSubtitleHighlighted = [
NSAttributedStringKey.font : UIFont.medium(size:VCreateSearchBaseListCell.Constants.subtitleFontSize),
NSAttributedStringKey.foregroundColor : colourLabelHighlighted]
breakLine = NSAttributedString(string:"\n")
super.init(frame:frame)
clipsToBounds = true
let label:UILabel = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.isUserInteractionEnabled = false
label.numberOfLines = 0
self.label = label
addSubview(label)
NSLayoutConstraint.topToTop(
view:label,
toView:self,
constant:VCreateSearchBaseListCell.Constants.marginTop)
NSLayoutConstraint.heightGreaterOrEqual(
view:label)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self,
margin:VCreateSearchBaseListCell.Constants.marginHorizontal)
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
backgroundColor = UIColor.colourSuccess
label.textColor = UIColor.white
}
else
{
backgroundColor = UIColor.white
label.attributedText = text
}
}
//MARK: internal
func config(model:MKLocalSearchCompletion)
{
text = factoryText(model:model)
hover()
}
}
| 7824b64fe4d409f4a31f6465b249a938 | 29.6 | 115 | 0.641457 | false | false | false | false |
hulinSun/MyRx | refs/heads/master | MyRx/MyRx/Classes/Core/Category/Response+HandyJSON.swift | mit | 1 |
// Response+HandyJSON.swift
// MyRx
//
// Created by Hony on 2016/12/29.
// Copyright © 2016年 Hony. All rights reserved.
//
import Foundation
import Moya
import HandyJSON
public extension Response {
/// 整个 Data Model
public func mapObject<T: HandyJSON>(_ type: T.Type) -> T? {
guard let dataString = String.init(data: self.data, encoding: .utf8),
let object = JSONDeserializer<T>.deserializeFrom(json: dataString)
else {
return nil
}
return object
}
/// 制定的某个 Key 对应的模型
public func mapObject<T: HandyJSON>(_ type: T.Type ,designatedPath: String) -> T?{
guard let dataString = String(data: self.data, encoding: .utf8),
let object = JSONDeserializer<T>.deserializeFrom(json: dataString, designatedPath: designatedPath)
else {
return nil
}
return object
}
/// Data 对应的 [Model]
public func mapArray<T: HandyJSON>(_ type: T.Type) -> [T?]? {
guard let dataString = String(data: self.data, encoding: .utf8),
let object = JSONDeserializer<T>.deserializeModelArrayFrom(json: dataString)
else {
return nil
}
return object
}
/// Data 某个Key 下对应的 的 [Model]
public func mapArray<T: HandyJSON>(_ type: T.Type ,designatedPath: String ) -> [T?]? {
guard let dataString = String(data: self.data, encoding: .utf8),
let object = JSONDeserializer<T>.deserializeModelArrayFrom(json: dataString , designatedPath: designatedPath)
else {
return nil
}
return object
}
}
| 7711f1af0388c0642a6edf6a77028ba2 | 24.761194 | 121 | 0.573001 | false | false | false | false |
sessionm/ios-swift-sdk-example | refs/heads/master | swift-3/complete/ios-swift-sdk-example/achievements/custom/AchievementViewController.swift | mit | 1 | //
// AchievementViewController.swift
// ios-swift-sdk-example
//
// Copyright © 2016 SessionM. All rights reserved.
//
import UIKit
open class AchievementViewController: UIViewController {
@IBOutlet weak var achievementIcon: UIImageView!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var pointsLabel: UILabel!
var _achievement : SMAchievementData?;
var _achievementActivity : SMAchievementActivity?;
open var achievement : SMAchievementData? {
set {
_achievement = newValue;
if let achieveData = _achievement {
_achievementActivity = SMAchievementActivity(data: achieveData);
if let achieve = _achievementActivity {
achieve.notifyPresented();
}
showAchieve(achieveData);
}
}
get { return nil; }
};
func showAchieve(_ achievement : SMAchievementData) {
messageLabel.text = achievement.message;
nameLabel.text = achievement.name;
pointsLabel.text = "\(achievement.pointValue)";
if let url = achievement.achievementIconURL {
loadFromUrl(url) { (image : UIImage?) in
if let draw = image {
self.achievementIcon.image = draw;
}
}
}
}
@IBAction func onClaim(_ sender: UIButton) {
self.presentingViewController!.dismiss(animated: true, completion: {
if let achieve = self._achievementActivity {
achieve.notifyDismissed(dismissType: .claimed);
}
});
}
@IBAction func onCancel(_ sender: UIButton) {
if let achieve = _achievementActivity {
achieve.notifyDismissed(dismissType: .canceled);
}
self.presentingViewController?.dismiss(animated: true, completion: nil);
}
// Not optimal, but gets URL load off UI Thread
func loadFromUrl(_ url : String, callback : @escaping ((UIImage?) -> Void)) {
let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated);
queue.async {
if let imageData = try? Data(contentsOf: URL(string: url)!) {
let image = UIImage(data: imageData);
DispatchQueue.main.async(execute: {
callback(image);
});
}
}
}
}
| b685e025e06a25a6b400855799b5558a | 30.649351 | 82 | 0.589249 | false | false | false | false |
CodaFi/swift | refs/heads/main | benchmark/single-source/Memset.swift | apache-2.0 | 34 | //===--- Memset.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let Memset = BenchmarkInfo(
name: "Memset",
runFunction: run_Memset,
tags: [.validation])
@inline(never)
func memset(_ a: inout [Int], _ c: Int) {
for i in 0..<a.count {
a[i] = c
}
}
@inline(never)
public func run_Memset(_ N: Int) {
var a = [Int](repeating: 0, count: 10_000)
for _ in 1...50*N {
memset(&a, 1)
memset(&a, 0)
}
CheckResults(a[87] == 0)
}
| 6ca2ad629bf5b5bb9115bb5695767c06 | 25.6 | 80 | 0.555317 | false | false | false | false |
mkoehnke/WKZombie | refs/heads/master | Sources/WKZombie/Parser.swift | mit | 1 | //
// Parser.swift
//
// Copyright (c) 2015 Mathias Koehnke (http://www.mathiaskoehnke.de)
//
// 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 hpple
/// Base class for the HTMLParser and JSONParser.
public class Parser : CustomStringConvertible {
/// The URL of the page.
public fileprivate(set) var url : URL?
/**
Returns a (HTML or JSON) parser instance for the specified data.
- parameter data: The encoded data.
- parameter url: The URL of the page.
- returns: A HTML or JSON page.
*/
required public init(data: Data, url: URL? = nil) {
self.url = url
}
public var description: String {
return "\(type(of: self))"
}
}
//========================================
// MARK: HTML
//========================================
/// A HTML Parser class, which wraps the functionality of the TFHpple class.
public class HTMLParser : Parser {
fileprivate var doc : TFHpple?
required public init(data: Data, url: URL? = nil) {
super.init(data: data, url: url)
self.doc = TFHpple(htmlData: data)
}
public func searchWithXPathQuery(_ xPathOrCSS: String) -> [AnyObject]? {
return doc?.search(withXPathQuery: xPathOrCSS) as [AnyObject]?
}
public var data: Data? {
return doc?.data
}
override public var description: String {
return (NSString(data: doc?.data ?? Data(), encoding: String.Encoding.utf8.rawValue) ?? "") as String
}
}
/// A HTML Parser Element class, which wraps the functionality of the TFHppleElement class.
public class HTMLParserElement : CustomStringConvertible {
fileprivate var element : TFHppleElement?
public internal(set) var XPathQuery : String?
required public init?(element: AnyObject, XPathQuery : String? = nil) {
if let element = element as? TFHppleElement {
self.element = element
self.XPathQuery = XPathQuery
} else {
return nil
}
}
public var innerContent : String? {
return element?.raw as String?
}
public var text : String? {
return element?.text() as String?
}
public var content : String? {
return element?.content as String?
}
public var tagName : String? {
return element?.tagName as String?
}
public func objectForKey(_ key: String) -> String? {
return element?.object(forKey: key.lowercased()) as String?
}
public func childrenWithTagName<T: HTMLElement>(_ tagName: String) -> [T]? {
return element?.children(withTagName: tagName).flatMap { T(element: $0 as AnyObject) }
}
public func children<T: HTMLElement>() -> [T]? {
return element?.children.flatMap { T(element:$0 as AnyObject) }
}
public func hasChildren() -> Bool {
return element?.hasChildren() ?? false
}
public var description : String {
return element?.raw ?? ""
}
}
//========================================
// MARK: JSON
//========================================
/// A JSON Parser class, which represents a JSON document.
public class JSONParser : Parser {
fileprivate var json : JSON?
required public init(data: Data, url: URL? = nil) {
super.init(data: data, url: url)
let result : Result<JSON> = parseJSON(data)
switch result {
case .success(let json): self.json = json
case .error: Logger.log("Error parsing JSON!")
}
}
public func content() -> JSON? {
return json
}
override public var description : String {
return "\(String(describing: json))"
}
}
| b1a0a828c6893aac746f08e5ad231fdb | 29.490446 | 109 | 0.618968 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | stdlib/public/SDK/Foundation/JSONEncoder.swift | apache-2.0 | 3 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// JSON Encoder
//===----------------------------------------------------------------------===//
/// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON.
open class JSONEncoder {
// MARK: Options
/// The formatting of the output JSON data.
public struct OutputFormatting : OptionSet {
/// The format's default value.
public let rawValue: UInt
/// Creates an OutputFormatting value with the given raw value.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
/// Produce human-readable JSON with indented output.
public static let prettyPrinted = OutputFormatting(rawValue: 1 << 0)
/// Produce JSON with dictionary keys sorted in lexicographic order.
@available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
public static let sortedKeys = OutputFormatting(rawValue: 1 << 1)
}
/// The strategy to use for encoding `Date` values.
public enum DateEncodingStrategy {
/// Defer to `Date` for choosing an encoding. This is the default strategy.
case deferredToDate
/// Encode the `Date` as a UNIX timestamp (as a JSON number).
case secondsSince1970
/// Encode the `Date` as UNIX millisecond timestamp (as a JSON number).
case millisecondsSince1970
/// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Encode the `Date` as a string formatted by the given formatter.
case formatted(DateFormatter)
/// Encode the `Date` as a custom value encoded by the given closure.
///
/// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place.
case custom((Date, Encoder) throws -> Void)
}
/// The strategy to use for encoding `Data` values.
public enum DataEncodingStrategy {
/// Defer to `Data` for choosing an encoding.
case deferredToData
/// Encoded the `Data` as a Base64-encoded string. This is the default strategy.
case base64
/// Encode the `Data` as a custom value encoded by the given closure.
///
/// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place.
case custom((Data, Encoder) throws -> Void)
}
/// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN).
public enum NonConformingFloatEncodingStrategy {
/// Throw upon encountering non-conforming values. This is the default strategy.
case `throw`
/// Encode the values using the given representation strings.
case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String)
}
/// The output format to produce. Defaults to `[]`.
open var outputFormatting: OutputFormatting = []
/// The strategy to use in encoding dates. Defaults to `.deferredToDate`.
open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate
/// The strategy to use in encoding binary data. Defaults to `.base64`.
open var dataEncodingStrategy: DataEncodingStrategy = .base64
/// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`.
open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw
/// Contextual user-provided information for use during encoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the encoding hierarchy.
fileprivate struct _Options {
let dateEncodingStrategy: DateEncodingStrategy
let dataEncodingStrategy: DataEncodingStrategy
let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level encoder.
fileprivate var options: _Options {
return _Options(dateEncodingStrategy: dateEncodingStrategy,
dataEncodingStrategy: dataEncodingStrategy,
nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy,
userInfo: userInfo)
}
// MARK: - Constructing a JSON Encoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Encoding Values
/// Encodes the given top-level value and returns its JSON representation.
///
/// - parameter value: The value to encode.
/// - returns: A new `Data` value containing the encoded JSON data.
/// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
/// - throws: An error if any value throws an error during encoding.
open func encode<T : Encodable>(_ value: T) throws -> Data {
let encoder = _JSONEncoder(options: self.options)
guard let topLevel = try encoder.box_(value) else {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values."))
}
if topLevel is NSNull {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as null JSON fragment."))
} else if topLevel is NSNumber {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as number JSON fragment."))
} else if topLevel is NSString {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as string JSON fragment."))
}
let writingOptions = JSONSerialization.WritingOptions(rawValue: self.outputFormatting.rawValue)
do {
return try JSONSerialization.data(withJSONObject: topLevel, options: writingOptions)
} catch {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Unable to encode the given top-level value to JSON.", underlyingError: error))
}
}
}
// MARK: - _JSONEncoder
fileprivate class _JSONEncoder : Encoder {
// MARK: Properties
/// The encoder's storage.
fileprivate var storage: _JSONEncodingStorage
/// Options set on the top-level encoder.
fileprivate let options: JSONEncoder._Options
/// The path to the current point in encoding.
public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level encoder options.
fileprivate init(options: JSONEncoder._Options, codingPath: [CodingKey] = []) {
self.options = options
self.storage = _JSONEncodingStorage()
self.codingPath = codingPath
}
/// Returns whether a new element can be encoded at this coding path.
///
/// `true` if an element has not yet been encoded at this coding path; `false` otherwise.
fileprivate var canEncodeNewValue: Bool {
// Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container).
// At the same time, every time a container is requested, a new value gets pushed onto the storage stack.
// If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition.
//
// This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path.
// Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here).
return self.storage.count == self.codingPath.count
}
// MARK: - Encoder Methods
public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> {
// If an existing keyed container was already requested, return that one.
let topContainer: NSMutableDictionary
if self.canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = self.storage.pushKeyedContainer()
} else {
guard let container = self.storage.containers.last as? NSMutableDictionary else {
preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.")
}
topContainer = container
}
let container = _JSONKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
return KeyedEncodingContainer(container)
}
public func unkeyedContainer() -> UnkeyedEncodingContainer {
// If an existing unkeyed container was already requested, return that one.
let topContainer: NSMutableArray
if self.canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = self.storage.pushUnkeyedContainer()
} else {
guard let container = self.storage.containers.last as? NSMutableArray else {
preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.")
}
topContainer = container
}
return _JSONUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
}
public func singleValueContainer() -> SingleValueEncodingContainer {
return self
}
}
// MARK: - Encoding Storage and Containers
fileprivate struct _JSONEncodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the JSON types (NSNull, NSNumber, NSString, NSArray, NSDictionary).
private(set) fileprivate var containers: [NSObject] = []
// MARK: - Initialization
/// Initializes `self` with no containers.
fileprivate init() {}
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary {
let dictionary = NSMutableDictionary()
self.containers.append(dictionary)
return dictionary
}
fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray {
let array = NSMutableArray()
self.containers.append(array)
return array
}
fileprivate mutating func push(container: NSObject) {
self.containers.append(container)
}
fileprivate mutating func popContainer() -> NSObject {
precondition(self.containers.count > 0, "Empty container stack.")
return self.containers.popLast()!
}
}
// MARK: - Encoding Containers
fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the encoder we're writing to.
private let encoder: _JSONEncoder
/// A reference to the container we're writing to.
private let container: NSMutableDictionary
/// The path of coding keys taken to get to this point in encoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` with the given references.
fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
// MARK: - KeyedEncodingContainerProtocol Methods
public mutating func encodeNil(forKey key: Key) throws { self.container[key.stringValue] = NSNull() }
public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: String, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Float, forKey key: Key) throws {
// Since the float may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[key.stringValue] = try self.encoder.box(value)
}
public mutating func encode(_ value: Double, forKey key: Key) throws {
// Since the double may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[key.stringValue] = try self.encoder.box(value)
}
public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[key.stringValue] = try self.encoder.box(value)
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
let dictionary = NSMutableDictionary()
self.container[key.stringValue] = dictionary
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
let array = NSMutableArray()
self.container[key.stringValue] = array
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
}
public mutating func superEncoder() -> Encoder {
return _JSONReferencingEncoder(referencing: self.encoder, at: _JSONKey.super, wrapping: self.container)
}
public mutating func superEncoder(forKey key: Key) -> Encoder {
return _JSONReferencingEncoder(referencing: self.encoder, at: key, wrapping: self.container)
}
}
fileprivate struct _JSONUnkeyedEncodingContainer : UnkeyedEncodingContainer {
// MARK: Properties
/// A reference to the encoder we're writing to.
private let encoder: _JSONEncoder
/// A reference to the container we're writing to.
private let container: NSMutableArray
/// The path of coding keys taken to get to this point in encoding.
private(set) public var codingPath: [CodingKey]
/// The number of elements encoded into the container.
public var count: Int {
return self.container.count
}
// MARK: - Initialization
/// Initializes `self` with the given references.
fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
// MARK: - UnkeyedEncodingContainer Methods
public mutating func encodeNil() throws { self.container.add(NSNull()) }
public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Float) throws {
// Since the float may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(_JSONKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func encode(_ value: Double) throws {
// Since the double may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(_JSONKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func encode<T : Encodable>(_ value: T) throws {
self.encoder.codingPath.append(_JSONKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> {
self.codingPath.append(_JSONKey(index: self.count))
defer { self.codingPath.removeLast() }
let dictionary = NSMutableDictionary()
self.container.add(dictionary)
let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
self.codingPath.append(_JSONKey(index: self.count))
defer { self.codingPath.removeLast() }
let array = NSMutableArray()
self.container.add(array)
return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
}
public mutating func superEncoder() -> Encoder {
return _JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container)
}
}
extension _JSONEncoder : SingleValueEncodingContainer {
// MARK: - SingleValueEncodingContainer Methods
fileprivate func assertCanEncodeNewValue() {
precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.")
}
public func encodeNil() throws {
assertCanEncodeNewValue()
self.storage.push(container: NSNull())
}
public func encode(_ value: Bool) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int8) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int16) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int32) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int64) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt8) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt16) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt32) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt64) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: String) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Float) throws {
assertCanEncodeNewValue()
try self.storage.push(container: self.box(value))
}
public func encode(_ value: Double) throws {
assertCanEncodeNewValue()
try self.storage.push(container: self.box(value))
}
public func encode<T : Encodable>(_ value: T) throws {
assertCanEncodeNewValue()
try self.storage.push(container: self.box(value))
}
}
// MARK: - Concrete Value Representations
extension _JSONEncoder {
/// Returns the given value boxed in a container appropriate for pushing onto the container stack.
fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) }
fileprivate func box(_ float: Float) throws -> NSObject {
guard !float.isInfinite && !float.isNaN else {
guard case let .convertToString(positiveInfinity: posInfString,
negativeInfinity: negInfString,
nan: nanString) = self.options.nonConformingFloatEncodingStrategy else {
throw EncodingError._invalidFloatingPointValue(float, at: codingPath)
}
if float == Float.infinity {
return NSString(string: posInfString)
} else if float == -Float.infinity {
return NSString(string: negInfString)
} else {
return NSString(string: nanString)
}
}
return NSNumber(value: float)
}
fileprivate func box(_ double: Double) throws -> NSObject {
guard !double.isInfinite && !double.isNaN else {
guard case let .convertToString(positiveInfinity: posInfString,
negativeInfinity: negInfString,
nan: nanString) = self.options.nonConformingFloatEncodingStrategy else {
throw EncodingError._invalidFloatingPointValue(double, at: codingPath)
}
if double == Double.infinity {
return NSString(string: posInfString)
} else if double == -Double.infinity {
return NSString(string: negInfString)
} else {
return NSString(string: nanString)
}
}
return NSNumber(value: double)
}
fileprivate func box(_ date: Date) throws -> NSObject {
switch self.options.dateEncodingStrategy {
case .deferredToDate:
// Must be called with a surrounding with(pushedKey:) call.
try date.encode(to: self)
return self.storage.popContainer()
case .secondsSince1970:
return NSNumber(value: date.timeIntervalSince1970)
case .millisecondsSince1970:
return NSNumber(value: 1000.0 * date.timeIntervalSince1970)
case .iso8601:
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return NSString(string: _iso8601Formatter.string(from: date))
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case .formatted(let formatter):
return NSString(string: formatter.string(from: date))
case .custom(let closure):
let depth = self.storage.count
try closure(date, self)
guard self.storage.count > depth else {
// The closure didn't encode anything. Return the default keyed container.
return NSDictionary()
}
// We can pop because the closure encoded something.
return self.storage.popContainer()
}
}
fileprivate func box(_ data: Data) throws -> NSObject {
switch self.options.dataEncodingStrategy {
case .deferredToData:
// Must be called with a surrounding with(pushedKey:) call.
try data.encode(to: self)
return self.storage.popContainer()
case .base64:
return NSString(string: data.base64EncodedString())
case .custom(let closure):
let depth = self.storage.count
try closure(data, self)
guard self.storage.count > depth else {
// The closure didn't encode anything. Return the default keyed container.
return NSDictionary()
}
// We can pop because the closure encoded something.
return self.storage.popContainer()
}
}
fileprivate func box<T : Encodable>(_ value: T) throws -> NSObject {
return try self.box_(value) ?? NSDictionary()
}
// This method is called "box_" instead of "box" to disambiguate it from the overloads. Because the return type here is different from all of the "box" overloads (and is more general), any "box" calls in here would call back into "box" recursively instead of calling the appropriate overload, which is not what we want.
fileprivate func box_<T : Encodable>(_ value: T) throws -> NSObject? {
if T.self == Date.self || T.self == NSDate.self {
// Respect Date encoding strategy
return try self.box((value as! Date))
} else if T.self == Data.self || T.self == NSData.self {
// Respect Data encoding strategy
return try self.box((value as! Data))
} else if T.self == URL.self || T.self == NSURL.self {
// Encode URLs as single strings.
return self.box((value as! URL).absoluteString)
} else if T.self == Decimal.self || T.self == NSDecimalNumber.self {
// JSONSerialization can natively handle NSDecimalNumber.
return (value as! NSDecimalNumber)
}
// The value should request a container from the _JSONEncoder.
let depth = self.storage.count
try value.encode(to: self)
// The top container should be a new container.
guard self.storage.count > depth else {
return nil
}
return self.storage.popContainer()
}
}
// MARK: - _JSONReferencingEncoder
/// _JSONReferencingEncoder is a special subclass of _JSONEncoder which has its own storage, but references the contents of a different encoder.
/// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container).
fileprivate class _JSONReferencingEncoder : _JSONEncoder {
// MARK: Reference types.
/// The type of container we're referencing.
private enum Reference {
/// Referencing a specific index in an array container.
case array(NSMutableArray, Int)
/// Referencing a specific key in a dictionary container.
case dictionary(NSMutableDictionary, String)
}
// MARK: - Properties
/// The encoder we're referencing.
fileprivate let encoder: _JSONEncoder
/// The container reference itself.
private let reference: Reference
// MARK: - Initialization
/// Initializes `self` by referencing the given array container in the given encoder.
fileprivate init(referencing encoder: _JSONEncoder, at index: Int, wrapping array: NSMutableArray) {
self.encoder = encoder
self.reference = .array(array, index)
super.init(options: encoder.options, codingPath: encoder.codingPath)
self.codingPath.append(_JSONKey(index: index))
}
/// Initializes `self` by referencing the given dictionary container in the given encoder.
fileprivate init(referencing encoder: _JSONEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) {
self.encoder = encoder
self.reference = .dictionary(dictionary, key.stringValue)
super.init(options: encoder.options, codingPath: encoder.codingPath)
self.codingPath.append(key)
}
// MARK: - Coding Path Operations
fileprivate override var canEncodeNewValue: Bool {
// With a regular encoder, the storage and coding path grow together.
// A referencing encoder, however, inherits its parents coding path, as well as the key it was created for.
// We have to take this into account.
return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1
}
// MARK: - Deinitialization
// Finalizes `self` by writing the contents of our storage to the referenced encoder's storage.
deinit {
let value: Any
switch self.storage.count {
case 0: value = NSDictionary()
case 1: value = self.storage.popContainer()
default: fatalError("Referencing encoder deallocated with multiple containers on stack.")
}
switch self.reference {
case .array(let array, let index):
array.insert(value, at: index)
case .dictionary(let dictionary, let key):
dictionary[NSString(string: key)] = value
}
}
}
//===----------------------------------------------------------------------===//
// JSON Decoder
//===----------------------------------------------------------------------===//
/// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types.
open class JSONDecoder {
// MARK: Options
/// The strategy to use for decoding `Date` values.
public enum DateDecodingStrategy {
/// Defer to `Date` for decoding. This is the default strategy.
case deferredToDate
/// Decode the `Date` as a UNIX timestamp from a JSON number.
case secondsSince1970
/// Decode the `Date` as UNIX millisecond timestamp from a JSON number.
case millisecondsSince1970
/// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Decode the `Date` as a string parsed by the given formatter.
case formatted(DateFormatter)
/// Decode the `Date` as a custom value decoded by the given closure.
case custom((_ decoder: Decoder) throws -> Date)
}
/// The strategy to use for decoding `Data` values.
public enum DataDecodingStrategy {
/// Defer to `Data` for decoding.
case deferredToData
/// Decode the `Data` from a Base64-encoded string. This is the default strategy.
case base64
/// Decode the `Data` as a custom value decoded by the given closure.
case custom((_ decoder: Decoder) throws -> Data)
}
/// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN).
public enum NonConformingFloatDecodingStrategy {
/// Throw upon encountering non-conforming values. This is the default strategy.
case `throw`
/// Decode the values from the given representation strings.
case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String)
}
/// The strategy to use in decoding dates. Defaults to `.deferredToDate`.
open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate
/// The strategy to use in decoding binary data. Defaults to `.base64`.
open var dataDecodingStrategy: DataDecodingStrategy = .base64
/// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`.
open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw
/// Contextual user-provided information for use during decoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the decoding hierarchy.
fileprivate struct _Options {
let dateDecodingStrategy: DateDecodingStrategy
let dataDecodingStrategy: DataDecodingStrategy
let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level decoder.
fileprivate var options: _Options {
return _Options(dateDecodingStrategy: dateDecodingStrategy,
dataDecodingStrategy: dataDecodingStrategy,
nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy,
userInfo: userInfo)
}
// MARK: - Constructing a JSON Decoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Decoding Values
/// Decodes a top-level value of the given type from the given JSON representation.
///
/// - parameter type: The type of the value to decode.
/// - parameter data: The data to decode from.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid JSON.
/// - throws: An error if any value throws an error during decoding.
open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T {
let topLevel: Any
do {
topLevel = try JSONSerialization.jsonObject(with: data)
} catch {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error))
}
let decoder = _JSONDecoder(referencing: topLevel, options: self.options)
guard let value = try decoder.unbox(topLevel, as: T.self) else {
throw DecodingError.valueNotFound(T.self, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
}
return value
}
}
// MARK: - _JSONDecoder
fileprivate class _JSONDecoder : Decoder {
// MARK: Properties
/// The decoder's storage.
fileprivate var storage: _JSONDecodingStorage
/// Options set on the top-level decoder.
fileprivate let options: JSONDecoder._Options
/// The path to the current point in encoding.
fileprivate(set) public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level container and options.
fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: JSONDecoder._Options) {
self.storage = _JSONDecodingStorage()
self.storage.push(container: container)
self.codingPath = codingPath
self.options = options
}
// MARK: - Decoder Methods
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let topContainer = self.storage.topContainer as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer)
}
let container = _JSONKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer)
return KeyedDecodingContainer(container)
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get unkeyed decoding container -- found null value instead."))
}
guard let topContainer = self.storage.topContainer as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer)
}
return _JSONUnkeyedDecodingContainer(referencing: self, wrapping: topContainer)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
}
// MARK: - Decoding Storage
fileprivate struct _JSONDecodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the JSON types (NSNull, NSNumber, String, Array, [String : Any]).
private(set) fileprivate var containers: [Any] = []
// MARK: - Initialization
/// Initializes `self` with no containers.
fileprivate init() {}
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate var topContainer: Any {
precondition(self.containers.count > 0, "Empty container stack.")
return self.containers.last!
}
fileprivate mutating func push(container: Any) {
self.containers.append(container)
}
fileprivate mutating func popContainer() {
precondition(self.containers.count > 0, "Empty container stack.")
self.containers.removeLast()
}
}
// MARK: Decoding Containers
fileprivate struct _JSONKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _JSONDecoder
/// A reference to the container we're reading from.
private let container: [String : Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [String : Any]) {
self.decoder = decoder
self.container = container
self.codingPath = decoder.codingPath
}
// MARK: - KeyedDecodingContainerProtocol Methods
public var allKeys: [Key] {
return self.container.keys.flatMap { Key(stringValue: $0) }
}
public func contains(_ key: Key) -> Bool {
return self.container[key.stringValue] != nil
}
public func decodeNil(forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
return entry is NSNull
}
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: T.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \"\(key.stringValue)\""))
}
guard let dictionary = value as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
}
let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
return KeyedDecodingContainer(container)
}
public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \"\(key.stringValue)\""))
}
guard let array = value as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
}
return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
private func _superDecoder(forKey key: CodingKey) throws -> Decoder {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
let value: Any = self.container[key.stringValue] ?? NSNull()
return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
public func superDecoder() throws -> Decoder {
return try _superDecoder(forKey: _JSONKey.super)
}
public func superDecoder(forKey key: Key) throws -> Decoder {
return try _superDecoder(forKey: key)
}
}
fileprivate struct _JSONUnkeyedDecodingContainer : UnkeyedDecodingContainer {
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _JSONDecoder
/// A reference to the container we're reading from.
private let container: [Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
/// The index of the element we're about to decode.
private(set) public var currentIndex: Int
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [Any]) {
self.decoder = decoder
self.container = container
self.codingPath = decoder.codingPath
self.currentIndex = 0
}
// MARK: - UnkeyedDecodingContainer Methods
public var count: Int? {
return self.container.count
}
public var isAtEnd: Bool {
return self.currentIndex >= self.count!
}
public mutating func decodeNil() throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
if self.container[self.currentIndex] is NSNull {
self.currentIndex += 1
return true
} else {
return false
}
}
public mutating func decode(_ type: Bool.Type) throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int.Type) throws -> Int {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int8.Type) throws -> Int8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int16.Type) throws -> Int16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int32.Type) throws -> Int32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int64.Type) throws -> Int64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt.Type) throws -> UInt {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Float.Type) throws -> Float {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Double.Type) throws -> Double {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: String.Type) throws -> String {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: T.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
guard !(value is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let dictionary = value as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
}
self.currentIndex += 1
let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
return KeyedDecodingContainer(container)
}
public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
guard !(value is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let array = value as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
}
self.currentIndex += 1
return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
public mutating func superDecoder() throws -> Decoder {
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Decoder.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get superDecoder() -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
self.currentIndex += 1
return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
}
extension _JSONDecoder : SingleValueDecodingContainer {
// MARK: SingleValueDecodingContainer Methods
private func expectNonNull<T>(_ type: T.Type) throws {
guard !self.decodeNil() else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead."))
}
}
public func decodeNil() -> Bool {
return self.storage.topContainer is NSNull
}
public func decode(_ type: Bool.Type) throws -> Bool {
try expectNonNull(Bool.self)
return try self.unbox(self.storage.topContainer, as: Bool.self)!
}
public func decode(_ type: Int.Type) throws -> Int {
try expectNonNull(Int.self)
return try self.unbox(self.storage.topContainer, as: Int.self)!
}
public func decode(_ type: Int8.Type) throws -> Int8 {
try expectNonNull(Int8.self)
return try self.unbox(self.storage.topContainer, as: Int8.self)!
}
public func decode(_ type: Int16.Type) throws -> Int16 {
try expectNonNull(Int16.self)
return try self.unbox(self.storage.topContainer, as: Int16.self)!
}
public func decode(_ type: Int32.Type) throws -> Int32 {
try expectNonNull(Int32.self)
return try self.unbox(self.storage.topContainer, as: Int32.self)!
}
public func decode(_ type: Int64.Type) throws -> Int64 {
try expectNonNull(Int64.self)
return try self.unbox(self.storage.topContainer, as: Int64.self)!
}
public func decode(_ type: UInt.Type) throws -> UInt {
try expectNonNull(UInt.self)
return try self.unbox(self.storage.topContainer, as: UInt.self)!
}
public func decode(_ type: UInt8.Type) throws -> UInt8 {
try expectNonNull(UInt8.self)
return try self.unbox(self.storage.topContainer, as: UInt8.self)!
}
public func decode(_ type: UInt16.Type) throws -> UInt16 {
try expectNonNull(UInt16.self)
return try self.unbox(self.storage.topContainer, as: UInt16.self)!
}
public func decode(_ type: UInt32.Type) throws -> UInt32 {
try expectNonNull(UInt32.self)
return try self.unbox(self.storage.topContainer, as: UInt32.self)!
}
public func decode(_ type: UInt64.Type) throws -> UInt64 {
try expectNonNull(UInt64.self)
return try self.unbox(self.storage.topContainer, as: UInt64.self)!
}
public func decode(_ type: Float.Type) throws -> Float {
try expectNonNull(Float.self)
return try self.unbox(self.storage.topContainer, as: Float.self)!
}
public func decode(_ type: Double.Type) throws -> Double {
try expectNonNull(Double.self)
return try self.unbox(self.storage.topContainer, as: Double.self)!
}
public func decode(_ type: String.Type) throws -> String {
try expectNonNull(String.self)
return try self.unbox(self.storage.topContainer, as: String.self)!
}
public func decode<T : Decodable>(_ type: T.Type) throws -> T {
try expectNonNull(T.self)
return try self.unbox(self.storage.topContainer, as: T.self)!
}
}
// MARK: - Concrete Value Representations
extension _JSONDecoder {
/// Returns the given value unboxed from a container.
fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber {
// TODO: Add a flag to coerce non-boolean numbers into Bools?
if number === kCFBooleanTrue as NSNumber {
return true
} else if number === kCFBooleanFalse as NSNumber {
return false
}
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let bool = value as? Bool {
return bool
*/
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int = number.intValue
guard NSNumber(value: int) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int
}
fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int8 = number.int8Value
guard NSNumber(value: int8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int8
}
fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int16 = number.int16Value
guard NSNumber(value: int16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int16
}
fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int32 = number.int32Value
guard NSNumber(value: int32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int32
}
fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int64 = number.int64Value
guard NSNumber(value: int64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int64
}
fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint = number.uintValue
guard NSNumber(value: uint) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint
}
fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint8 = number.uint8Value
guard NSNumber(value: uint8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint8
}
fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint16 = number.uint16Value
guard NSNumber(value: uint16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint16
}
fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint32 = number.uint32Value
guard NSNumber(value: uint32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint32
}
fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint64 = number.uint64Value
guard NSNumber(value: uint64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint64
}
fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse {
// We are willing to return a Float by losing precision:
// * If the original value was integral,
// * and the integral value was > Float.greatestFiniteMagnitude, we will fail
// * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24
// * If it was a Float, you will get back the precise value
// * If it was a Double or Decimal, you will get back the nearest approximation if it will fit
let double = number.doubleValue
guard abs(double) <= Double(Float.greatestFiniteMagnitude) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type)."))
}
return Float(double)
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let double = value as? Double {
if abs(double) <= Double(Float.max) {
return Float(double)
}
overflow = true
} else if let int = value as? Int {
if let float = Float(exactly: int) {
return float
}
overflow = true
*/
} else if let string = value as? String,
case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy {
if string == posInfString {
return Float.infinity
} else if string == negInfString {
return -Float.infinity
} else if string == nanString {
return Float.nan
}
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse {
// We are always willing to return the number as a Double:
// * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double
// * If it was a Float or Double, you will get back the precise value
// * If it was Decimal, you will get back the nearest approximation
return number.doubleValue
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let double = value as? Double {
return double
} else if let int = value as? Int {
if let double = Double(exactly: int) {
return double
}
overflow = true
*/
} else if let string = value as? String,
case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy {
if string == posInfString {
return Double.infinity
} else if string == negInfString {
return -Double.infinity
} else if string == nanString {
return Double.nan
}
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
return string
}
fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? {
guard !(value is NSNull) else { return nil }
switch self.options.dateDecodingStrategy {
case .deferredToDate:
self.storage.push(container: value)
let date = try Date(from: self)
self.storage.popContainer()
return date
case .secondsSince1970:
let double = try self.unbox(value, as: Double.self)!
return Date(timeIntervalSince1970: double)
case .millisecondsSince1970:
let double = try self.unbox(value, as: Double.self)!
return Date(timeIntervalSince1970: double / 1000.0)
case .iso8601:
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
let string = try self.unbox(value, as: String.self)!
guard let date = _iso8601Formatter.date(from: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted."))
}
return date
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case .formatted(let formatter):
let string = try self.unbox(value, as: String.self)!
guard let date = formatter.date(from: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter."))
}
return date
case .custom(let closure):
self.storage.push(container: value)
let date = try closure(self)
self.storage.popContainer()
return date
}
}
fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
guard !(value is NSNull) else { return nil }
switch self.options.dataDecodingStrategy {
case .deferredToData:
self.storage.push(container: value)
let data = try Data(from: self)
self.storage.popContainer()
return data
case .base64:
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
guard let data = Data(base64Encoded: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64."))
}
return data
case .custom(let closure):
self.storage.push(container: value)
let data = try closure(self)
self.storage.popContainer()
return data
}
}
fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? {
guard !(value is NSNull) else { return nil }
// Attempt to bridge from NSDecimalNumber.
if let decimal = value as? Decimal {
return decimal
} else {
let doubleValue = try self.unbox(value, as: Double.self)!
return Decimal(doubleValue)
}
}
fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? {
let decoded: T
if T.self == Date.self || T.self == NSDate.self {
guard let date = try self.unbox(value, as: Date.self) else { return nil }
decoded = date as! T
} else if T.self == Data.self || T.self == NSData.self {
guard let data = try self.unbox(value, as: Data.self) else { return nil }
decoded = data as! T
} else if T.self == URL.self || T.self == NSURL.self {
guard let urlString = try self.unbox(value, as: String.self) else {
return nil
}
guard let url = URL(string: urlString) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Invalid URL string."))
}
decoded = (url as! T)
} else if T.self == Decimal.self || T.self == NSDecimalNumber.self {
guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil }
decoded = decimal as! T
} else {
self.storage.push(container: value)
decoded = try T(from: self)
self.storage.popContainer()
}
return decoded
}
}
//===----------------------------------------------------------------------===//
// Shared Key Types
//===----------------------------------------------------------------------===//
fileprivate struct _JSONKey : CodingKey {
public var stringValue: String
public var intValue: Int?
public init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
public init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
fileprivate init(index: Int) {
self.stringValue = "Index \(index)"
self.intValue = index
}
fileprivate static let `super` = _JSONKey(stringValue: "super")!
}
//===----------------------------------------------------------------------===//
// Shared ISO8601 Date Formatter
//===----------------------------------------------------------------------===//
// NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
fileprivate var _iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter
}()
//===----------------------------------------------------------------------===//
// Error Utilities
//===----------------------------------------------------------------------===//
fileprivate extension EncodingError {
/// Returns a `.invalidValue` error describing the given invalid floating-point value.
///
///
/// - parameter value: The value that was invalid to encode.
/// - parameter path: The path of `CodingKey`s taken to encode this value.
/// - returns: An `EncodingError` with the appropriate path and debug description.
fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError {
let valueDescription: String
if value == T.infinity {
valueDescription = "\(T.self).infinity"
} else if value == -T.infinity {
valueDescription = "-\(T.self).infinity"
} else {
valueDescription = "\(T.self).nan"
}
let debugDescription = "Unable to encode \(valueDescription) directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded."
return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription))
}
}
| 0ee0ed52d241a033794c00db862f0b7d | 43.111923 | 323 | 0.651516 | false | false | false | false |
ZNosX/HackerNews | refs/heads/master | HackerNews/MainViewController.swift | mit | 3 | //
// MainViewController.swift
// HackerNews
//
// Copyright (c) 2015 Amit Burstein. All rights reserved.
// See LICENSE for licensing information.
//
import UIKit
import SafariServices
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SFSafariViewControllerDelegate {
// MARK: Properties
let PostCellIdentifier = "PostCell"
let ShowBrowserIdentifier = "ShowBrowser"
let PullToRefreshString = "Pull to Refresh"
let FetchErrorMessage = "Could Not Fetch Posts"
let ErrorMessageLabelTextColor = UIColor.grayColor()
let ErrorMessageFontSize: CGFloat = 16
let FirebaseRef = "https://hacker-news.firebaseio.com/v0/"
let ItemChildRef = "item"
let StoryTypeChildRefMap = [StoryType.Top: "topstories", .New: "newstories", .Show: "showstories"]
let StoryLimit: UInt = 30
let DefaultStoryType = StoryType.Top
var firebase: Firebase!
var stories: [Story]!
var storyType: StoryType!
var retrievingStories: Bool!
var refreshControl: UIRefreshControl!
var errorMessageLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
// MARK: Enums
enum StoryType {
case Top, New, Show
}
// MARK: Structs
struct Story {
var title: String
var url: String?
var by: String
var score: Int
}
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
firebase = Firebase(url: FirebaseRef)
stories = []
storyType = DefaultStoryType
retrievingStories = false
refreshControl = UIRefreshControl()
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
retrieveStories()
}
// MARK: Functions
func configureUI() {
refreshControl.addTarget(self, action: "retrieveStories", forControlEvents: .ValueChanged)
refreshControl.attributedTitle = NSAttributedString(string: PullToRefreshString)
tableView.insertSubview(refreshControl, atIndex: 0)
// Have to initialize this UILabel here because the view does not exist in init() yet.
errorMessageLabel = UILabel(frame: CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height))
errorMessageLabel.textColor = ErrorMessageLabelTextColor
errorMessageLabel.textAlignment = .Center
errorMessageLabel.font = UIFont.systemFontOfSize(ErrorMessageFontSize)
}
func retrieveStories() {
if retrievingStories! {
return
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
stories = []
retrievingStories = true
var storiesMap = [Int:Story]()
let query = firebase.childByAppendingPath(StoryTypeChildRefMap[storyType]).queryLimitedToFirst(StoryLimit)
query.observeSingleEventOfType(.Value, withBlock: { snapshot in
let storyIds = snapshot.value as! [Int]
for storyId in storyIds {
let query = self.firebase.childByAppendingPath(self.ItemChildRef).childByAppendingPath(String(storyId))
query.observeSingleEventOfType(.Value, withBlock: { snapshot in
let title = snapshot.value["title"] as! String
let url = snapshot.value["url"] as? String
let by = snapshot.value["by"] as! String
let score = snapshot.value["score"] as! Int
let story = Story(title: title, url: url, by: by, score: score)
storiesMap[storyId] = story
if storiesMap.count == Int(self.StoryLimit) {
var sortedStories = [Story]()
for storyId in storyIds {
sortedStories.append(storiesMap[storyId]!)
}
self.stories = sortedStories
self.tableView.reloadData()
self.refreshControl.endRefreshing()
self.retrievingStories = false
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}, withCancelBlock: { error in
self.retrievingStories = false
self.stories.removeAll()
self.tableView.reloadData()
self.showErrorMessage(self.FetchErrorMessage)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
}, withCancelBlock: { error in
self.retrievingStories = false
self.stories.removeAll()
self.tableView.reloadData()
self.showErrorMessage(self.FetchErrorMessage)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
func showErrorMessage(message: String) {
errorMessageLabel.text = message
self.tableView.backgroundView = errorMessageLabel
self.tableView.separatorStyle = .None
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stories.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let story = stories[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(PostCellIdentifier) as UITableViewCell!
cell.textLabel?.text = story.title
cell.detailTextLabel?.text = "\(story.score) points by \(story.by)"
return cell
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let story = stories[indexPath.row]
if let url = story.url {
let webViewController = SFSafariViewController(URL: NSURL(string: url)!)
webViewController.delegate = self
presentViewController(webViewController, animated: true, completion: nil)
}
}
// MARK: SFSafariViewControllerDelegate
func safariViewControllerDidFinish(controller: SFSafariViewController) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: IBActions
@IBAction func changeStoryType(sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
storyType = .Top
} else if sender.selectedSegmentIndex == 1 {
storyType = .New
} else if sender.selectedSegmentIndex == 2 {
storyType = .Show
} else {
print("Bad segment index!")
}
retrieveStories()
}
}
| 00e8c0c9c32f74922da28e9128b5f5f5 | 32.073684 | 120 | 0.69478 | false | false | false | false |
PD-Jell/Swift_study | refs/heads/master | SwiftStudy/RxSwift/RxSwift-Chameleon/RxChameleonViewController.swift | mit | 1 | //
// RxChameleonViewController.swift
// SwiftStudy
//
// Created by YooHG on 7/8/20.
// Copyright © 2020 Jell PD. All rights reserved.
//
import ChameleonFramework
import UIKit
import RxSwift
import RxCocoa
class RXChameleonViewController: UIViewController {
var circleView: UIView!
var circleViewModel: CircleViewModel!
var disposeBag: DisposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
circleView = UIView(frame: CGRect(origin: view.center, size: CGSize(width: 100.0, height: 100.0)))
circleView.layer.cornerRadius = circleView.frame.width / 2.0
circleView.center = view.center
circleView.backgroundColor = .green
view.addSubview(circleView)
circleViewModel = CircleViewModel()
circleView
.rx.observe(CGPoint.self, "center")
.bind(to: circleViewModel.centerVariable)
.disposed(by: disposeBag) // CircleView의 중앙 지점을 centerObservable에 묶는다.(bind)
// ViewModel의 새로운 색을 얻기 위해 backgroundObservable을 구독한다.
circleViewModel.backgroundColorObservable
.subscribe(onNext: {[weak self] backgroundColor in
UIView.animate(withDuration: 0.1, animations: {
self?.circleView.backgroundColor = backgroundColor
// 주어진 배경색의 보색을 구한다.
let viewBackgroundColor = UIColor(complementaryFlatColorOf: backgroundColor)
if viewBackgroundColor != backgroundColor {
self?.view.backgroundColor = viewBackgroundColor
}
})
})
.disposed(by: disposeBag)
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(circleMoved(_:)))
circleView.addGestureRecognizer(gestureRecognizer)
}
@objc func circleMoved(_ recognizer: UIPanGestureRecognizer) {
let location = recognizer.location(in: view)
UIView.animate(withDuration: 0.1, animations: {
self.circleView.center = location
})
}
}
| 8f611b0d834d549bc4978bbe011385fc | 33.296875 | 106 | 0.620501 | false | false | false | false |
aschwaighofer/swift | refs/heads/master | test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-public-1distinct_use.swift | apache-2.0 | 2 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$sytN" = external{{( dllimport)?}} global %swift.full_type
// CHECK: @"$s4main5ValueOySiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i8**,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5ValueOySiGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1PAAWP", i32 0, i32 0),
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
public protocol P {}
extension Int : P {}
enum Value<First : P> {
case first(First)
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i8**,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Value.first(13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, %swift.type* %1, i8** %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TABLE:%[0-9]+]] = bitcast i8** %2 to i8*
// CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_LABEL]]:
// CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE]]
// CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]]
// CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED]]:
// CHECK: ret %swift.metadata_response {
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i8**,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] 0
// CHECK-SAME: }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE]],
// CHECK-SAME: i8* [[ERASED_TABLE]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| 63cfc6aebd0622631e7da58a4de8b2fc | 37.878505 | 157 | 0.569952 | false | false | false | false |
jad6/DataStore | refs/heads/master | Example/Places/Settings.swift | bsd-2-clause | 1 | //
// Settings.swift
// Places
//
// Created by Jad Osseiran on 28/06/2015.
// Copyright © 2015 Jad Osseiran. All rights reserved.
//
import Foundation
var sharedSettings = Settings()
struct Settings {
enum Thread: Int {
case Main = 0, Background, Mixed
}
var thread = Thread.Main
enum DelayDuration: Int {
case None = 0
case OneSecond
case FiveSeconds
case TenSeconds
case ThirtySeconds
}
var delayDuration = DelayDuration.None
enum BatchSize: Int {
case OneItem = 1
case TwoItems
case FiveItems
case TwentyItems
case FiftyItems
case HunderdItems
}
var batchSize = BatchSize.OneItem
var atomicBatchSave = false
// Index Path Helpers
let threadSection = 0
var checkedThreadIndexPath: NSIndexPath {
let row: Int
switch thread {
case .Main:
row = 0
case .Background:
row = 1
case .Mixed:
row = 2
}
return NSIndexPath(forRow: row, inSection: 0)
}
let delaySection = 1
var checkedDelayIndexPath: NSIndexPath {
let row: Int
switch delayDuration {
case .None:
row = 0
case .OneSecond:
row = 1
case .FiveSeconds:
row = 2
case .TenSeconds:
row = 3
case .ThirtySeconds:
row = 4
}
return NSIndexPath(forRow: row, inSection: 1)
}
let batchSection = 2
var checkedBatchIndexPath: NSIndexPath {
let row: Int
switch batchSize {
case .OneItem:
row = 1
case .TwoItems:
row = 2
case .FiveItems:
row = 3
case .TwentyItems:
row = 4
case .FiftyItems:
row = 5
case .HunderdItems:
row = 6
}
return NSIndexPath(forRow: row, inSection: 2)
}
}
| 9855b70b0ce7c71e38ec8526a7c94c2f | 20.554348 | 55 | 0.533535 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.