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
Tomikes/eidolon
refs/heads/master
Kiosk/Bid Fulfillment/StripeManager.swift
mit
6
import Foundation import ReactiveCocoa import Stripe class StripeManager: NSObject { var stripeClient = STPAPIClient.sharedClient() func registerCard(digits: String, month: UInt, year: UInt) -> RACSignal { let card = STPCard() card.number = digits card.expMonth = month card.expYear = year return RACSignal.createSignal { [weak self] (subscriber) -> RACDisposable! in self?.stripeClient.createTokenWithCard(card) { (token, error) -> Void in if (token as STPToken?).hasValue { subscriber.sendNext(token) subscriber.sendCompleted() } else { subscriber.sendError(error) } } return nil } } func stringIsCreditCard(object: AnyObject!) -> AnyObject! { let cardNumber = object as! String return STPCard.validateCardNumber(cardNumber) } } extension STPCardBrand { var name: String? { switch self { case .Visa: return "Visa" case .Amex: return "American Express" case .MasterCard: return "MasterCard" case .Discover: return "Discover" case .JCB: return "JCB" case .DinersClub: return "Diners Club" default: return nil } } }
cc118460dceae5c546d8b349ae5069d2
25.185185
85
0.547383
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGeometry/Bezier/CubicBezier.swift
mit
1
// // CubicBezier.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @frozen public struct CubicBezier<Element: ScalarMultiplicative>: BezierProtocol where Element.Scalar == Double { public var p0: Element public var p1: Element public var p2: Element public var p3: Element @inlinable @inline(__always) public init() { self.p0 = .zero self.p1 = .zero self.p2 = .zero self.p3 = .zero } @inlinable @inline(__always) public init(_ p0: Element, _ p1: Element, _ p2: Element, _ p3: Element) { self.p0 = p0 self.p1 = p1 self.p2 = p2 self.p3 = p3 } } extension Bezier { @inlinable @inline(__always) public init(_ bezier: CubicBezier<Element>) { self.init(bezier.p0, bezier.p1, bezier.p2, bezier.p3) } } extension CubicBezier: Hashable where Element: Hashable { } extension CubicBezier: Decodable where Element: Decodable { @inlinable @inline(__always) public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() self.init(try container.decode(Element.self), try container.decode(Element.self), try container.decode(Element.self), try container.decode(Element.self)) } } extension CubicBezier: Encodable where Element: Encodable { @inlinable @inline(__always) public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(p0) try container.encode(p1) try container.encode(p2) try container.encode(p3) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension CubicBezier: Sendable where Element: Sendable { } extension CubicBezier { @inlinable @inline(__always) public func map(_ transform: (Element) -> Element) -> CubicBezier { return CubicBezier(transform(p0), transform(p1), transform(p2), transform(p3)) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, p0) updateAccumulatingResult(&accumulator, p1) updateAccumulatingResult(&accumulator, p2) updateAccumulatingResult(&accumulator, p3) return accumulator } @inlinable @inline(__always) public func combined(_ other: CubicBezier, _ transform: (Element, Element) -> Element) -> CubicBezier { return CubicBezier(transform(p0, other.p0), transform(p1, other.p1), transform(p2, other.p2), transform(p3, other.p3)) } } extension CubicBezier { public typealias Indices = Range<Int> @inlinable @inline(__always) public var startIndex: Int { return 0 } @inlinable @inline(__always) public var endIndex: Int { return 4 } @inlinable @inline(__always) public subscript(position: Int) -> Element { get { return withUnsafeTypePunnedPointer(of: self, to: Element.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Element.self) { $0[position] = newValue } } } } extension CubicBezier { @inlinable @inline(__always) public var start: Element { return p0 } @inlinable @inline(__always) public var end: Element { return p3 } @inlinable @inline(__always) public func eval(_ t: Double) -> Element { let t2 = t * t let _t = 1 - t let _t2 = _t * _t let a = _t * _t2 * p0 let b = 3 * _t2 * t * p1 let c = 3 * _t * t2 * p2 let d = t * t2 * p3 return a + b + c + d } @inlinable @inline(__always) public func split(_ t: Double) -> (CubicBezier, CubicBezier) { let q0 = p0 + t * (p1 - p0) let q1 = p1 + t * (p2 - p1) let q2 = p2 + t * (p3 - p2) let u0 = q0 + t * (q1 - q0) let u1 = q1 + t * (q2 - q1) let v0 = u0 + t * (u1 - u0) return (CubicBezier(p0, q0, u0, v0), CubicBezier(v0, u1, q2, p3)) } @inlinable @inline(__always) public func elevated() -> Bezier<Element> { return Bezier(self).elevated() } @inlinable @inline(__always) public func derivative() -> QuadBezier<Element> { let q0 = 3 * (p1 - p0) let q1 = 3 * (p2 - p1) let q2 = 3 * (p3 - p2) return QuadBezier(q0, q1, q2) } } extension CubicBezier where Element == Point { @inlinable @inline(__always) public var x: CubicBezier<Double> { return CubicBezier<Double>(p0.x, p1.x, p2.x, p3.x) } @inlinable @inline(__always) public var y: CubicBezier<Double> { return CubicBezier<Double>(p0.y, p1.y, p2.y, p3.y) } } extension CubicBezier where Element == Vector { @inlinable @inline(__always) public var x: CubicBezier<Double> { return CubicBezier<Double>(p0.x, p1.x, p2.x, p3.x) } @inlinable @inline(__always) public var y: CubicBezier<Double> { return CubicBezier<Double>(p0.y, p1.y, p2.y, p3.y) } @inlinable @inline(__always) public var z: CubicBezier<Double> { return CubicBezier<Double>(p0.z, p1.z, p2.z, p3.z) } } extension CubicBezier { @inlinable @inline(__always) public var _polynomial: (Element, Element, Element) { let b = 3 * (p1 - p0) var c = 3 * (p2 + p0) c -= 6 * p1 var d = p3 - p0 d += 3 * (p1 - p2) return (b, c, d) } } extension CubicBezier where Element == Double { @inlinable @inline(__always) public var polynomial: Polynomial { let a = p0 let (b, c, d) = _polynomial return [a, b, c, d] } } extension CubicBezier where Element: Tensor { @inlinable @inline(__always) public func closest(_ point: Element, in range: ClosedRange<Double> = -.infinity ... .infinity) -> [Double] { let a = p0 - point let (b, c, d) = _polynomial var dot: Polynomial = [] for i in 0..<Element.numberOfComponents { let p: Polynomial = [a[i], b[i], c[i], d[i]] dot += p * p } return dot.derivative.roots(in: range).sorted(by: { dot.eval($0) }) } } extension CubicBezier where Element == Point { @inlinable @inline(__always) public var area: Double { let a = p3.x - p0.x + 3 * (p1.x - p2.x) let b = 3 * (p2.x + p0.x) - 6 * p1.x let c = 3 * (p1.x - p0.x) let d = p3.y - p0.y + 3 * (p1.y - p2.y) let e = 3 * (p2.y + p0.y) - 6 * p1.y let f = 3 * (p1.y - p0.y) return 0.5 * (p0.x * p3.y - p3.x * p0.y) + 0.1 * (b * d - a * e) + 0.25 * (c * d - a * f) + (c * e - b * f) / 6 } } extension CubicBezier where Element == Point { @inlinable public var inflection: Degree2Roots { let p = (p3 - p0).phase let _p1 = (p1 - p0) * SDTransform.rotate(-p) let _p2 = (p2 - p0) * SDTransform.rotate(-p) let _p3 = (p3 - p0) * SDTransform.rotate(-p) let a = _p2.x * _p1.y let b = _p3.x * _p1.y let c = _p1.x * _p2.y let d = _p3.x * _p2.y let x = 18 * (2 * b + 3 * (c - a) - d) let y = 18 * (3 * (a - c) - b) let z = 18 * (c - a) if x.almostZero() { return y.almostZero() ? Degree2Roots() : Degree2Roots(-z / y) } return degree2roots(y / x, z / x) } @inlinable public func curvature(_ t: Double) -> Double { let x = self.x.polynomial let y = self.y.polynomial return _bezier_curvature(x, y, t) } @inlinable public var stationary: [Double] { let x = self.x.polynomial let y = self.y.polynomial return _bezier_stationary(x, y) } } extension CubicBezier where Element == Double { @inlinable public var stationary: Degree2Roots { let _a = 3 * (p3 - p0) + 9 * (p1 - p2) let _b = 6 * (p2 + p0) - 12 * p1 let _c = 3 * (p1 - p0) if _a.almostZero() { if _b.almostZero() { return Degree2Roots() } let t = -_c / _b return Degree2Roots(t) } else { let delta = _b * _b - 4 * _a * _c let _a2 = 2 * _a let _b2 = -_b / _a2 if delta.sign == .plus { let sqrt_delta = sqrt(delta) / _a2 let t1 = _b2 + sqrt_delta let t2 = _b2 - sqrt_delta return Degree2Roots(t1, t2) } else if delta.almostZero() { return Degree2Roots(_b2) } } return Degree2Roots() } } extension CubicBezier where Element == Point { @inlinable public var boundary: Rect { let bx = self.x let by = self.y let _x = bx.stationary.lazy.map { bx.eval($0.clamped(to: 0...1)) }.minAndMax() let _y = by.stationary.lazy.map { by.eval($0.clamped(to: 0...1)) }.minAndMax() let minX = _x.map { Swift.min(p0.x, p3.x, $0.min) } ?? Swift.min(p0.x, p3.x) let minY = _y.map { Swift.min(p0.y, p3.y, $0.min) } ?? Swift.min(p0.y, p3.y) let maxX = _x.map { Swift.max(p0.x, p3.x, $0.max) } ?? Swift.max(p0.x, p3.x) let maxY = _y.map { Swift.max(p0.y, p3.y, $0.max) } ?? Swift.max(p0.y, p3.y) return Rect(x: minX, y: minY, width: maxX - minX, height: maxY - minY) } } extension CubicBezier where Element == Point { @inlinable public func selfIntersect() -> (Double, Double)? { let (q1, q2, q3) = _polynomial let d1 = -cross(q3, q2) let d2 = cross(q3, q1) let d3 = -cross(q2, q1) let discr = 3 * d2 * d2 - 4 * d1 * d3 if !d1.almostZero() && !discr.almostZero() && discr < 0 { let delta = sqrt(-discr) let s = 0.5 / d1 let td = d2 + delta let te = d2 - delta return (td * s, te * s) } return nil } @inlinable public func _intersect(_ other: LineSegment<Element>) -> Polynomial { let a = p0 - other.p0 let (b, c, d) = _polynomial let u0: Polynomial = [a.x, b.x, c.x, d.x] let u1 = other.p0.x - other.p1.x let v0: Polynomial = [a.y, b.y, c.y, d.y] let v1 = other.p0.y - other.p1.y return u1 * v0 - u0 * v1 } @inlinable public func _intersect(_ other: QuadBezier<Element>) -> Polynomial { let a = p0 - other.p0 let (b, c, d) = _polynomial let u0: Polynomial = [a.x, b.x, c.x, d.x] let u1 = 2 * (other.p0.x - other.p1.x) let u2 = 2 * other.p1.x - other.p0.x - other.p2.x let v0: Polynomial = [a.y, b.y, c.y, d.y] let v1 = 2 * (other.p0.y - other.p1.y) let v2 = 2 * other.p1.y - other.p0.y - other.p2.y // Bézout matrix let m00 = u2 * v1 - u1 * v2 let m01 = u2 * v0 - u0 * v2 let m10 = m01 let m11 = u1 * v0 - u0 * v1 return m00 * m11 - m01 * m10 } @inlinable public func _intersect(_ other: CubicBezier) -> Polynomial { let a = p0 - other.p0 let (b, c, d) = _polynomial let u0: Polynomial = [a.x, b.x, c.x, d.x] let u1 = 3 * (other.p0.x - other.p1.x) let u2 = 6 * other.p1.x - 3 * (other.p2.x + other.p0.x) let u3 = other.p0.x - other.p3.x + 3 * (other.p2.x - other.p1.x) let v0: Polynomial = [a.y, b.y, c.y, d.y] let v1 = 3 * (other.p0.y - other.p1.y) let v2 = 6 * other.p1.y - 3 * (other.p2.y + other.p0.y) let v3 = other.p0.y - other.p3.y + 3 * (other.p2.y - other.p1.y) // Bézout matrix let m00 = u3 * v2 - u2 * v3 let m01 = u3 * v1 - u1 * v3 let m02 = u3 * v0 - u0 * v3 let m10 = m01 let m11 = u2 * v1 - u1 * v2 + m02 let m12 = u2 * v0 - u0 * v2 let m20 = m02 let m21 = m12 let m22 = u1 * v0 - u0 * v1 let _a = m11 * m22 - m12 * m21 let _b = m12 * m20 - m10 * m22 let _c = m10 * m21 - m11 * m20 let _d = m00 * _a let _e = m01 * _b let _f = m02 * _c return _d + _e + _f } @inlinable public func overlap(_ other: LineSegment<Element>) -> Bool { return self._intersect(other).allSatisfy { $0.almostZero() } } @inlinable public func overlap(_ other: QuadBezier<Element>) -> Bool { return self._intersect(other).allSatisfy { $0.almostZero() } } @inlinable public func overlap(_ other: CubicBezier) -> Bool { return self._intersect(other).allSatisfy { $0.almostZero() } } @inlinable public func intersect(_ other: LineSegment<Element>, in range: ClosedRange<Double> = -.infinity ... .infinity) -> [Double]? { let det = self._intersect(other) return det.allSatisfy { $0.almostZero() } ? nil : det.roots(in: range) } @inlinable public func intersect(_ other: QuadBezier<Element>, in range: ClosedRange<Double> = -.infinity ... .infinity) -> [Double]? { let det = self._intersect(other) return det.allSatisfy { $0.almostZero() } ? nil : det.roots(in: range) } @inlinable public func intersect(_ other: CubicBezier, in range: ClosedRange<Double> = -.infinity ... .infinity) -> [Double]? { let det = self._intersect(other) return det.allSatisfy { $0.almostZero() } ? nil : det.roots(in: range) } }
cf737ec3be6e6e02c183535956d35d64
28.54845
131
0.534203
false
false
false
false
richflee/Beatles-Songs
refs/heads/master
BeatlesSongs/View Controllers/FavouriteSongsViewController.swift
mit
1
// // FavouriteSongsViewController.swift // BeatlesSongs // // Created by Richard Lee on 29/10/2015. // Copyright © 2015 Richard Lee. All rights reserved. // import UIKit class FavouriteSongsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { typealias beatlesSong = (title:String, viewed:Int) @IBOutlet var tableView: UITableView! { didSet { tableView.dataSource = self tableView.delegate = self } } var songs:[beatlesSong] = [] let songsReuseIdentifier = "songsCellReuseIdentifier" override func viewDidLoad() { super.viewDidLoad() let songTitles = [ "Yesterday", "Yellow Submarine", "Help!", "Nowhere man", "Glass onion", "Julia", "Ticket to Ride", "Here comes the sun", "Come together", "A day in the life", "Michelle" ] songTitles.forEach { (songTitle) -> () in let song = ( songTitle, Int(arc4random_uniform(2)) ) songs.append(song) } let nib:UINib = UINib(nibName: "SongTableCell", bundle: NSBundle.mainBundle()) tableView.registerNib(nib, forCellReuseIdentifier: songsReuseIdentifier) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if let selectedIndexPath = tableView.indexPathForSelectedRow { tableView.deselectRowAtIndexPath(selectedIndexPath, animated:true) } } // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return songs.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:SongTableViewCell = tableView.dequeueReusableCellWithIdentifier(songsReuseIdentifier, forIndexPath: indexPath) as! SongTableViewCell cell.songLabel.text = songs[indexPath.row].title cell.markAsRead(Bool(songs[indexPath.row].viewed)) return cell } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var song = songs[indexPath.row] let songViewController = SongViewController(nibName:"SongViewController", bundle:nil) songViewController.songTitle = song.title song.viewed = 1 songs[indexPath.row] = song let cell:SongTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as! SongTableViewCell cell.markAsRead(Bool(song.viewed)) navigationController?.pushViewController(songViewController, animated: true) } }
c5568dd668e7dd2aa2524f82448fde62
28.97
198
0.635636
false
false
false
false
syllabix/swipe-card-carousel
refs/heads/master
Example/SwipeCardCarouselExample/ExampleViewController.swift
mit
1
// // ViewController.swift // SwipeCardCarouselExample // // Created by Tom Stoepker on 10/6/16. // Copyright © 2016 CrushOnly. All rights reserved. // import UIKit import SwipeCardCarousel class ExampleViewController: UIViewController { @IBOutlet weak var cardDeck: SwipeCardDeck! var data = [ExampleData]() override func viewDidLoad() { super.viewDidLoad() data = getExampleData() cardDeck.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension ExampleViewController: SwipeCardDeckDelegate { func cardAt(index: Int) -> SwipeCard { let d = data[index] let card = ExampleCard() card.titleLabel.text = d.name card.aboutLabel.text = d.description card.valueLabel.text = "Price: $\(d.value)" return card } func numberOfCardsInDeck() -> Int { return data.count } func labelForNextIndicatorAt(index: Int) -> String { guard let text = data[index].name else { return "Next" } return text } func labelForPrevIndicatorAt(index: Int) -> String { guard let text = data[index].name else { return "Prev" } return text } }
984351e95c0fa511a78c974195e0a04b
20.605634
103
0.711213
false
false
false
false
SoufianeLasri/Sisley
refs/heads/master
Sisley/HistoryActivityView.swift
mit
1
// // HistoryActivityView.swift // Sisley // // Created by Soufiane Lasri on 07/01/2016. // Copyright © 2016 Soufiane Lasri. All rights reserved. // import UIKit class HistoryActivityView: UIView { var header: HistoryHeaderView! var etiquette: HistoryEtiquetteView! init( frame: CGRect, data: [ String : String ] ) { super.init( frame: frame ) self.header = HistoryHeaderView( frame: CGRect( x: 0, y: 95, width: self.frame.width - 60, height: 40 ), data: data[ "header" ]! ) header.center.x = self.center.x self.addSubview( self.header ) self.etiquette = HistoryEtiquetteView( frame: CGRect( x: 0, y: header.frame.maxY, width: self.frame.width - 60, height: 120 ), mainText: data[ "mainText" ]!, secondText: data[ "secondText" ]! ) etiquette.center.x = self.center.x self.addSubview( self.etiquette ) self.frame.size.height = 260 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
2929654117abca95b9cc66793cf1394c
32.15625
201
0.633365
false
false
false
false
gmunhoz/CollieGallery
refs/heads/master
Pod/Classes/CollieGalleryOptions.swift
mit
1
// // CollieGalleryOptions.swift // // Copyright (c) 2016 Guilherme Munhoz <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit /// Class used to customize the gallery options open class CollieGalleryOptions: NSObject { /// Shared options between all new instances of the gallery public static var sharedOptions = CollieGalleryOptions() /// The amount of the parallax effect from 0 to 1 open var parallaxFactor: CGFloat = 0.2 /// Indicates weather the pictures can be zoomed or not open var enableZoom: Bool = true /// The maximum scale that images can reach when zoomed open var maximumZoomScale: CGFloat = 5.0 /// Indicates weather the progress should be displayed or not open var showProgress: Bool = true /// Indicates weather the caption view should be displayed or not open var showCaptionView: Bool = false /// The amount of pictures that should be preloaded next to the current displayed picture open var preLoadedImages: Int = 3 /// The space between each scrollview's page open var gapBetweenPages: CGFloat = 10.0 /// Open gallery at specified page open var openAtIndex: Int = 0 /// Custom close button image name open var customCloseImageName: String? = nil /// Custom options button image name open var customOptionsImageName: String? = nil /// Indicates if the user should be able to save the picture open var enableSave: Bool = true /// Indicates if the user should be able to dismiss the gallery interactively with a pan gesture open var enableInteractiveDismiss: Bool = true /// Add fire custom block instead of showing default share menu open var customOptionsBlock: (() -> Void)? /// Array with the custom buttons open var customActions: [CollieGalleryCustomAction] = [] /// Default actions to exclude from the gallery actions (UIActivityType Constants) open var excludedActions: [UIActivity.ActivityType] = [] }
aee23f10a8058feec61df600aee62f57
40.013158
100
0.717356
false
false
false
false
aiwalle/LiveProject
refs/heads/master
LiveProject/Live/View/ChatView/LJChatToolsView.swift
mit
1
// // LJChatToolsView.swift // LiveProject // // Created by liang on 2017/8/30. // Copyright © 2017年 liang. All rights reserved. // import UIKit protocol LJChatToolsViewDelegate : class { func chatToolsView(_ chatToolsView: LJChatToolsView, message : String) } class LJChatToolsView: UIView { weak open var delegate : LJChatToolsViewDelegate? lazy var inputTextField : UITextField = UITextField() fileprivate lazy var sendMsgBtn: UIButton = { let btn = UIButton(type: UIButtonType.custom) btn.setTitle("发送", for: UIControlState.normal) btn.backgroundColor = UIColor.orange btn.setTitleColor(UIColor.white, for: UIControlState.normal) btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15.0) btn.addTarget(self, action: #selector(sendMsgBtnClick(_ :)), for: UIControlEvents.touchUpInside) btn.isEnabled = false return btn }() fileprivate lazy var emoticonBtn : UIButton = { let btn = UIButton(type: UIButtonType.custom) btn.frame = CGRect(x: 0, y: 0, width: kEmoticonBtnWidth, height: kEmoticonBtnWidth) btn.setImage(UIImage(named: "chat_btn_emoji"), for: .normal) btn.setImage(UIImage(named: "chat_btn_keyboard"), for: .selected) btn.addTarget(self, action: #selector(emoticonBtnClick(_:)), for: .touchUpInside) return btn }() fileprivate lazy var emoticonView : LJEmoticonView = { let emoticon = LJEmoticonView(frame: CGRect(x: 0, y: 0, width: kDeviceWidth, height: KEmoticonViewHeight)) return emoticon }() override init(frame: CGRect) { super.init(frame: frame) setupUI() } override func layoutSubviews() { super.layoutSubviews() inputTextField.frame = CGRect(x: kChatToolsViewMargin, y: kChatToolsViewMargin, width: kDeviceWidth - kChatToolsViewMargin * 3 - 60, height: self.bounds.height - kChatToolsViewMargin * 2) sendMsgBtn.frame = CGRect(x: self.inputTextField.frame.maxX + kChatToolsViewMargin, y: kChatToolsViewMargin, width: 60, height: self.bounds.height - kChatToolsViewMargin * 2) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension LJChatToolsView { fileprivate func setupUI() { addSubview(inputTextField) addSubview(sendMsgBtn) inputTextField.rightView = emoticonBtn inputTextField.rightViewMode = .always inputTextField.allowsEditingTextAttributes = true inputTextField.addTarget(self, action: #selector(textFieldDidEdit(_:)), for: UIControlEvents.editingChanged) emoticonView.emoticonClickCallback = { [weak self] emoticon in if emoticon.emoticonName == "delete-n" { self?.inputTextField.deleteBackward() return } guard let range = self?.inputTextField.selectedTextRange else { return } self?.inputTextField.replace(range, withText: emoticon.emoticonName) } } } extension LJChatToolsView { @objc fileprivate func textFieldDidEdit(_ textField : UITextField) { sendMsgBtn.isEnabled = textField.text?.characters.count != 0 } @objc fileprivate func sendMsgBtnClick(_ sender : UIButton) { let message = inputTextField.text! inputTextField.text = "" sender.isEnabled = false delegate?.chatToolsView(self, message: message) } @objc fileprivate func emoticonBtnClick(_ btn : UIButton) { btn.isSelected = !btn.isSelected let range = inputTextField.selectedTextRange inputTextField.resignFirstResponder() inputTextField.inputView = inputTextField.inputView == nil ? emoticonView : nil inputTextField.becomeFirstResponder() inputTextField.selectedTextRange = range } }
0cacdcfcbe3c20c23714789d9aa87d2a
33.765217
195
0.656328
false
false
false
false
jotade/onthemap-udacity
refs/heads/master
onthemap/FindOnTheMapViewController.swift
gpl-3.0
1
// // FindOnTheMapViewController.swift // onthemap // // Created by IM Development on 7/27/17. // Copyright © 2017 IM Development. All rights reserved. // import UIKit import CoreLocation class FindOnTheMapViewController: UIViewController { @IBOutlet weak var findButton: UIButton! @IBOutlet weak var locationTextField: UITextField! let geocoder = CLGeocoder() var activityIndicator: UIView? func geocodeLocation(city: String){ geocoder.geocodeAddressString(city) { (placemarks, error) in if error != nil{ print(error!.localizedDescription) self.activityIndicator?.removeFromSuperview() Utils.showAlert(with: "Error", message: "couldn't find your location!", viewController: self, isDefault: true, actions: nil) return } if let place = placemarks?.first, let coordinate = place.location?.coordinate, let name = place.name, let country = place.country{ AuthService.instance.currentStudent?.latitude = coordinate.latitude AuthService.instance.currentStudent?.longitude = coordinate.longitude AuthService.instance.currentStudent?.mapString = "\(name), \(country)" NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showLocation"), object: nil) self.dismiss(animated: true) { self.activityIndicator?.removeFromSuperview() } } } } @IBAction func find(_ sender: UIButton) { guard let location = locationTextField.text , locationTextField.text != "" else { Utils.showAlert(with: "Oops", message: "You forgot to put your location!", viewController: self, isDefault: true, actions: nil) return } activityIndicator = Utils.showActivityIndicatory(uiView: self.view) geocodeLocation(city: location) } @IBAction func cancel(_ sender: UIButton) { dismiss(animated: true, completion: nil) } }
e7a2ca9dca46fb71c42024dbe16a3da1
33.318182
142
0.58543
false
false
false
false
hhroc/yellr-ios
refs/heads/master
Yellr/Yellr/ProfileViewController.swift
mit
1
// // ProfileViewController.swift // Yellr // // Created by Debjit Saha on 6/15/15. // Copyright (c) 2015 wxxi. All rights reserved. // import UIKit import CoreLocation class ProfileViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var resetCuidButton: UIBarButtonItem! @IBOutlet weak var cancelButton: UIBarButtonItem! @IBOutlet weak var cuidValue: UILabel! @IBOutlet weak var userName: UILabel! @IBOutlet weak var verified: UILabel! @IBOutlet weak var userLogo: UILabel! @IBOutlet weak var postsLogo: UILabel! @IBOutlet weak var postsViewedLogo: UILabel! @IBOutlet weak var postsUsedLogo: UILabel! @IBOutlet weak var postsLabel: UILabel! @IBOutlet weak var postsViewedLabel: UILabel! @IBOutlet weak var postsUsedLabel: UILabel! @IBOutlet weak var postsCount: UILabel! @IBOutlet weak var postsViewedCount: UILabel! @IBOutlet weak var postsUsedCount: UILabel! @IBOutlet weak var tapToVerify: UIButton! var latitude:String = "" var longitude:String = "" var profileUrlEndpoint: String = "" var webActivityIndicator : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) var urlSession = NSURLSession.sharedSession() var locationManager: CLLocationManager = CLLocationManager() var startLocation: CLLocation! override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString(YellrConstants.Profile.Title, comment: "Profile Screen title") self.cancelButton.title = NSLocalizedString(YellrConstants.Common.BackButton, comment: "Profile Screen back button") self.resetCuidButton.title = NSLocalizedString(YellrConstants.Profile.ResetCUIDButton, comment: "Profile Screen Reset CUID button") self.cuidValue.text = "CUID: " + getCUID() self.tapToVerify.hidden = true self.postsLogo.font = UIFont.fontAwesome(size: 14) self.postsLogo.text = "\(String.fontAwesome(unicode: 0xf0e5)) " self.postsViewedLogo.font = UIFont.fontAwesome(size: 14) self.postsViewedLogo.text = "\(String.fontAwesome(unicode: 0xf06e)) " self.postsUsedLogo.font = UIFont.fontAwesome(size: 14) self.postsUsedLogo.text = "\(String.fontAwesome(unicode: 0xf075)) " self.verified.font = UIFont.fontAwesome(size: 13) self.verified.text = "\(String.fontAwesome(unicode: 0xf00d)) " + NSLocalizedString(YellrConstants.Profile.Unverified, comment: "Profile Screen Unverified") self.userLogo.font = UIFont.fontAwesome(size: 44) self.userLogo.text = "\(String.fontAwesome(unicode: 0xf21b)) " self.userLogo.backgroundColor = UIColorFromRGB(YellrConstants.Colors.dark_yellow) self.postsLabel.text = NSLocalizedString(YellrConstants.Profile.PostsLabel, comment: "Profile Screen Posts") self.postsViewedLabel.text = NSLocalizedString(YellrConstants.Profile.PostsViewedLabel, comment: "Profile Screen Posts Viewed") self.postsUsedLabel.text = NSLocalizedString(YellrConstants.Profile.PostsUsedLabel, comment: "Profile Screen Posts Used") let resetCuidBarButtonItem:UIBarButtonItem = UIBarButtonItem(fontAwesome: "f084", target: self, action: "resetCuidTapped:") self.navigationItem.setRightBarButtonItems([resetCuidBarButtonItem], animated: true) } //for the location object override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //location locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.delegate = self //this check is needed to add the additional //location methods for ios8 if #available(iOS 8.0, *) { locationManager.requestWhenInUseAuthorization() } else { } locationManager.startUpdatingLocation() startLocation = nil } //dismiss the profilemodal on pressing cancel @IBAction func cancelPressed(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil); } func resetCuidTapped(sender: UIBarButtonItem) { let alert = UIAlertView() alert.title = NSLocalizedString(YellrConstants.Profile.ResetDialogTitle, comment: "Reset Dialog Title") alert.message = NSLocalizedString(YellrConstants.Profile.ResetDialogMessage, comment: "Reset Dialog Message") alert.addButtonWithTitle(NSLocalizedString(YellrConstants.Profile.ResetDialogConfirm, comment: "Yes")) alert.addButtonWithTitle(NSLocalizedString(YellrConstants.Common.CancelButton, comment: "Cancel")) alert.cancelButtonIndex = 1 alert.tag=213 alert.delegate = self alert.show() } // MARK: - Networking func requestProfile(endPointURL : String, responseHandler : (error : NSError? , items : Array<LocalPostDataModel>?) -> () ) -> () { let url:NSURL = NSURL(string: endPointURL)! let task = self.urlSession.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in //Yellr.println(response) //Yellr.println(error) if (error == nil) { self.profileItems(data!) responseHandler( error: nil, items: nil) } else { Yellr.println(error) } }) task.resume() } @IBAction func tapToVerifyPressed(sender: UIButton) { self.performSegueWithIdentifier("ProfileVerifySegue", sender: sender) } func profileItems(data: NSData) -> Void { //var jsonParseError: NSError? do { if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { //var pr_first_name = jsonResult["first_name"] as! String //var pr_last_name = jsonResult["last_name"] as! String let pr_verified = jsonResult["verified"] as! Bool //var pr_success = jsonResult["success"] as! Bool let pr_post_count = jsonResult["post_count"] as! Int let pr_post_view_count = jsonResult["post_view_count"] as! Int //var pr_organization = jsonResult["organization"] as! String let pr_post_used_count = jsonResult["post_used_count"] as! Int //var pr_email = jsonResult["email"] as! String dispatch_async(dispatch_get_main_queue()!, { () -> Void in self.postsCount.text = String(pr_post_count) self.postsUsedCount.text = String(pr_post_used_count) self.postsViewedCount.text = String(pr_post_view_count) if (pr_verified) { //self.tapToVerify.hidden = true } else { //self.tapToVerify.hidden = false } }) } else { } } catch _ { } } //MARK: Location Delegate functions func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let latestLocation: AnyObject = locations[locations.count - 1] self.latitude = String(format: "%.2f", latestLocation.coordinate.latitude) self.longitude = String(format: "%.2f", latestLocation.coordinate.longitude) //store lat long in prefs let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(self.latitude, forKey: YellrConstants.Direction.Latitude) defaults.setObject(self.longitude, forKey: YellrConstants.Direction.Longitude) defaults.synchronize() self.profileUrlEndpoint = buildUrl("get_profile.json", latitude: self.latitude, longitude: self.longitude) self.requestProfile(self.profileUrlEndpoint, responseHandler: { (error, items) -> () in //TODO: update UI code here //Yellr.println("1") }) locationManager.stopUpdatingLocation() } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { Yellr.println(error) let alert = UIAlertView() alert.title = NSLocalizedString(YellrConstants.Location.Title, comment: "Location Error Title") alert.message = NSLocalizedString(YellrConstants.Location.Message, comment: "Location Error Message") alert.addButtonWithTitle(NSLocalizedString(YellrConstants.Location.Okay, comment: "Okay")) alert.show() } //MARK: Alert View Delegates func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){ Yellr.println(View.tag) //identifier for the reset dialog if (View.tag == 213) { Yellr.println(buttonIndex) //first time post notify switch buttonIndex{ case 0: //reset the cuid let cuid = resetCUID() dispatch_async(dispatch_get_main_queue()){ self.cuidValue.text = "CUID: " + cuid self.postsCount.text = String("0") self.postsViewedCount.text = String("0") self.postsUsedCount.text = String("0") } break; default: break; } } } }
b9896c30938417eb2e5202d4974a2b1a
40.910638
165
0.62368
false
false
false
false
samantharachelb/todolist
refs/heads/master
todolist/AppDelegate.swift
mit
1
// // AppDelegate.swift // todolist // // Created by Samantha Emily-Rachel Belnavis on 2017-10-02. // Copyright © 2017 Samantha Emily-Rachel Belnavis. All rights reserved. // import UIKit import CoreData import Firebase import GoogleSignIn import SwiftyPlistManager import HealthKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate { var window: UIWindow? // true: display debug info // false: don't display debug info var debugMode: Bool = true // app specific variables var connectionAvailable: Bool! var plistPathInDocument: String = String() let userDefaults = UserDefaults.standard let plistManager = SwiftyPlistManager.shared // plist list var userPrefs = "UserPrefs" var themesPlist = "ThemesList" // individual theme property lists var theme0 = "defaultTheme" var theme1 = "lightTheme" var theme2 = "darkTheme" var theme3 = "tangerineTheme" var theme4 = "sunflowerTheme" var theme5 = "cloverTheme" var theme6 = "blueberryTheme" var theme7 = "skyBlueTheme" var theme8 = "amethystTheme" var theme9 = "graphiteTheme" // user info variables var googleUserId = String() var googleUserName = String() var googleUserEmail = String() var googleUserPhoto = String() var userGender = String() var userAge = String() var userBirthday = String() // create database reference var databaseRef: DatabaseReference! // internet connectivity var internetConnected: Bool! // theme things var navbarAppearance = UINavigationBar.appearance() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // initialize firebase application FirebaseApp.configure() let settings = FirestoreSettings() settings.isPersistenceEnabled = true let db = Firestore.firestore() db.settings = settings Database.database().isPersistenceEnabled = true // google login instance setup GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID GIDSignIn.sharedInstance().delegate = self plistManager.start(plistNames: [userPrefs, themesPlist, theme0, theme1, theme2, theme3, theme4, theme5, theme6, theme7, theme8, theme9], logging: true) // get the name of the currently selected theme let currentTheme = plistManager.fetchValue(for: "selectedAppTheme", fromPlistWithName: userPrefs) as! String! // get colours from theme file let headerBarColour = plistManager.fetchValue(for: "headerBarColour", fromPlistWithName: currentTheme!) as! String! let headerTextColour = plistManager.fetchValue(for: "headerTextColour", fromPlistWithName: currentTheme!) as! String! UINavigationBar.appearance().barTintColor = UIColor().hexToColour(hexString: headerBarColour!) UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor().hexToColour(hexString: headerTextColour!)] return true } func checkInternet() { guard let status = Network.reachability?.status else { return } switch status { case .unreachable: print ("Internet unreachable") return connectionAvailable = false case .wifi: print ("Internet reachable") return connectionAvailable = true case .wwan: print ("Internet reachable") return connectionAvailable = true } } func getIdentifyingHealthKitData() throws -> (age: Int, birthDate: String, gender: HKBiologicalSex) { // database reference self.databaseRef = Database.database().reference().child("user_profiles").child(self.googleUserId) let healthKitStore = HKHealthStore() do { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US") dateFormatter.setLocalizedDateFormatFromTemplate("MMM-dd-yyyy") let birthdayComponents = try healthKitStore.dateOfBirthComponents() let gender = try healthKitStore.biologicalSex() let today = Date() let calendar = Calendar.current let currentDateComponents = calendar.dateComponents([.year], from: today) let thisYear = currentDateComponents.year! let age = thisYear - birthdayComponents.year! let dateToDisplay = calendar.date(from: birthdayComponents)! let birthDate = dateFormatter.string(from: dateToDisplay) let unwrappedGender = gender.biologicalSex return (age, birthDate, unwrappedGender) } } func saveUserInfo() { self.databaseRef = Database.database().reference().child("user_profiles").child(self.googleUserId) self.databaseRef.observeSingleEvent(of: .value, with: { (snapshot) in let snapshot = snapshot.value as? NSDictionary // if values don't exist in the database, save them to the database // otherwise update the values if (snapshot == nil) { self.databaseRef.child("user_id").setValue(self.googleUserId) self.databaseRef.child("user_name").setValue(self.googleUserId) self.databaseRef.child("user_gender").setValue(self.userGender) self.databaseRef.child("user_age").setValue(self.userAge) self.databaseRef.child("user_birthday").setValue(self.userBirthday) } }) // save to plist for offline functionality plistManager.save(self.googleUserId as String!, forKey: "user_id", toPlistWithName: userPrefs) { (err) in if (err == nil) { return } } plistManager.save(self.googleUserName as String!, forKey: "user_name", toPlistWithName: userPrefs) { (err) in if (err == nil) { return } } plistManager.save(self.googleUserEmail as String!, forKey: "user_email", toPlistWithName: userPrefs) { (err) in if (err == nil) { return } } plistManager.save(self.googleUserPhoto as String!, forKey: "user_photo_url", toPlistWithName: userPrefs) { (err) in if (err == nil) { return } } plistManager.save(self.userGender, forKey: "user_gender", toPlistWithName: userPrefs) { (err) in if (err == nil) { return } } plistManager.save(self.userAge, forKey: "user_age", toPlistWithName: userPrefs) { (err) in if (err == nil) { return } } plistManager.save(self.userBirthday, forKey: "user_birthday", toPlistWithName: userPrefs) { (err) in if (err == nil) { return } } if (debugMode) { debugPrint("User info was saved") } } func sign(_ signIn: GIDSignIn, didSignInFor user: GIDGoogleUser!, withError error: Error?) { if error != nil { return } guard let authentication = user.authentication else { return } let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken) // retrieve details from the google user's profile googleUserId = user.userID googleUserName = user.profile.name googleUserEmail = user.profile.email googleUserPhoto = "\(String(describing: user.profile.imageURL(withDimension: 100 * UInt(UIScreen.main.scale))!))" let userIdentifyingInfo = try? getIdentifyingHealthKitData() let userGender = userIdentifyingInfo?.gender.stringRepresentation let userAge = userIdentifyingInfo?.age let userBirthday = userIdentifyingInfo?.birthDate if (debugMode == true) { debugPrint("retrieved userID: ", self.googleUserId) debugPrint("retrieved user_name: ", self.googleUserName) debugPrint("retrieved user_email: ", self.googleUserEmail) debugPrint("retrieved user_photo_url: ", self.googleUserPhoto) debugPrint("retrieved user_gender: ", userGender) debugPrint("retrieved user_age: ", userAge!) debugPrint("retrieved user_birthday: ", userBirthday) } // save information saveUserInfo() Auth.auth().signIn(with: credential) { (user, error) in if error != nil { return } } return } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { // create / return container for appplication let container = NSPersistentContainer(name: "todolist") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } static func shared() -> AppDelegate { return UIApplication.shared.delegate as! AppDelegate } }
43f6fb38a4c4540fc9f2890dc73ea197
38.352313
281
0.703201
false
false
false
false
jovito-royeca/ManaKit
refs/heads/master
Example/ManaKit/Maintainer/Maintainer.swift
mit
1
// // Maintainer.swift // ManaKit_Example // // Created by Jovito Royeca on 23/10/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import ManaKit import PostgresClientKit import PromiseKit import SSZipArchive class Maintainer: NSObject { // MARK: - Constants let printMilestone = 1000 let bulkDataFileName = "scryfall-bulkData.json" let setsFileName = "scryfall-sets.json" let keyruneFileName = "keyrune.html" let comprehensiveRulesFileName = "MagicCompRules 20200807" // let setCodesForProcessing:[String]? = nil let storeName = "TCGPlayer" // MARK: - Variables var tcgplayerAPIToken = "" var dateStart = Date() var cardsRemotePath = "" var rulingsRemotePath = "" let setsModel = SetsViewModel() var _bulkArray: [[String: Any]]? var bulkArray: [[String: Any]] { get { if _bulkArray == nil { _bulkArray = self.bulkData() } return _bulkArray! } } var _setsArray: [[String: Any]]? var setsArray: [[String: Any]] { get { if _setsArray == nil { _setsArray = self.setsData() } return _setsArray! } } var _cardsArray: [[String: Any]]? var cardsArray: [[String: Any]] { get { if _cardsArray == nil { _cardsArray = self.cardsData() } return _cardsArray! } } var _rulingsArray: [[String: Any]]? var rulingsArray: [[String: Any]] { get { if _rulingsArray == nil { _rulingsArray = self.rulingsData() } return _rulingsArray! } } var _rulesArray: [String]? var rulesArray: [String] { get { if _rulesArray == nil { _rulesArray = self.rulesData() } return _rulesArray! } } // MARK: - Database methods func checkServerInfo() { let viewModel = ServerInfoViewModel() firstly { viewModel.fetchRemoteData() }.compactMap { (data, result) in try JSONSerialization.jsonObject(with: data) as? [[String: Any]] }.then { data in viewModel.saveLocalData(data: data) }.then { viewModel.fetchLocalData() }.done { if let serverInfo = viewModel.allObjects()?.first as? MGServerInfo { if serverInfo.scryfallVersion != ManaKit.Constants.ScryfallDate { viewModel.deleteAllCache() self.updateDatabase() } } }.catch { error in print(error) } } func createConnection() -> Connection { var configuration = PostgresClientKit.ConnectionConfiguration() configuration.host = "192.168.1.182" configuration.port = 5432 configuration.database = "managuide_prod" configuration.user = "managuide" configuration.credential = .cleartextPassword(password: "DarkC0nfidant") configuration.ssl = false do { let connection = try PostgresClientKit.Connection(configuration: configuration) return connection } catch { fatalError("\(error)") } } private func updateDatabase() { guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else { fatalError("Malformed cachePath") } let bulkDataLocalPath = "\(cachePath)/\(ManaKit.Constants.ScryfallDate)_\(bulkDataFileName)" let bulkDataRemotePath = "https://api.scryfall.com/bulk-data" let setsLocalPath = "\(cachePath)/\(ManaKit.Constants.ScryfallDate)_\(setsFileName)" let setsRemotePath = "https://api.scryfall.com/sets" let keyruneLocalPath = "\(cachePath)/\(ManaKit.Constants.ScryfallDate)_\(keyruneFileName)" let keyruneRemotePath = "https://keyrune.andrewgioia.com/cheatsheet.html" startActivity() firstly { fetchData(localPath: bulkDataLocalPath, remotePath: bulkDataRemotePath) }.then { self.createBulkData() }.then { self.fetchData(localPath: setsLocalPath, remotePath: setsRemotePath) }.then { self.fetchData(localPath: keyruneLocalPath, remotePath: keyruneRemotePath) }.then { self.fetchData(localPath: "\(cachePath)/\(self.cardsRemotePath.components(separatedBy: "/").last ?? "")", remotePath: self.cardsRemotePath) }.then { self.fetchData(localPath: "\(cachePath)/\(self.rulingsRemotePath.components(separatedBy: "/").last ?? "")", remotePath: self.rulingsRemotePath) }.then { self.createSetsData() }.then { self.createCardsData() }.then { self.createRulingsData() }.then { self.createRulesData() }.then { self.createOtherCardsData() }.then { self.createPricingData() }.then { self.fetchCardImages() }.then { self.createScryfallPromise() }.done { self.endActivity() }.catch { error in print(error) } } private func createBulkData() -> Promise<Void> { return Promise { seal in let _ = bulkArray seal.fulfill(()) } } private func createSetsData() -> Promise<Void> { return Promise { seal in let connection = createConnection() var promises = [()->Promise<Void>]() promises.append(contentsOf: self.filterSetBlocks(array: setsArray, connection: connection)) promises.append(contentsOf: self.filterSetTypes(array: setsArray, connection: connection)) promises.append(contentsOf: self.filterSets(array: setsArray, connection: connection)) promises.append(contentsOf: self.createKeyrunePromises(array: setsArray, connection: connection)) let completion = { connection.close() seal.fulfill(()) } self.execInSequence(label: "createSetsData", promises: promises, completion: completion) } } private func createCardsData() -> Promise<Void> { return Promise { seal in let connection = createConnection() var promises = [()->Promise<Void>]() // cards promises.append(contentsOf: self.filterArtists(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterRarities(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterLanguages(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterWatermarks(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterLayouts(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterFrames(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterFrameEffects(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterColors(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterFormats(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterLegalities(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterTypes(array: cardsArray, connection: connection)) promises.append(contentsOf: self.filterComponents(array: cardsArray, connection: connection)) promises.append(contentsOf: cardsArray.map { dict in return { return self.createCardPromise(dict: dict, connection: connection) } }) // parts promises.append({ return self.createDeletePartsPromise(connection: connection) }) promises.append(contentsOf: self.filterParts(array: cardsArray, connection: connection)) // faces promises.append({ return self.createDeleteFacesPromise(connection: connection) }) promises.append(contentsOf: self.filterFaces(array: cardsArray, connection: connection)) let completion = { connection.close() seal.fulfill(()) } self.execInSequence(label: "createCardsData", promises: promises, completion: completion) } } private func createRulingsData() -> Promise<Void> { return Promise { seal in let connection = createConnection() var promises = [()->Promise<Void>]() promises.append({ return self.createDeleteRulingsPromise(connection: connection) }) promises.append(contentsOf: rulingsArray.map { dict in return { return self.createRulingPromise(dict: dict, connection: connection) } }) let completion = { connection.close() seal.fulfill(()) } self.execInSequence(label: "createRulingsData", promises: promises, completion: completion) } } private func createRulesData() -> Promise<Void> { return Promise { seal in let connection = createConnection() var promises = [()->Promise<Void>]() promises.append({ return self.createDeleteRulesPromise(connection: connection) }) promises.append(contentsOf: self.filterRules(lines: rulesArray, connection: connection)) let completion = { connection.close() seal.fulfill(()) } self.execInSequence(label: "createRulesData", promises: promises, completion: completion) } } private func createOtherCardsData() -> Promise<Void> { return Promise { seal in let promises = [createOtherLanguagesPromise(), createOtherPrintingsPromise(), createVariationsPromise()] print("Start createOtherCardsData:") firstly { when(fulfilled: promises) }.done { print("End createOtherCardsData!") seal.fulfill(()) }.catch { error in seal.reject(error) } } } private func createPricingData() -> Promise<Void> { return Promise { seal in let connection = createConnection() firstly { self.createStorePromise(name: self.storeName, connection: connection) }.then { self.getTcgPlayerToken() }.then { self.fetchSets() }.then { groupIds in self.fetchTcgPlayerCardPricing(groupIds: groupIds, connection: connection) }.done { promises in let completion = { connection.close() seal.fulfill(()) } self.execInSequence(label: "createPricingData", promises: promises, completion: completion) }.catch { error in seal.reject(error) } } } func bulkData() -> [[String: Any]] { guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else { fatalError("Malformed cachePath") } let bulkDataPath = "\(cachePath)/\(ManaKit.Constants.ScryfallDate)_\(bulkDataFileName)" let data = try! Data(contentsOf: URL(fileURLWithPath: bulkDataPath)) guard let dict = try! JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else { fatalError("Malformed data") } guard let array = dict["data"] as? [[String: Any]] else { fatalError("Malformed data") } for dict in array { for (k,v) in dict { if k == "name" { if let value = v as? String { switch value { case "All Cards": self.cardsRemotePath = dict["download_uri"] as! String case "Rulings": self.rulingsRemotePath = dict["download_uri"] as! String default: () } } } } } return array } // MARK: - Promise methods func fetchData(localPath: String, remotePath: String) -> Promise<Void> { return Promise { seal in let willFetch = !FileManager.default.fileExists(atPath: localPath) if willFetch { guard let urlString = remotePath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: urlString) else { fatalError("Malformed url") } var rq = URLRequest(url: url) rq.httpMethod = "GET" firstly { URLSession.shared.downloadTask(.promise, with: rq, to: URL(fileURLWithPath: localPath)) }.done { _ in seal.fulfill(()) }.catch { error in seal.reject(error) } } else { seal.fulfill(()) } } } func createPromise(with query: String, parameters: [Any]?, connection: Connection?) -> Promise<Void> { return Promise { seal in if let connection = connection { execPG(query: query, parameters: parameters, connection: connection) seal.fulfill(()) } else { let conn = createConnection() execPG(query: query, parameters: parameters, connection: conn) conn.close() seal.fulfill(()) } } } private func execPG(query: String, parameters: [Any]?, connection: Connection) { do { let statement = try connection.prepareStatement(text: query) if let parameters = parameters { var convertibles = [PostgresValueConvertible]() for parameter in parameters { if let c = parameter as? PostgresValueConvertible { convertibles.append(c) } } try statement.execute(parameterValues: convertibles) } else { try statement.execute() } statement.close() } catch { fatalError("\(error)") } } func execInSequence(label: String, promises: [()->Promise<Void>], completion: @escaping () -> Void) { var promise = promises.first!() let countTotal = promises.count var countIndex = 0 print("Start \(label):") print("Exec... \(countIndex)/\(countTotal) \(Date())") for next in promises { promise = promise.then { n -> Promise<Void> in countIndex += 1 if countIndex % self.printMilestone == 0 { print("Exec... \(countIndex)/\(countTotal) \(Date())") } return next() } } promise.done {_ in print("Exec... \(countIndex)/\(countTotal) \(Date())") print("Done \(label)!") completion() }.catch { error in print(error) completion() } } // MARK: - Utility methods func sectionFor(name: String) -> String? { if name.count == 0 { return nil } else { let letters = CharacterSet.letters var prefix = String(name.prefix(1)) if prefix.rangeOfCharacter(from: letters) == nil { prefix = "#" } return prefix.uppercased().folding(options: .diacriticInsensitive, locale: .current) } } func displayFor(name: String) -> String { var display = "" let components = name.components(separatedBy: "_") if components.count > 1 { for e in components { var cap = e if e != "the" || e != "a" || e != "an" || e != "and" { cap = e.prefix(1).uppercased() + e.dropFirst() } if display.count > 0 { display.append(" ") } display.append(cap) } } else { display = name } return display } func capitalize(string: String) -> String { if string.count == 0 { return string } else { return (string.prefix(1).uppercased() + string.dropFirst()).replacingOccurrences(of: "_", with: " ") } } /* * Converts @param string into double equivalents i.e. 100.1a = 100.197 * Useful for ordering in NSSortDescriptor. */ func order(of string: String) -> Double { var termOrder = Double(0) if let num = Double(string) { termOrder = num } else { let digits = NSCharacterSet.decimalDigits var numString = "" var charString = "" for c in string.unicodeScalars { if c == "." || digits.contains(c) { numString.append(String(c)) } else { charString.append(String(c)) } } if let num = Double(numString) { termOrder = num } if charString.count > 0 { for c in charString.unicodeScalars { let s = String(c).unicodeScalars termOrder += Double(s[s.startIndex].value) / 100 } } } return termOrder } func startActivity() { dateStart = Date() print("Starting on... \(dateStart)") } func endActivity() { let dateEnd = Date() let timeDifference = dateEnd.timeIntervalSince(dateStart) print("Total Time Elapsed on: \(dateStart) - \(dateEnd) = \(format(timeDifference))") print("docsPath = \(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])") } func format(_ interval: TimeInterval) -> String { if interval == 0 { return "HH:mm:ss" } let seconds = interval.truncatingRemainder(dividingBy: 60) let minutes = (interval / 60).truncatingRemainder(dividingBy: 60) let hours = (interval / 3600) return String(format: "%.2d:%.2d:%.2d", Int(hours), Int(minutes), Int(seconds)) } }
228bdde2432b3fb3641d8c2739da9564
34.114385
155
0.514042
false
false
false
false
JaSpa/swift
refs/heads/master
stdlib/public/SDK/Foundation/NSError.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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import CoreFoundation import Darwin //===----------------------------------------------------------------------===// // NSError (as an out parameter). //===----------------------------------------------------------------------===// public typealias NSErrorPointer = AutoreleasingUnsafeMutablePointer<NSError?>? // Note: NSErrorPointer becomes ErrorPointer in Swift 3. public typealias ErrorPointer = NSErrorPointer public // COMPILER_INTRINSIC let _nilObjCError: Error = _GenericObjCError.nilError @_silgen_name("swift_convertNSErrorToError") public // COMPILER_INTRINSIC func _convertNSErrorToError(_ error: NSError?) -> Error { if let error = error { return error } return _nilObjCError } @_silgen_name("swift_convertErrorToNSError") public // COMPILER_INTRINSIC func _convertErrorToNSError(_ error: Error) -> NSError { return unsafeDowncast(_bridgeErrorToNSError(error), to: NSError.self) } /// Describes an error that provides localized messages describing why /// an error occurred and provides more information about the error. public protocol LocalizedError : Error { /// A localized message describing what error occurred. var errorDescription: String? { get } /// A localized message describing the reason for the failure. var failureReason: String? { get } /// A localized message describing how one might recover from the failure. var recoverySuggestion: String? { get } /// A localized message providing "help" text if the user requests help. var helpAnchor: String? { get } } public extension LocalizedError { var errorDescription: String? { return nil } var failureReason: String? { return nil } var recoverySuggestion: String? { return nil } var helpAnchor: String? { return nil } } @_silgen_name("NS_Swift_performErrorRecoverySelector") internal func NS_Swift_performErrorRecoverySelector( delegate: AnyObject?, selector: Selector, success: ObjCBool, contextInfo: UnsafeMutableRawPointer?) /// Class that implements the informal protocol /// NSErrorRecoveryAttempting, which is used by NSError when it /// attempts recovery from an error. class _NSErrorRecoveryAttempter { @objc(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:) func attemptRecovery(fromError nsError: NSError, optionIndex recoveryOptionIndex: Int, delegate: AnyObject?, didRecoverSelector: Selector, contextInfo: UnsafeMutableRawPointer?) { let error = nsError as Error as! RecoverableError error.attemptRecovery(optionIndex: recoveryOptionIndex) { success in NS_Swift_performErrorRecoverySelector( delegate: delegate, selector: didRecoverSelector, success: ObjCBool(success), contextInfo: contextInfo) } } @objc(attemptRecoveryFromError:optionIndex:) func attemptRecovery(fromError nsError: NSError, optionIndex recoveryOptionIndex: Int) -> Bool { let error = nsError as Error as! RecoverableError return error.attemptRecovery(optionIndex: recoveryOptionIndex) } } /// Describes an error that may be recoverable by presenting several /// potential recovery options to the user. public protocol RecoverableError : Error { /// Provides a set of possible recovery options to present to the user. var recoveryOptions: [String] { get } /// Attempt to recover from this error when the user selected the /// option at the given index. This routine must call handler and /// indicate whether recovery was successful (or not). /// /// This entry point is used for recovery of errors handled at a /// "document" granularity, that do not affect the entire /// application. func attemptRecovery(optionIndex recoveryOptionIndex: Int, resultHandler handler: (_ recovered: Bool) -> Void) /// Attempt to recover from this error when the user selected the /// option at the given index. Returns true to indicate /// successful recovery, and false otherwise. /// /// This entry point is used for recovery of errors handled at /// the "application" granularity, where nothing else in the /// application can proceed until the attempted error recovery /// completes. func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool } public extension RecoverableError { /// Default implementation that uses the application-model recovery /// mechanism (``attemptRecovery(optionIndex:)``) to implement /// document-modal recovery. func attemptRecovery(optionIndex recoveryOptionIndex: Int, resultHandler handler: (_ recovered: Bool) -> Void) { handler(attemptRecovery(optionIndex: recoveryOptionIndex)) } } /// Describes an error type that specifically provides a domain, code, /// and user-info dictionary. public protocol CustomNSError : Error { /// The domain of the error. static var errorDomain: String { get } /// The error code within the given domain. var errorCode: Int { get } /// The user-info dictionary. var errorUserInfo: [String : Any] { get } } public extension CustomNSError { /// Default domain of the error. static var errorDomain: String { return String(reflecting: self) } /// The error code within the given domain. var errorCode: Int { return _swift_getDefaultErrorCode(self) } /// The default user-info dictionary. var errorUserInfo: [String : Any] { return [:] } } extension CustomNSError where Self: RawRepresentable, Self.RawValue: SignedInteger { // The error code of Error with integral raw values is the raw value. public var errorCode: Int { return numericCast(self.rawValue) } } extension CustomNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger { // The error code of Error with integral raw values is the raw value. public var errorCode: Int { return numericCast(self.rawValue) } } public extension Error where Self : CustomNSError { /// Default implementation for customized NSErrors. var _domain: String { return Self.errorDomain } /// Default implementation for customized NSErrors. var _code: Int { return self.errorCode } } public extension Error where Self: CustomNSError, Self: RawRepresentable, Self.RawValue: SignedInteger { /// Default implementation for customized NSErrors. var _code: Int { return self.errorCode } } public extension Error where Self: CustomNSError, Self: RawRepresentable, Self.RawValue: UnsignedInteger { /// Default implementation for customized NSErrors. var _code: Int { return self.errorCode } } public extension Error { /// Retrieve the localized description for this error. var localizedDescription: String { return (self as NSError).localizedDescription } } internal let _errorDomainUserInfoProviderQueue = DispatchQueue( label: "SwiftFoundation._errorDomainUserInfoProviderQueue") /// Retrieve the default userInfo dictionary for a given error. @_silgen_name("swift_Foundation_getErrorDefaultUserInfo") public func _swift_Foundation_getErrorDefaultUserInfo(_ error: Error) -> AnyObject? { let hasUserInfoValueProvider: Bool // If the OS supports user info value providers, use those // to lazily populate the user-info dictionary for this domain. if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { // Note: the Cocoa error domain specifically excluded from // user-info value providers. let domain = error._domain if domain != NSCocoaErrorDomain { _errorDomainUserInfoProviderQueue.sync { if NSError.userInfoValueProvider(forDomain: domain) != nil { return } NSError.setUserInfoValueProvider(forDomain: domain) { (nsError, key) in let error = nsError as Error switch key { case NSLocalizedDescriptionKey: return (error as? LocalizedError)?.errorDescription case NSLocalizedFailureReasonErrorKey: return (error as? LocalizedError)?.failureReason case NSLocalizedRecoverySuggestionErrorKey: return (error as? LocalizedError)?.recoverySuggestion case NSHelpAnchorErrorKey: return (error as? LocalizedError)?.helpAnchor case NSLocalizedRecoveryOptionsErrorKey: return (error as? RecoverableError)?.recoveryOptions case NSRecoveryAttempterErrorKey: if error is RecoverableError { return _NSErrorRecoveryAttempter() } return nil default: return nil } } } assert(NSError.userInfoValueProvider(forDomain: domain) != nil) hasUserInfoValueProvider = true } else { hasUserInfoValueProvider = false } } else { hasUserInfoValueProvider = false } // Populate the user-info dictionary var result: [String : Any] // Initialize with custom user-info. if let customNSError = error as? CustomNSError { result = customNSError.errorUserInfo } else { result = [:] } // Handle localized errors. If we registered a user-info value // provider, these will computed lazily. if !hasUserInfoValueProvider, let localizedError = error as? LocalizedError { if let description = localizedError.errorDescription { result[NSLocalizedDescriptionKey] = description } if let reason = localizedError.failureReason { result[NSLocalizedFailureReasonErrorKey] = reason } if let suggestion = localizedError.recoverySuggestion { result[NSLocalizedRecoverySuggestionErrorKey] = suggestion } if let helpAnchor = localizedError.helpAnchor { result[NSHelpAnchorErrorKey] = helpAnchor } } // Handle recoverable errors. If we registered a user-info value // provider, these will computed lazily. if !hasUserInfoValueProvider, let recoverableError = error as? RecoverableError { result[NSLocalizedRecoveryOptionsErrorKey] = recoverableError.recoveryOptions result[NSRecoveryAttempterErrorKey] = _NSErrorRecoveryAttempter() } return result as AnyObject } // NSError and CFError conform to the standard Error protocol. Compiler // magic allows this to be done as a "toll-free" conversion when an NSError // or CFError is used as an Error existential. extension NSError : Error { public var _domain: String { return domain } public var _code: Int { return code } public var _userInfo: AnyObject? { return userInfo as NSDictionary } /// The "embedded" NSError is itself. public func _getEmbeddedNSError() -> AnyObject? { return self } } extension CFError : Error { public var _domain: String { return CFErrorGetDomain(self) as String } public var _code: Int { return CFErrorGetCode(self) } public var _userInfo: AnyObject? { return CFErrorCopyUserInfo(self) as AnyObject } /// The "embedded" NSError is itself. public func _getEmbeddedNSError() -> AnyObject? { return self } } // An error value to use when an Objective-C API indicates error // but produces a nil error object. public enum _GenericObjCError : Error { case nilError } /// An internal protocol to represent Swift error enums that map to standard /// Cocoa NSError domains. public protocol _ObjectiveCBridgeableError : Error { /// Produce a value of the error type corresponding to the given NSError, /// or return nil if it cannot be bridged. init?(_bridgedNSError: NSError) } /// A hook for the runtime to use _ObjectiveCBridgeableError in order to /// attempt an "errorTypeValue as? SomeError" cast. /// /// If the bridge succeeds, the bridged value is written to the uninitialized /// memory pointed to by 'out', and true is returned. Otherwise, 'out' is /// left uninitialized, and false is returned. @_silgen_name("swift_stdlib_bridgeNSErrorToError") public func _stdlib_bridgeNSErrorToError< T : _ObjectiveCBridgeableError >(_ error: NSError, out: UnsafeMutablePointer<T>) -> Bool { if let bridged = T(_bridgedNSError: error) { out.initialize(to: bridged) return true } else { return false } } /// Helper protocol for _BridgedNSError, which used to provide /// default implementations. public protocol __BridgedNSError : Error { static var _nsErrorDomain: String { get } } // Allow two bridged NSError types to be compared. extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: SignedInteger { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.rawValue.toIntMax() == rhs.rawValue.toIntMax() } } public extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: SignedInteger { public final var _domain: String { return Self._nsErrorDomain } public final var _code: Int { return Int(rawValue.toIntMax()) } public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } public init?(_bridgedNSError: NSError) { if _bridgedNSError.domain != Self._nsErrorDomain { return nil } self.init(rawValue: RawValue(IntMax(_bridgedNSError.code))) } public final var hashValue: Int { return _code } } // Allow two bridged NSError types to be compared. extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.rawValue.toUIntMax() == rhs.rawValue.toUIntMax() } } public extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger { public final var _domain: String { return Self._nsErrorDomain } public final var _code: Int { return Int(bitPattern: UInt(rawValue.toUIntMax())) } public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } public init?(_bridgedNSError: NSError) { if _bridgedNSError.domain != Self._nsErrorDomain { return nil } self.init(rawValue: RawValue(UIntMax(UInt(_bridgedNSError.code)))) } public final var hashValue: Int { return _code } } /// Describes a raw representable type that is bridged to a particular /// NSError domain. /// /// This protocol is used primarily to generate the conformance to /// _ObjectiveCBridgeableError for such an enum. public protocol _BridgedNSError : __BridgedNSError, RawRepresentable, _ObjectiveCBridgeableError, Hashable { /// The NSError domain to which this type is bridged. static var _nsErrorDomain: String { get } } /// Describes a bridged error that stores the underlying NSError, so /// it can be queried. public protocol _BridgedStoredNSError : __BridgedNSError, _ObjectiveCBridgeableError, CustomNSError, Hashable { /// The type of an error code. associatedtype Code: _ErrorCodeProtocol /// The error code for the given error. var code: Code { get } //// Retrieves the embedded NSError. var _nsError: NSError { get } /// Create a new instance of the error type with the given embedded /// NSError. /// /// The \c error must have the appropriate domain for this error /// type. init(_nsError error: NSError) } /// TODO: Better way to do this? internal func _stringDictToAnyHashableDict(_ input: [String : Any]) -> [AnyHashable : Any] { var result = [AnyHashable : Any](minimumCapacity: input.count) for (k, v) in input { result[k] = v } return result } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: SignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: Self._nsErrorDomain, code: numericCast(code.rawValue), userInfo: _stringDictToAnyHashableDict(userInfo))) } /// The user-info dictionary for an error that was bridged from /// NSError. var userInfo: [String : Any] { return errorUserInfo } } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: UnsignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: Self._nsErrorDomain, code: numericCast(code.rawValue), userInfo: _stringDictToAnyHashableDict(userInfo))) } } /// Implementation of __BridgedNSError for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { /// Default implementation of ``init(_bridgedNSError)`` to provide /// bridging from NSError. public init?(_bridgedNSError error: NSError) { if error.domain != Self._nsErrorDomain { return nil } self.init(_nsError: error) } } /// Implementation of CustomNSError for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { // FIXME: Would prefer to have a clear "extract an NSError // directly" operation. static var errorDomain: String { return _nsErrorDomain } var errorCode: Int { return _nsError.code } var errorUserInfo: [String : Any] { var result: [String : Any] = [:] for (key, value) in _nsError.userInfo { guard let stringKey = key.base as? String else { continue } result[stringKey] = value } return result } } /// Implementation of Hashable for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { var hashValue: Int { return _nsError.hashValue } } /// Describes the code of an error. public protocol _ErrorCodeProtocol : Equatable { /// The corresponding error code. associatedtype _ErrorType // FIXME: We want _ErrorType to be _BridgedStoredNSError and have its // Code match Self, but we cannot express those requirements yet. } extension _ErrorCodeProtocol where Self._ErrorType: _BridgedStoredNSError { /// Allow one to match an error code against an arbitrary error. public static func ~=(match: Self, error: Error) -> Bool { guard let specificError = error as? Self._ErrorType else { return false } // FIXME: Work around IRGen crash when we set Code == Code._ErrorType.Code. let specificCode = specificError.code as! Self return match == specificCode } } extension _BridgedStoredNSError { /// Retrieve the embedded NSError from a bridged, stored NSError. public func _getEmbeddedNSError() -> AnyObject? { return _nsError } public static func == (lhs: Self, rhs: Self) -> Bool { return lhs._nsError.isEqual(rhs._nsError) } } @available(*, unavailable, renamed: "CocoaError") public typealias NSCocoaError = CocoaError /// Describes errors within the Cocoa error domain. public struct CocoaError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSCocoaErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSCocoaErrorDomain } /// The error code itself. public struct Code : RawRepresentable, _ErrorCodeProtocol { public typealias _ErrorType = CocoaError public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } } } public extension CocoaError { private var _nsUserInfo: [AnyHashable : Any] { return (self as NSError).userInfo } /// The file path associated with the error, if any. var filePath: String? { return _nsUserInfo[NSFilePathErrorKey as NSString] as? String } /// The string encoding associated with this error, if any. var stringEncoding: String.Encoding? { return (_nsUserInfo[NSStringEncodingErrorKey as NSString] as? NSNumber) .map { String.Encoding(rawValue: $0.uintValue) } } /// The underlying error behind this error, if any. var underlying: Error? { return _nsUserInfo[NSUnderlyingErrorKey as NSString] as? Error } /// The URL associated with this error, if any. var url: URL? { return _nsUserInfo[NSURLErrorKey as NSString] as? URL } } extension CocoaError.Code { public static var fileNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 4) } public static var fileLocking: CocoaError.Code { return CocoaError.Code(rawValue: 255) } public static var fileReadUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 256) } public static var fileReadNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 257) } public static var fileReadInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 258) } public static var fileReadCorruptFile: CocoaError.Code { return CocoaError.Code(rawValue: 259) } public static var fileReadNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 260) } public static var fileReadInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 261) } public static var fileReadUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 262) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var fileReadTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 263) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var fileReadUnknownStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 264) } public static var fileWriteUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 512) } public static var fileWriteNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 513) } public static var fileWriteInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 514) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0) public static var fileWriteFileExists: CocoaError.Code { return CocoaError.Code(rawValue: 516) } public static var fileWriteInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 517) } public static var fileWriteUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 518) } public static var fileWriteOutOfSpace: CocoaError.Code { return CocoaError.Code(rawValue: 640) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var fileWriteVolumeReadOnly: CocoaError.Code { return CocoaError.Code(rawValue: 642) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) public static var fileManagerUnmountUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 768) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) public static var fileManagerUnmountBusy: CocoaError.Code { return CocoaError.Code(rawValue: 769) } public static var keyValueValidation: CocoaError.Code { return CocoaError.Code(rawValue: 1024) } public static var formatting: CocoaError.Code { return CocoaError.Code(rawValue: 2048) } public static var userCancelled: CocoaError.Code { return CocoaError.Code(rawValue: 3072) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var featureUnsupported: CocoaError.Code { return CocoaError.Code(rawValue: 3328) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableNotLoadable: CocoaError.Code { return CocoaError.Code(rawValue: 3584) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableArchitectureMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3585) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableRuntimeMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3586) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableLoad: CocoaError.Code { return CocoaError.Code(rawValue: 3587) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableLink: CocoaError.Code { return CocoaError.Code(rawValue: 3588) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 3840) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadUnknownVersion: CocoaError.Code { return CocoaError.Code(rawValue: 3841) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadStream: CocoaError.Code { return CocoaError.Code(rawValue: 3842) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListWriteStream: CocoaError.Code { return CocoaError.Code(rawValue: 3851) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var propertyListWriteInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 3852) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionInterrupted: CocoaError.Code { return CocoaError.Code(rawValue: 4097) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4099) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionReplyInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4101) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4353) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code { return CocoaError.Code(rawValue: 4354) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code { return CocoaError.Code(rawValue: 4355) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityHandoffFailed: CocoaError.Code { return CocoaError.Code(rawValue: 4608) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityConnectionUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4609) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityRemoteApplicationTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 4610) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 4611) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var coderReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 4864) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var coderValueNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 4865) } } extension CocoaError.Code { @available(*, deprecated, renamed: "fileNoSuchFile") public static var fileNoSuchFileError: CocoaError.Code { return CocoaError.Code(rawValue: 4) } @available(*, deprecated, renamed: "fileLocking") public static var fileLockingError: CocoaError.Code { return CocoaError.Code(rawValue: 255) } @available(*, deprecated, renamed: "fileReadUnknown") public static var fileReadUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 256) } @available(*, deprecated, renamed: "fileReadNoPermission") public static var fileReadNoPermissionError: CocoaError.Code { return CocoaError.Code(rawValue: 257) } @available(*, deprecated, renamed: "fileReadInvalidFileName") public static var fileReadInvalidFileNameError: CocoaError.Code { return CocoaError.Code(rawValue: 258) } @available(*, deprecated, renamed: "fileReadCorruptFile") public static var fileReadCorruptFileError: CocoaError.Code { return CocoaError.Code(rawValue: 259) } @available(*, deprecated, renamed: "fileReadNoSuchFile") public static var fileReadNoSuchFileError: CocoaError.Code { return CocoaError.Code(rawValue: 260) } @available(*, deprecated, renamed: "fileReadInapplicableStringEncoding") public static var fileReadInapplicableStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 261) } @available(*, deprecated, renamed: "fileReadUnsupportedScheme") public static var fileReadUnsupportedSchemeError: CocoaError.Code { return CocoaError.Code(rawValue: 262) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "fileReadTooLarge") public static var fileReadTooLargeError: CocoaError.Code { return CocoaError.Code(rawValue: 263) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "fileReadUnknownStringEncoding") public static var fileReadUnknownStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 264) } @available(*, deprecated, renamed: "fileWriteUnknown") public static var fileWriteUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 512) } @available(*, deprecated, renamed: "fileWriteNoPermission") public static var fileWriteNoPermissionError: CocoaError.Code { return CocoaError.Code(rawValue: 513) } @available(*, deprecated, renamed: "fileWriteInvalidFileName") public static var fileWriteInvalidFileNameError: CocoaError.Code { return CocoaError.Code(rawValue: 514) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0) @available(*, deprecated, renamed: "fileWriteFileExists") public static var fileWriteFileExistsError: CocoaError.Code { return CocoaError.Code(rawValue: 516) } @available(*, deprecated, renamed: "fileWriteInapplicableStringEncoding") public static var fileWriteInapplicableStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 517) } @available(*, deprecated, renamed: "fileWriteUnsupportedScheme") public static var fileWriteUnsupportedSchemeError: CocoaError.Code { return CocoaError.Code(rawValue: 518) } @available(*, deprecated, renamed: "fileWriteOutOfSpace") public static var fileWriteOutOfSpaceError: CocoaError.Code { return CocoaError.Code(rawValue: 640) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "fileWriteVolumeReadOnly") public static var fileWriteVolumeReadOnlyError: CocoaError.Code { return CocoaError.Code(rawValue: 642) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) @available(*, deprecated, renamed: "fileManagerUnmountUnknown") public static var fileManagerUnmountUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 768) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) @available(*, deprecated, renamed: "fileManagerUnmountBusy") public static var fileManagerUnmountBusyError: CocoaError.Code { return CocoaError.Code(rawValue: 769) } @available(*, deprecated, renamed: "keyValueValidation") public static var keyValueValidationError: CocoaError.Code { return CocoaError.Code(rawValue: 1024) } @available(*, deprecated, renamed: "formatting") public static var formattingError: CocoaError.Code { return CocoaError.Code(rawValue: 2048) } @available(*, deprecated, renamed: "userCancelled") public static var userCancelledError: CocoaError.Code { return CocoaError.Code(rawValue: 3072) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) @available(*, deprecated, renamed: "featureUnsupported") public static var featureUnsupportedError: CocoaError.Code { return CocoaError.Code(rawValue: 3328) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableNotLoadable") public static var executableNotLoadableError: CocoaError.Code { return CocoaError.Code(rawValue: 3584) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableArchitectureMismatch") public static var executableArchitectureMismatchError: CocoaError.Code { return CocoaError.Code(rawValue: 3585) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableRuntimeMismatch") public static var executableRuntimeMismatchError: CocoaError.Code { return CocoaError.Code(rawValue: 3586) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableLoad") public static var executableLoadError: CocoaError.Code { return CocoaError.Code(rawValue: 3587) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableLink") public static var executableLinkError: CocoaError.Code { return CocoaError.Code(rawValue: 3588) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadCorrupt") public static var propertyListReadCorruptError: CocoaError.Code { return CocoaError.Code(rawValue: 3840) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadUnknownVersion") public static var propertyListReadUnknownVersionError: CocoaError.Code { return CocoaError.Code(rawValue: 3841) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadStream") public static var propertyListReadStreamError: CocoaError.Code { return CocoaError.Code(rawValue: 3842) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListWriteStream") public static var propertyListWriteStreamError: CocoaError.Code { return CocoaError.Code(rawValue: 3851) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "propertyListWriteInvalid") public static var propertyListWriteInvalidError: CocoaError.Code { return CocoaError.Code(rawValue: 3852) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) @available(*, deprecated, renamed: "ubiquitousFileUnavailable") public static var ubiquitousFileUnavailableError: CocoaError.Code { return CocoaError.Code(rawValue: 4353) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) @available(*, deprecated, renamed: "ubiquitousFileNotUploadedDueToQuota") public static var ubiquitousFileNotUploadedDueToQuotaError: CocoaError.Code { return CocoaError.Code(rawValue: 4354) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityHandoffFailed") public static var userActivityHandoffFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 4608) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityConnectionUnavailable") public static var userActivityConnectionUnavailableError: CocoaError.Code { return CocoaError.Code(rawValue: 4609) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityRemoteApplicationTimedOut") public static var userActivityRemoteApplicationTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 4610) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityHandoffUserInfoTooLarge") public static var userActivityHandoffUserInfoTooLargeError: CocoaError.Code { return CocoaError.Code(rawValue: 4611) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) @available(*, deprecated, renamed: "coderReadCorrupt") public static var coderReadCorruptError: CocoaError.Code { return CocoaError.Code(rawValue: 4864) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) @available(*, deprecated, renamed: "coderValueNotFound") public static var coderValueNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 4865) } } extension CocoaError { public static var fileNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 4) } public static var fileLocking: CocoaError.Code { return CocoaError.Code(rawValue: 255) } public static var fileReadUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 256) } public static var fileReadNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 257) } public static var fileReadInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 258) } public static var fileReadCorruptFile: CocoaError.Code { return CocoaError.Code(rawValue: 259) } public static var fileReadNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 260) } public static var fileReadInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 261) } public static var fileReadUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 262) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var fileReadTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 263) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var fileReadUnknownStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 264) } public static var fileWriteUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 512) } public static var fileWriteNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 513) } public static var fileWriteInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 514) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0) public static var fileWriteFileExists: CocoaError.Code { return CocoaError.Code(rawValue: 516) } public static var fileWriteInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 517) } public static var fileWriteUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 518) } public static var fileWriteOutOfSpace: CocoaError.Code { return CocoaError.Code(rawValue: 640) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var fileWriteVolumeReadOnly: CocoaError.Code { return CocoaError.Code(rawValue: 642) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) public static var fileManagerUnmountUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 768) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) public static var fileManagerUnmountBusy: CocoaError.Code { return CocoaError.Code(rawValue: 769) } public static var keyValueValidation: CocoaError.Code { return CocoaError.Code(rawValue: 1024) } public static var formatting: CocoaError.Code { return CocoaError.Code(rawValue: 2048) } public static var userCancelled: CocoaError.Code { return CocoaError.Code(rawValue: 3072) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var featureUnsupported: CocoaError.Code { return CocoaError.Code(rawValue: 3328) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableNotLoadable: CocoaError.Code { return CocoaError.Code(rawValue: 3584) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableArchitectureMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3585) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableRuntimeMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3586) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableLoad: CocoaError.Code { return CocoaError.Code(rawValue: 3587) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableLink: CocoaError.Code { return CocoaError.Code(rawValue: 3588) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 3840) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadUnknownVersion: CocoaError.Code { return CocoaError.Code(rawValue: 3841) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadStream: CocoaError.Code { return CocoaError.Code(rawValue: 3842) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListWriteStream: CocoaError.Code { return CocoaError.Code(rawValue: 3851) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var propertyListWriteInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 3852) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionInterrupted: CocoaError.Code { return CocoaError.Code(rawValue: 4097) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4099) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionReplyInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4101) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4353) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code { return CocoaError.Code(rawValue: 4354) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code { return CocoaError.Code(rawValue: 4355) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityHandoffFailed: CocoaError.Code { return CocoaError.Code(rawValue: 4608) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityConnectionUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4609) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityRemoteApplicationTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 4610) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 4611) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var coderReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 4864) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var coderValueNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 4865) } } extension CocoaError { @available(*, deprecated, renamed: "fileNoSuchFile") public static var fileNoSuchFileError: CocoaError.Code { return CocoaError.Code(rawValue: 4) } @available(*, deprecated, renamed: "fileLocking") public static var fileLockingError: CocoaError.Code { return CocoaError.Code(rawValue: 255) } @available(*, deprecated, renamed: "fileReadUnknown") public static var fileReadUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 256) } @available(*, deprecated, renamed: "fileReadNoPermission") public static var fileReadNoPermissionError: CocoaError.Code { return CocoaError.Code(rawValue: 257) } @available(*, deprecated, renamed: "fileReadInvalidFileName") public static var fileReadInvalidFileNameError: CocoaError.Code { return CocoaError.Code(rawValue: 258) } @available(*, deprecated, renamed: "fileReadCorruptFile") public static var fileReadCorruptFileError: CocoaError.Code { return CocoaError.Code(rawValue: 259) } @available(*, deprecated, renamed: "fileReadNoSuchFile") public static var fileReadNoSuchFileError: CocoaError.Code { return CocoaError.Code(rawValue: 260) } @available(*, deprecated, renamed: "fileReadInapplicableStringEncoding") public static var fileReadInapplicableStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 261) } @available(*, deprecated, renamed: "fileReadUnsupportedScheme") public static var fileReadUnsupportedSchemeError: CocoaError.Code { return CocoaError.Code(rawValue: 262) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "fileReadTooLarge") public static var fileReadTooLargeError: CocoaError.Code { return CocoaError.Code(rawValue: 263) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "fileReadUnknownStringEncoding") public static var fileReadUnknownStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 264) } @available(*, deprecated, renamed: "fileWriteUnknown") public static var fileWriteUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 512) } @available(*, deprecated, renamed: "fileWriteNoPermission") public static var fileWriteNoPermissionError: CocoaError.Code { return CocoaError.Code(rawValue: 513) } @available(*, deprecated, renamed: "fileWriteInvalidFileName") public static var fileWriteInvalidFileNameError: CocoaError.Code { return CocoaError.Code(rawValue: 514) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0) @available(*, deprecated, renamed: "fileWriteFileExists") public static var fileWriteFileExistsError: CocoaError.Code { return CocoaError.Code(rawValue: 516) } @available(*, deprecated, renamed: "fileWriteInapplicableStringEncoding") public static var fileWriteInapplicableStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 517) } @available(*, deprecated, renamed: "fileWriteUnsupportedScheme") public static var fileWriteUnsupportedSchemeError: CocoaError.Code { return CocoaError.Code(rawValue: 518) } @available(*, deprecated, renamed: "fileWriteOutOfSpace") public static var fileWriteOutOfSpaceError: CocoaError.Code { return CocoaError.Code(rawValue: 640) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "fileWriteVolumeReadOnly") public static var fileWriteVolumeReadOnlyError: CocoaError.Code { return CocoaError.Code(rawValue: 642) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) @available(*, deprecated, renamed: "fileManagerUnmountUnknown") public static var fileManagerUnmountUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 768) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) @available(*, deprecated, renamed: "fileManagerUnmountBusy") public static var fileManagerUnmountBusyError: CocoaError.Code { return CocoaError.Code(rawValue: 769) } @available(*, deprecated, renamed: "keyValueValidation") public static var keyValueValidationError: CocoaError.Code { return CocoaError.Code(rawValue: 1024) } @available(*, deprecated, renamed: "formatting") public static var formattingError: CocoaError.Code { return CocoaError.Code(rawValue: 2048) } @available(*, deprecated, renamed: "userCancelled") public static var userCancelledError: CocoaError.Code { return CocoaError.Code(rawValue: 3072) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) @available(*, deprecated, renamed: "featureUnsupported") public static var featureUnsupportedError: CocoaError.Code { return CocoaError.Code(rawValue: 3328) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableNotLoadable") public static var executableNotLoadableError: CocoaError.Code { return CocoaError.Code(rawValue: 3584) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableArchitectureMismatch") public static var executableArchitectureMismatchError: CocoaError.Code { return CocoaError.Code(rawValue: 3585) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableRuntimeMismatch") public static var executableRuntimeMismatchError: CocoaError.Code { return CocoaError.Code(rawValue: 3586) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableLoad") public static var executableLoadError: CocoaError.Code { return CocoaError.Code(rawValue: 3587) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableLink") public static var executableLinkError: CocoaError.Code { return CocoaError.Code(rawValue: 3588) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadCorrupt") public static var propertyListReadCorruptError: CocoaError.Code { return CocoaError.Code(rawValue: 3840) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadUnknownVersion") public static var propertyListReadUnknownVersionError: CocoaError.Code { return CocoaError.Code(rawValue: 3841) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadStream") public static var propertyListReadStreamError: CocoaError.Code { return CocoaError.Code(rawValue: 3842) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListWriteStream") public static var propertyListWriteStreamError: CocoaError.Code { return CocoaError.Code(rawValue: 3851) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "propertyListWriteInvalid") public static var propertyListWriteInvalidError: CocoaError.Code { return CocoaError.Code(rawValue: 3852) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) @available(*, deprecated, renamed: "ubiquitousFileUnavailable") public static var ubiquitousFileUnavailableError: CocoaError.Code { return CocoaError.Code(rawValue: 4353) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) @available(*, deprecated, renamed: "ubiquitousFileNotUploadedDueToQuota") public static var ubiquitousFileNotUploadedDueToQuotaError: CocoaError.Code { return CocoaError.Code(rawValue: 4354) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityHandoffFailed") public static var userActivityHandoffFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 4608) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityConnectionUnavailable") public static var userActivityConnectionUnavailableError: CocoaError.Code { return CocoaError.Code(rawValue: 4609) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityRemoteApplicationTimedOut") public static var userActivityRemoteApplicationTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 4610) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityHandoffUserInfoTooLarge") public static var userActivityHandoffUserInfoTooLargeError: CocoaError.Code { return CocoaError.Code(rawValue: 4611) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) @available(*, deprecated, renamed: "coderReadCorrupt") public static var coderReadCorruptError: CocoaError.Code { return CocoaError.Code(rawValue: 4864) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) @available(*, deprecated, renamed: "coderValueNotFound") public static var coderValueNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 4865) } } extension CocoaError { @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public var isCoderError: Bool { return code.rawValue >= 4864 && code.rawValue <= 4991 } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public var isExecutableError: Bool { return code.rawValue >= 3584 && code.rawValue <= 3839 } public var isFileError: Bool { return code.rawValue >= 0 && code.rawValue <= 1023 } public var isFormattingError: Bool { return code.rawValue >= 2048 && code.rawValue <= 2559 } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public var isPropertyListError: Bool { return code.rawValue >= 3840 && code.rawValue <= 4095 } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public var isUbiquitousFileError: Bool { return code.rawValue >= 4352 && code.rawValue <= 4607 } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public var isUserActivityError: Bool { return code.rawValue >= 4608 && code.rawValue <= 4863 } public var isValidationError: Bool { return code.rawValue >= 1024 && code.rawValue <= 2047 } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public var isXPCConnectionError: Bool { return code.rawValue >= 4096 && code.rawValue <= 4224 } } extension CocoaError.Code { @available(*, unavailable, renamed: "fileNoSuchFile") public static var FileNoSuchFileError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileLocking") public static var FileLockingError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadUnknown") public static var FileReadUnknownError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadNoPermission") public static var FileReadNoPermissionError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadInvalidFileName") public static var FileReadInvalidFileNameError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadCorruptFile") public static var FileReadCorruptFileError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadNoSuchFile") public static var FileReadNoSuchFileError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadInapplicableStringEncoding") public static var FileReadInapplicableStringEncodingError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadUnsupportedScheme") public static var FileReadUnsupportedSchemeError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadTooLarge") public static var FileReadTooLargeError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadUnknownStringEncoding") public static var FileReadUnknownStringEncodingError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteUnknown") public static var FileWriteUnknownError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteNoPermission") public static var FileWriteNoPermissionError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteInvalidFileName") public static var FileWriteInvalidFileNameError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteFileExists") public static var FileWriteFileExistsError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteInapplicableStringEncoding") public static var FileWriteInapplicableStringEncodingError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteUnsupportedScheme") public static var FileWriteUnsupportedSchemeError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteOutOfSpace") public static var FileWriteOutOfSpaceError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteVolumeReadOnly") public static var FileWriteVolumeReadOnlyError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileManagerUnmountUnknown") public static var FileManagerUnmountUnknownError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileManagerUnmountBusy") public static var FileManagerUnmountBusyError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "keyValueValidation") public static var KeyValueValidationError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "formatting") public static var FormattingError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userCancelled") public static var UserCancelledError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "featureUnsupported") public static var FeatureUnsupportedError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableNotLoadable") public static var ExecutableNotLoadableError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableArchitectureMismatch") public static var ExecutableArchitectureMismatchError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableRuntimeMismatch") public static var ExecutableRuntimeMismatchError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableLoad") public static var ExecutableLoadError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableLink") public static var ExecutableLinkError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListReadCorrupt") public static var PropertyListReadCorruptError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListReadUnknownVersion") public static var PropertyListReadUnknownVersionError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListReadStream") public static var PropertyListReadStreamError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListWriteStream") public static var PropertyListWriteStreamError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListWriteInvalid") public static var PropertyListWriteInvalidError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "xpcConnectionInterrupted") public static var XPCConnectionInterrupted: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "xpcConnectionInvalid") public static var XPCConnectionInvalid: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "xpcConnectionReplyInvalid") public static var XPCConnectionReplyInvalid: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "ubiquitousFileUnavailable") public static var UbiquitousFileUnavailableError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "ubiquitousFileNotUploadedDueToQuota") public static var UbiquitousFileNotUploadedDueToQuotaError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "ubiquitousFileUbiquityServerNotAvailable") public static var UbiquitousFileUbiquityServerNotAvailable: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityHandoffFailed") public static var UserActivityHandoffFailedError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityConnectionUnavailable") public static var UserActivityConnectionUnavailableError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityRemoteApplicationTimedOut") public static var UserActivityRemoteApplicationTimedOutError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityHandoffUserInfoTooLarge") public static var UserActivityHandoffUserInfoTooLargeError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "coderReadCorrupt") public static var CoderReadCorruptError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "coderValueNotFound") public static var CoderValueNotFoundError: CocoaError.Code { fatalError("unavailable accessor can't be called") } } /// Describes errors in the URL error domain. public struct URLError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSURLErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSURLErrorDomain } @objc public enum Code : Int, _ErrorCodeProtocol { public typealias _ErrorType = URLError case unknown = -1 case cancelled = -999 case badURL = -1000 case timedOut = -1001 case unsupportedURL = -1002 case cannotFindHost = -1003 case cannotConnectToHost = -1004 case networkConnectionLost = -1005 case dnsLookupFailed = -1006 case httpTooManyRedirects = -1007 case resourceUnavailable = -1008 case notConnectedToInternet = -1009 case redirectToNonExistentLocation = -1010 case badServerResponse = -1011 case userCancelledAuthentication = -1012 case userAuthenticationRequired = -1013 case zeroByteResource = -1014 case cannotDecodeRawData = -1015 case cannotDecodeContentData = -1016 case cannotParseResponse = -1017 case fileDoesNotExist = -1100 case fileIsDirectory = -1101 case noPermissionsToReadFile = -1102 case secureConnectionFailed = -1200 case serverCertificateHasBadDate = -1201 case serverCertificateUntrusted = -1202 case serverCertificateHasUnknownRoot = -1203 case serverCertificateNotYetValid = -1204 case clientCertificateRejected = -1205 case clientCertificateRequired = -1206 case cannotLoadFromNetwork = -2000 case cannotCreateFile = -3000 case cannotOpenFile = -3001 case cannotCloseFile = -3002 case cannotWriteToFile = -3003 case cannotRemoveFile = -3004 case cannotMoveFile = -3005 case downloadDecodingFailedMidStream = -3006 case downloadDecodingFailedToComplete = -3007 @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) case internationalRoamingOff = -1018 @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) case callIsActive = -1019 @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) case dataNotAllowed = -1020 @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) case requestBodyStreamExhausted = -1021 @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) static var backgroundSessionRequiresSharedContainer: Code { return Code(rawValue: -995)! } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) static var backgroundSessionInUseByAnotherProcess: Code { return Code(rawValue: -996)! } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) static var backgroundSessionWasDisconnected: Code { return Code(rawValue: -997)! } } } public extension URLError { private var _nsUserInfo: [AnyHashable : Any] { return (self as NSError).userInfo } /// The URL which caused a load to fail. public var failingURL: URL? { return _nsUserInfo[NSURLErrorFailingURLErrorKey as NSString] as? URL } /// The string for the URL which caused a load to fail. public var failureURLString: String? { return _nsUserInfo[NSURLErrorFailingURLStringErrorKey as NSString] as? String } /// The state of a failed SSL handshake. public var failureURLPeerTrust: SecTrust? { if let secTrust = _nsUserInfo[NSURLErrorFailingURLPeerTrustErrorKey as NSString] { return (secTrust as! SecTrust) } return nil } } public extension URLError { public static var unknown: URLError.Code { return .unknown } public static var cancelled: URLError.Code { return .cancelled } public static var badURL: URLError.Code { return .badURL } public static var timedOut: URLError.Code { return .timedOut } public static var unsupportedURL: URLError.Code { return .unsupportedURL } public static var cannotFindHost: URLError.Code { return .cannotFindHost } public static var cannotConnectToHost: URLError.Code { return .cannotConnectToHost } public static var networkConnectionLost: URLError.Code { return .networkConnectionLost } public static var dnsLookupFailed: URLError.Code { return .dnsLookupFailed } public static var httpTooManyRedirects: URLError.Code { return .httpTooManyRedirects } public static var resourceUnavailable: URLError.Code { return .resourceUnavailable } public static var notConnectedToInternet: URLError.Code { return .notConnectedToInternet } public static var redirectToNonExistentLocation: URLError.Code { return .redirectToNonExistentLocation } public static var badServerResponse: URLError.Code { return .badServerResponse } public static var userCancelledAuthentication: URLError.Code { return .userCancelledAuthentication } public static var userAuthenticationRequired: URLError.Code { return .userAuthenticationRequired } public static var zeroByteResource: URLError.Code { return .zeroByteResource } public static var cannotDecodeRawData: URLError.Code { return .cannotDecodeRawData } public static var cannotDecodeContentData: URLError.Code { return .cannotDecodeContentData } public static var cannotParseResponse: URLError.Code { return .cannotParseResponse } public static var fileDoesNotExist: URLError.Code { return .fileDoesNotExist } public static var fileIsDirectory: URLError.Code { return .fileIsDirectory } public static var noPermissionsToReadFile: URLError.Code { return .noPermissionsToReadFile } public static var secureConnectionFailed: URLError.Code { return .secureConnectionFailed } public static var serverCertificateHasBadDate: URLError.Code { return .serverCertificateHasBadDate } public static var serverCertificateUntrusted: URLError.Code { return .serverCertificateUntrusted } public static var serverCertificateHasUnknownRoot: URLError.Code { return .serverCertificateHasUnknownRoot } public static var serverCertificateNotYetValid: URLError.Code { return .serverCertificateNotYetValid } public static var clientCertificateRejected: URLError.Code { return .clientCertificateRejected } public static var clientCertificateRequired: URLError.Code { return .clientCertificateRequired } public static var cannotLoadFromNetwork: URLError.Code { return .cannotLoadFromNetwork } public static var cannotCreateFile: URLError.Code { return .cannotCreateFile } public static var cannotOpenFile: URLError.Code { return .cannotOpenFile } public static var cannotCloseFile: URLError.Code { return .cannotCloseFile } public static var cannotWriteToFile: URLError.Code { return .cannotWriteToFile } public static var cannotRemoveFile: URLError.Code { return .cannotRemoveFile } public static var cannotMoveFile: URLError.Code { return .cannotMoveFile } public static var downloadDecodingFailedMidStream: URLError.Code { return .downloadDecodingFailedMidStream } public static var downloadDecodingFailedToComplete: URLError.Code { return .downloadDecodingFailedToComplete } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var internationalRoamingOff: URLError.Code { return .internationalRoamingOff } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var callIsActive: URLError.Code { return .callIsActive } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var dataNotAllowed: URLError.Code { return .dataNotAllowed } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var requestBodyStreamExhausted: URLError.Code { return .requestBodyStreamExhausted } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var backgroundSessionRequiresSharedContainer: Code { return .backgroundSessionRequiresSharedContainer } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var backgroundSessionInUseByAnotherProcess: Code { return .backgroundSessionInUseByAnotherProcess } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var backgroundSessionWasDisconnected: Code { return .backgroundSessionWasDisconnected } } extension URLError { @available(*, unavailable, renamed: "unknown") public static var Unknown: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cancelled") public static var Cancelled: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "badURL") public static var BadURL: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "timedOut") public static var TimedOut: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "unsupportedURL") public static var UnsupportedURL: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotFindHost") public static var CannotFindHost: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotConnectToHost") public static var CannotConnectToHost: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "networkConnectionLost") public static var NetworkConnectionLost: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "dnsLookupFailed") public static var DNSLookupFailed: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "httpTooManyRedirects") public static var HTTPTooManyRedirects: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "resourceUnavailable") public static var ResourceUnavailable: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "notConnectedToInternet") public static var NotConnectedToInternet: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "redirectToNonExistentLocation") public static var RedirectToNonExistentLocation: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "badServerResponse") public static var BadServerResponse: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userCancelledAuthentication") public static var UserCancelledAuthentication: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userAuthenticationRequired") public static var UserAuthenticationRequired: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "zeroByteResource") public static var ZeroByteResource: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotDecodeRawData") public static var CannotDecodeRawData: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotDecodeContentData") public static var CannotDecodeContentData: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotParseResponse") public static var CannotParseResponse: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileDoesNotExist") public static var FileDoesNotExist: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileIsDirectory") public static var FileIsDirectory: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "noPermissionsToReadFile") public static var NoPermissionsToReadFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "secureConnectionFailed") public static var SecureConnectionFailed: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateHasBadDate") public static var ServerCertificateHasBadDate: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateUntrusted") public static var ServerCertificateUntrusted: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateHasUnknownRoot") public static var ServerCertificateHasUnknownRoot: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateNotYetValid") public static var ServerCertificateNotYetValid: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "clientCertificateRejected") public static var ClientCertificateRejected: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "clientCertificateRequired") public static var ClientCertificateRequired: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotLoadFromNetwork") public static var CannotLoadFromNetwork: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotCreateFile") public static var CannotCreateFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotOpenFile") public static var CannotOpenFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotCloseFile") public static var CannotCloseFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotWriteToFile") public static var CannotWriteToFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotRemoveFile") public static var CannotRemoveFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotMoveFile") public static var CannotMoveFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "downloadDecodingFailedMidStream") public static var DownloadDecodingFailedMidStream: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "downloadDecodingFailedToComplete") public static var DownloadDecodingFailedToComplete: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "internationalRoamingOff") public static var InternationalRoamingOff: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "callIsActive") public static var CallIsActive: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "dataNotAllowed") public static var DataNotAllowed: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "requestBodyStreamExhausted") public static var RequestBodyStreamExhausted: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "backgroundSessionRequiresSharedContainer") public static var BackgroundSessionRequiresSharedContainer: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "backgroundSessionInUseByAnotherProcess") public static var BackgroundSessionInUseByAnotherProcess: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "backgroundSessionWasDisconnected") public static var BackgroundSessionWasDisconnected: URLError.Code { fatalError("unavailable accessor can't be called") } } /// Describes an error in the POSIX error domain. public struct POSIXError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSPOSIXErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSPOSIXErrorDomain } public typealias Code = POSIXErrorCode } extension POSIXErrorCode : _ErrorCodeProtocol { public typealias _ErrorType = POSIXError } extension POSIXError { public static var EPERM: POSIXErrorCode { return .EPERM } /// No such file or directory. public static var ENOENT: POSIXErrorCode { return .ENOENT } /// No such process. public static var ESRCH: POSIXErrorCode { return .ESRCH } /// Interrupted system call. public static var EINTR: POSIXErrorCode { return .EINTR } /// Input/output error. public static var EIO: POSIXErrorCode { return .EIO } /// Device not configured. public static var ENXIO: POSIXErrorCode { return .ENXIO } /// Argument list too long. public static var E2BIG: POSIXErrorCode { return .E2BIG } /// Exec format error. public static var ENOEXEC: POSIXErrorCode { return .ENOEXEC } /// Bad file descriptor. public static var EBADF: POSIXErrorCode { return .EBADF } /// No child processes. public static var ECHILD: POSIXErrorCode { return .ECHILD } /// Resource deadlock avoided. public static var EDEADLK: POSIXErrorCode { return .EDEADLK } /// Cannot allocate memory. public static var ENOMEM: POSIXErrorCode { return .ENOMEM } /// Permission denied. public static var EACCES: POSIXErrorCode { return .EACCES } /// Bad address. public static var EFAULT: POSIXErrorCode { return .EFAULT } /// Block device required. public static var ENOTBLK: POSIXErrorCode { return .ENOTBLK } /// Device / Resource busy. public static var EBUSY: POSIXErrorCode { return .EBUSY } /// File exists. public static var EEXIST: POSIXErrorCode { return .EEXIST } /// Cross-device link. public static var EXDEV: POSIXErrorCode { return .EXDEV } /// Operation not supported by device. public static var ENODEV: POSIXErrorCode { return .ENODEV } /// Not a directory. public static var ENOTDIR: POSIXErrorCode { return .ENOTDIR } /// Is a directory. public static var EISDIR: POSIXErrorCode { return .EISDIR } /// Invalid argument. public static var EINVAL: POSIXErrorCode { return .EINVAL } /// Too many open files in system. public static var ENFILE: POSIXErrorCode { return .ENFILE } /// Too many open files. public static var EMFILE: POSIXErrorCode { return .EMFILE } /// Inappropriate ioctl for device. public static var ENOTTY: POSIXErrorCode { return .ENOTTY } /// Text file busy. public static var ETXTBSY: POSIXErrorCode { return .ETXTBSY } /// File too large. public static var EFBIG: POSIXErrorCode { return .EFBIG } /// No space left on device. public static var ENOSPC: POSIXErrorCode { return .ENOSPC } /// Illegal seek. public static var ESPIPE: POSIXErrorCode { return .ESPIPE } /// Read-only file system. public static var EROFS: POSIXErrorCode { return .EROFS } /// Too many links. public static var EMLINK: POSIXErrorCode { return .EMLINK } /// Broken pipe. public static var EPIPE: POSIXErrorCode { return .EPIPE } /// math software. /// Numerical argument out of domain. public static var EDOM: POSIXErrorCode { return .EDOM } /// Result too large. public static var ERANGE: POSIXErrorCode { return .ERANGE } /// non-blocking and interrupt i/o. /// Resource temporarily unavailable. public static var EAGAIN: POSIXErrorCode { return .EAGAIN } /// Operation would block. public static var EWOULDBLOCK: POSIXErrorCode { return .EWOULDBLOCK } /// Operation now in progress. public static var EINPROGRESS: POSIXErrorCode { return .EINPROGRESS } /// Operation already in progress. public static var EALREADY: POSIXErrorCode { return .EALREADY } /// ipc/network software -- argument errors. /// Socket operation on non-socket. public static var ENOTSOCK: POSIXErrorCode { return .ENOTSOCK } /// Destination address required. public static var EDESTADDRREQ: POSIXErrorCode { return .EDESTADDRREQ } /// Message too long. public static var EMSGSIZE: POSIXErrorCode { return .EMSGSIZE } /// Protocol wrong type for socket. public static var EPROTOTYPE: POSIXErrorCode { return .EPROTOTYPE } /// Protocol not available. public static var ENOPROTOOPT: POSIXErrorCode { return .ENOPROTOOPT } /// Protocol not supported. public static var EPROTONOSUPPORT: POSIXErrorCode { return .EPROTONOSUPPORT } /// Socket type not supported. public static var ESOCKTNOSUPPORT: POSIXErrorCode { return .ESOCKTNOSUPPORT } /// Operation not supported. public static var ENOTSUP: POSIXErrorCode { return .ENOTSUP } /// Protocol family not supported. public static var EPFNOSUPPORT: POSIXErrorCode { return .EPFNOSUPPORT } /// Address family not supported by protocol family. public static var EAFNOSUPPORT: POSIXErrorCode { return .EAFNOSUPPORT } /// Address already in use. public static var EADDRINUSE: POSIXErrorCode { return .EADDRINUSE } /// Can't assign requested address. public static var EADDRNOTAVAIL: POSIXErrorCode { return .EADDRNOTAVAIL } /// ipc/network software -- operational errors /// Network is down. public static var ENETDOWN: POSIXErrorCode { return .ENETDOWN } /// Network is unreachable. public static var ENETUNREACH: POSIXErrorCode { return .ENETUNREACH } /// Network dropped connection on reset. public static var ENETRESET: POSIXErrorCode { return .ENETRESET } /// Software caused connection abort. public static var ECONNABORTED: POSIXErrorCode { return .ECONNABORTED } /// Connection reset by peer. public static var ECONNRESET: POSIXErrorCode { return .ECONNRESET } /// No buffer space available. public static var ENOBUFS: POSIXErrorCode { return .ENOBUFS } /// Socket is already connected. public static var EISCONN: POSIXErrorCode { return .EISCONN } /// Socket is not connected. public static var ENOTCONN: POSIXErrorCode { return .ENOTCONN } /// Can't send after socket shutdown. public static var ESHUTDOWN: POSIXErrorCode { return .ESHUTDOWN } /// Too many references: can't splice. public static var ETOOMANYREFS: POSIXErrorCode { return .ETOOMANYREFS } /// Operation timed out. public static var ETIMEDOUT: POSIXErrorCode { return .ETIMEDOUT } /// Connection refused. public static var ECONNREFUSED: POSIXErrorCode { return .ECONNREFUSED } /// Too many levels of symbolic links. public static var ELOOP: POSIXErrorCode { return .ELOOP } /// File name too long. public static var ENAMETOOLONG: POSIXErrorCode { return .ENAMETOOLONG } /// Host is down. public static var EHOSTDOWN: POSIXErrorCode { return .EHOSTDOWN } /// No route to host. public static var EHOSTUNREACH: POSIXErrorCode { return .EHOSTUNREACH } /// Directory not empty. public static var ENOTEMPTY: POSIXErrorCode { return .ENOTEMPTY } /// quotas & mush. /// Too many processes. public static var EPROCLIM: POSIXErrorCode { return .EPROCLIM } /// Too many users. public static var EUSERS: POSIXErrorCode { return .EUSERS } /// Disc quota exceeded. public static var EDQUOT: POSIXErrorCode { return .EDQUOT } /// Network File System. /// Stale NFS file handle. public static var ESTALE: POSIXErrorCode { return .ESTALE } /// Too many levels of remote in path. public static var EREMOTE: POSIXErrorCode { return .EREMOTE } /// RPC struct is bad. public static var EBADRPC: POSIXErrorCode { return .EBADRPC } /// RPC version wrong. public static var ERPCMISMATCH: POSIXErrorCode { return .ERPCMISMATCH } /// RPC prog. not avail. public static var EPROGUNAVAIL: POSIXErrorCode { return .EPROGUNAVAIL } /// Program version wrong. public static var EPROGMISMATCH: POSIXErrorCode { return .EPROGMISMATCH } /// Bad procedure for program. public static var EPROCUNAVAIL: POSIXErrorCode { return .EPROCUNAVAIL } /// No locks available. public static var ENOLCK: POSIXErrorCode { return .ENOLCK } /// Function not implemented. public static var ENOSYS: POSIXErrorCode { return .ENOSYS } /// Inappropriate file type or format. public static var EFTYPE: POSIXErrorCode { return .EFTYPE } /// Authentication error. public static var EAUTH: POSIXErrorCode { return .EAUTH } /// Need authenticator. public static var ENEEDAUTH: POSIXErrorCode { return .ENEEDAUTH } /// Intelligent device errors. /// Device power is off. public static var EPWROFF: POSIXErrorCode { return .EPWROFF } /// Device error, e.g. paper out. public static var EDEVERR: POSIXErrorCode { return .EDEVERR } /// Value too large to be stored in data type. public static var EOVERFLOW: POSIXErrorCode { return .EOVERFLOW } /// Program loading errors. /// Bad executable. public static var EBADEXEC: POSIXErrorCode { return .EBADEXEC } /// Bad CPU type in executable. public static var EBADARCH: POSIXErrorCode { return .EBADARCH } /// Shared library version mismatch. public static var ESHLIBVERS: POSIXErrorCode { return .ESHLIBVERS } /// Malformed Macho file. public static var EBADMACHO: POSIXErrorCode { return .EBADMACHO } /// Operation canceled. public static var ECANCELED: POSIXErrorCode { return .ECANCELED } /// Identifier removed. public static var EIDRM: POSIXErrorCode { return .EIDRM } /// No message of desired type. public static var ENOMSG: POSIXErrorCode { return .ENOMSG } /// Illegal byte sequence. public static var EILSEQ: POSIXErrorCode { return .EILSEQ } /// Attribute not found. public static var ENOATTR: POSIXErrorCode { return .ENOATTR } /// Bad message. public static var EBADMSG: POSIXErrorCode { return .EBADMSG } /// Reserved. public static var EMULTIHOP: POSIXErrorCode { return .EMULTIHOP } /// No message available on STREAM. public static var ENODATA: POSIXErrorCode { return .ENODATA } /// Reserved. public static var ENOLINK: POSIXErrorCode { return .ENOLINK } /// No STREAM resources. public static var ENOSR: POSIXErrorCode { return .ENOSR } /// Not a STREAM. public static var ENOSTR: POSIXErrorCode { return .ENOSTR } /// Protocol error. public static var EPROTO: POSIXErrorCode { return .EPROTO } /// STREAM ioctl timeout. public static var ETIME: POSIXErrorCode { return .ETIME } /// No such policy registered. public static var ENOPOLICY: POSIXErrorCode { return .ENOPOLICY } /// State not recoverable. public static var ENOTRECOVERABLE: POSIXErrorCode { return .ENOTRECOVERABLE } /// Previous owner died. public static var EOWNERDEAD: POSIXErrorCode { return .EOWNERDEAD } /// Interface output queue is full. public static var EQFULL: POSIXErrorCode { return .EQFULL } } /// Describes an error in the Mach error domain. public struct MachError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSMachErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSMachErrorDomain } public typealias Code = MachErrorCode } extension MachErrorCode : _ErrorCodeProtocol { public typealias _ErrorType = MachError } extension MachError { public static var success: MachError.Code { return .success } /// Specified address is not currently valid. public static var invalidAddress: MachError.Code { return .invalidAddress } /// Specified memory is valid, but does not permit the required /// forms of access. public static var protectionFailure: MachError.Code { return .protectionFailure } /// The address range specified is already in use, or no address /// range of the size specified could be found. public static var noSpace: MachError.Code { return .noSpace } /// The function requested was not applicable to this type of /// argument, or an argument is invalid. public static var invalidArgument: MachError.Code { return .invalidArgument } /// The function could not be performed. A catch-all. public static var failure: MachError.Code { return .failure } /// A system resource could not be allocated to fulfill this /// request. This failure may not be permanent. public static var resourceShortage: MachError.Code { return .resourceShortage } /// The task in question does not hold receive rights for the port /// argument. public static var notReceiver: MachError.Code { return .notReceiver } /// Bogus access restriction. public static var noAccess: MachError.Code { return .noAccess } /// During a page fault, the target address refers to a memory /// object that has been destroyed. This failure is permanent. public static var memoryFailure: MachError.Code { return .memoryFailure } /// During a page fault, the memory object indicated that the data /// could not be returned. This failure may be temporary; future /// attempts to access this same data may succeed, as defined by the /// memory object. public static var memoryError: MachError.Code { return .memoryError } /// The receive right is already a member of the portset. public static var alreadyInSet: MachError.Code { return .alreadyInSet } /// The receive right is not a member of a port set. public static var notInSet: MachError.Code { return .notInSet } /// The name already denotes a right in the task. public static var nameExists: MachError.Code { return .nameExists } /// The operation was aborted. Ipc code will catch this and reflect /// it as a message error. public static var aborted: MachError.Code { return .aborted } /// The name doesn't denote a right in the task. public static var invalidName: MachError.Code { return .invalidName } /// Target task isn't an active task. public static var invalidTask: MachError.Code { return .invalidTask } /// The name denotes a right, but not an appropriate right. public static var invalidRight: MachError.Code { return .invalidRight } /// A blatant range error. public static var invalidValue: MachError.Code { return .invalidValue } /// Operation would overflow limit on user-references. public static var userReferencesOverflow: MachError.Code { return .userReferencesOverflow } /// The supplied (port) capability is improper. public static var invalidCapability: MachError.Code { return .invalidCapability } /// The task already has send or receive rights for the port under /// another name. public static var rightExists: MachError.Code { return .rightExists } /// Target host isn't actually a host. public static var invalidHost: MachError.Code { return .invalidHost } /// An attempt was made to supply "precious" data for memory that is /// already present in a memory object. public static var memoryPresent: MachError.Code { return .memoryPresent } /// A page was requested of a memory manager via /// memory_object_data_request for an object using a /// MEMORY_OBJECT_COPY_CALL strategy, with the VM_PROT_WANTS_COPY /// flag being used to specify that the page desired is for a copy /// of the object, and the memory manager has detected the page was /// pushed into a copy of the object while the kernel was walking /// the shadow chain from the copy to the object. This error code is /// delivered via memory_object_data_error and is handled by the /// kernel (it forces the kernel to restart the fault). It will not /// be seen by users. public static var memoryDataMoved: MachError.Code { return .memoryDataMoved } /// A strategic copy was attempted of an object upon which a quicker /// copy is now possible. The caller should retry the copy using /// vm_object_copy_quickly. This error code is seen only by the /// kernel. public static var memoryRestartCopy: MachError.Code { return .memoryRestartCopy } /// An argument applied to assert processor set privilege was not a /// processor set control port. public static var invalidProcessorSet: MachError.Code { return .invalidProcessorSet } /// The specified scheduling attributes exceed the thread's limits. public static var policyLimit: MachError.Code { return .policyLimit } /// The specified scheduling policy is not currently enabled for the /// processor set. public static var invalidPolicy: MachError.Code { return .invalidPolicy } /// The external memory manager failed to initialize the memory object. public static var invalidObject: MachError.Code { return .invalidObject } /// A thread is attempting to wait for an event for which there is /// already a waiting thread. public static var alreadyWaiting: MachError.Code { return .alreadyWaiting } /// An attempt was made to destroy the default processor set. public static var defaultSet: MachError.Code { return .defaultSet } /// An attempt was made to fetch an exception port that is /// protected, or to abort a thread while processing a protected /// exception. public static var exceptionProtected: MachError.Code { return .exceptionProtected } /// A ledger was required but not supplied. public static var invalidLedger: MachError.Code { return .invalidLedger } /// The port was not a memory cache control port. public static var invalidMemoryControl: MachError.Code { return .invalidMemoryControl } /// An argument supplied to assert security privilege was not a host /// security port. public static var invalidSecurity: MachError.Code { return .invalidSecurity } /// thread_depress_abort was called on a thread which was not /// currently depressed. public static var notDepressed: MachError.Code { return .notDepressed } /// Object has been terminated and is no longer available. public static var terminated: MachError.Code { return .terminated } /// Lock set has been destroyed and is no longer available. public static var lockSetDestroyed: MachError.Code { return .lockSetDestroyed } /// The thread holding the lock terminated before releasing the lock. public static var lockUnstable: MachError.Code { return .lockUnstable } /// The lock is already owned by another thread. public static var lockOwned: MachError.Code { return .lockOwned } /// The lock is already owned by the calling thread. public static var lockOwnedSelf: MachError.Code { return .lockOwnedSelf } /// Semaphore has been destroyed and is no longer available. public static var semaphoreDestroyed: MachError.Code { return .semaphoreDestroyed } /// Return from RPC indicating the target server was terminated /// before it successfully replied. public static var rpcServerTerminated: MachError.Code { return .rpcServerTerminated } /// Terminate an orphaned activation. public static var rpcTerminateOrphan: MachError.Code { return .rpcTerminateOrphan } /// Allow an orphaned activation to continue executing. public static var rpcContinueOrphan: MachError.Code { return .rpcContinueOrphan } /// Empty thread activation (No thread linked to it). public static var notSupported: MachError.Code { return .notSupported } /// Remote node down or inaccessible. public static var nodeDown: MachError.Code { return .nodeDown } /// A signalled thread was not actually waiting. public static var notWaiting: MachError.Code { return .notWaiting } /// Some thread-oriented operation (semaphore_wait) timed out. public static var operationTimedOut: MachError.Code { return .operationTimedOut } /// During a page fault, indicates that the page was rejected as a /// result of a signature check. public static var codesignError: MachError.Code { return .codesignError } /// The requested property cannot be changed at this time. public static var policyStatic: MachError.Code { return .policyStatic } } public struct ErrorUserInfoKey : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, _ObjectiveCBridgeable { public init(rawValue: String) { self.rawValue = rawValue } public var rawValue: String } public extension ErrorUserInfoKey { @available(*, deprecated, renamed: "NSUnderlyingErrorKey") static let underlyingErrorKey = ErrorUserInfoKey(rawValue: NSUnderlyingErrorKey) @available(*, deprecated, renamed: "NSLocalizedDescriptionKey") static let localizedDescriptionKey = ErrorUserInfoKey(rawValue: NSLocalizedDescriptionKey) @available(*, deprecated, renamed: "NSLocalizedFailureReasonErrorKey") static let localizedFailureReasonErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedFailureReasonErrorKey) @available(*, deprecated, renamed: "NSLocalizedRecoverySuggestionErrorKey") static let localizedRecoverySuggestionErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedRecoverySuggestionErrorKey) @available(*, deprecated, renamed: "NSLocalizedRecoveryOptionsErrorKey") static let localizedRecoveryOptionsErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedRecoveryOptionsErrorKey) @available(*, deprecated, renamed: "NSRecoveryAttempterErrorKey") static let recoveryAttempterErrorKey = ErrorUserInfoKey(rawValue: NSRecoveryAttempterErrorKey) @available(*, deprecated, renamed: "NSHelpAnchorErrorKey") static let helpAnchorErrorKey = ErrorUserInfoKey(rawValue: NSHelpAnchorErrorKey) @available(*, deprecated, renamed: "NSStringEncodingErrorKey") static let stringEncodingErrorKey = ErrorUserInfoKey(rawValue: NSStringEncodingErrorKey) @available(*, deprecated, renamed: "NSURLErrorKey") static let NSURLErrorKey = ErrorUserInfoKey(rawValue: Foundation.NSURLErrorKey) @available(*, deprecated, renamed: "NSFilePathErrorKey") static let filePathErrorKey = ErrorUserInfoKey(rawValue: NSFilePathErrorKey) }
bd2ae22e5bc077bf3163faabda6b3d61
31.867591
117
0.731027
false
false
false
false
Ivacker/swift
refs/heads/master
test/ClangModules/availability_implicit_macosx.swift
apache-2.0
10
// RUN: %swift -parse -verify -target x86_64-apple-macosx10.10 %clang-importer-sdk -I %S/Inputs/custom-modules %s %S/Inputs/availability_implicit_macosx_other.swift // RUN: not %swift -parse -target x86_64-apple-macosx10.10 %clang-importer-sdk -I %S/Inputs/custom-modules %s %S/Inputs/availability_implicit_macosx_other.swift 2>&1 | FileCheck %s '--implicit-check-not=<unknown>:0' // REQUIRES: OS=macosx // This is a temporary test for checking of availability diagnostics (explicit unavailability, // deprecation, and potential unavailability) in synthesized code. After this checking // is fully staged in, the tests in this file will be moved. // import Foundation func useClassThatTriggersImportOfDeprecatedEnum() { // Check to make sure that the bodies of enum methods that are synthesized // when importing deprecated enums do not themselves trigger deprecation // warnings in the synthesized code. _ = NSClassWithDeprecatedOptionsInMethodSignature.sharedInstance() } func useClassThatTriggersImportOExplicitlyUnavailableOptions() { _ = NSClassWithPotentiallyUnavailableOptionsInMethodSignature.sharedInstance() } func useClassThatTriggersImportOfPotentiallyUnavailableOptions() { _ = NSClassWithExplicitlyUnavailableOptionsInMethodSignature.sharedInstance() } func directUseShouldStillTriggerDeprecationWarning() { _ = NSDeprecatedOptions.First // expected-warning {{'NSDeprecatedOptions' was deprecated in OS X 10.10: Use a different API}} _ = NSDeprecatedEnum.First // expected-warning {{'NSDeprecatedEnum' was deprecated in OS X 10.10: Use a different API}} } func useInSignature(options: NSDeprecatedOptions) { // expected-warning {{'NSDeprecatedOptions' was deprecated in OS X 10.10: Use a different API}} } class SuperClassWithDeprecatedInitializer { @available(OSX, introduced=10.9, deprecated=10.10) init() { } } class SubClassWithSynthesizedDesignedInitializerOverride : SuperClassWithDeprecatedInitializer { // The synthesized designated initializer override calls super.init(), which is // deprecated, so the synthesized initializer is marked as deprecated as well. // This does not generate a warning here (perhaps it should?) but any call // to Sub's initializer will cause a deprecation warning. } func callImplicitInitializerOnSubClassWithSynthesizedDesignedInitializerOverride() { _ = SubClassWithSynthesizedDesignedInitializerOverride() // expected-warning {{'init()' was deprecated in OS X 10.10}} } @available(OSX, introduced=10.9, deprecated=10.10) class DeprecatedSuperClass { var i : Int = 7 // Causes initializer to be synthesized } class NotDeprecatedSubClassOfDeprecatedSuperClass : DeprecatedSuperClass { // expected-warning {{'DeprecatedSuperClass' was deprecated in OS X 10.10}} } func callImplicitInitalizerOnNotDeprecatedSubClassOfDeprecatedSuperClass() { // We do not expect a warning here because the synthesized initializer // in NotDeprecatedSubClassOfDeprecatedSuperClass is not itself marked // deprecated. _ = NotDeprecatedSubClassOfDeprecatedSuperClass() } @available(OSX, introduced=10.9, deprecated=10.10) class DeprecatedSubClassOfDeprecatedSuperClass : DeprecatedSuperClass { } // Tests synthesis of materializeForSet class ClassWithLimitedAvailabilityAccessors { var limitedGetter: Int { @available(OSX, introduced=10.11) get { return 10 } set(newVal) {} } var limitedSetter: Int { get { return 10 } @available(OSX, introduced=10.11) set(newVal) {} } } @available(*, unavailable) func unavailableFunction() -> Int { return 10 } // expected-note 3{{'unavailableFunction()' has been explicitly marked unavailable here}} class ClassWithReferencesLazyInitializers { var propWithUnavailableInInitializer: Int = unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} lazy var lazyPropWithUnavailableInInitializer: Int = unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} } @available(*, unavailable) func unavailableUseInUnavailableFunction() { // Diagnose references to unavailable functions in non-implicit code // as errors unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} } @available(OSX 10.11, *) func foo() { let _ = SubOfOtherWithInit() }
e1b7be30fca0bf569b7069bbb07e1664
38.440367
215
0.775762
false
false
false
false
kazuhiro4949/EditDistance
refs/heads/master
iOS Example/iOS Example/TableViewController.swift
mit
1
// // TableViewController.swift // // Created by Kazuhiro Hayashi on 2017/02/15. // Copyright © 2017年 Kazuhiro Hayashi. All rights reserved. // import UIKit import EditDistance class TableViewController: UITableViewController { var source = ["a", "b", "c", "d", "e"] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return source.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) cell.textLabel?.text = source[indexPath.row] return cell } @IBAction func rightBarButtonItemDidTap(_ sender: UIBarButtonItem) { let newSource = generateRandomAlphabets() let container = source.diff.compare(to: newSource) source = Array(newSource) tableView.diff.reload(with: container) } private func generateRandomAlphabets() -> [String] { let aScalars = "a".unicodeScalars let aCode = aScalars[aScalars.startIndex].value let newSource = Array((0..<15).map { i -> String in String(describing: UnicodeScalar(Int(aCode) + i)!) }.shuffled()[0...Int(arc4random() % 15)]) return newSource } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /*b // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
0c3fe7c09a0eac3f8cbbbc340071fb76
30.932692
136
0.652213
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Common/UI/Cells/TripCell.swift
agpl-3.0
2
// // TripCell.swift // SmartReceipts // // Created by Bogdan Evsenev on 12/08/2018. // Copyright © 2018 Will Baumann. All rights reserved. // import UIKit class TripCell: SyncableTableCell { @IBOutlet private(set) weak var priceLabel: UILabel! @IBOutlet private(set) weak var nameLabel: UILabel! @IBOutlet private(set) weak var dateLabel: UILabel! @IBOutlet private(set) weak var selectionIndicator: UIView! private let dateFormatter = WBDateFormatter() override func awakeFromNib() { super.awakeFromNib() selectionIndicator.layer.cornerRadius = 5 } @discardableResult func configure(trip: WBTrip, selected: Bool) -> Self { selectionIndicator.isHidden = !selected nameLabel.textColor = selected ? #colorLiteral(red: 0.2020273507, green: 0.1010685936, blue: 0.5962305665, alpha: 1) : #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) priceLabel.text = trip.formattedPrice() nameLabel.text = trip.name let from = dateFormatter.formattedDate(trip.startDate, in: trip.startTimeZone)! let to = dateFormatter.formattedDate(trip.endDate, in: trip.endTimeZone)! dateLabel.text = "\(from) ⇀ \(to)" let state = ModelSyncState.modelState(modelChangeDate: trip.lastLocalModificationTime) setState(state) return self } }
8c6b82bda74148b8ca79b8d7eca4f4fd
33.75
177
0.672662
false
false
false
false
cwwise/CWWeChat
refs/heads/master
CWWeChat/ChatModule/CWChatClient/Model/CWImageMessageBody.swift
mit
2
// // CWImageMessageBody.swift // CWWeChat // // Created by wei chen on 2017/3/31. // Copyright © 2017年 cwcoder. All rights reserved. // import Foundation import SwiftyJSON class CWImageMessageBody: NSObject, CWMessageBody { weak var message: CWMessage? /// 消息体类型 var type: CWMessageType = .image /// 图片尺寸 var size = CGSize.zero /// 缩略图尺寸 var thumbnailSize = CGSize.zero /// 设置发送图片消息时的压缩率 var compressionRatio: Double = 0.6 /// 缩略图的本地路径 var thumbnailLocalPath: String? /// 缩略图服务器地址 var thumbnailURL: URL? /// 原图服务器地址 var originalURL: URL? /// 原图的本地路径 var originalLocalPath: String? init(path: String? = nil, originalURL:URL? = nil, size: CGSize = CGSize.zero) { self.originalURL = originalURL self.originalLocalPath = path self.size = size } } extension CWImageMessageBody { var info: [String: String] { var info = ["size": NSStringFromCGSize(size)] if let urlString = self.originalURL?.absoluteString { info["url"] = urlString } if let path = self.originalLocalPath { info["path"] = path } return info } } extension CWImageMessageBody { var messageEncode: String { do { let data = try JSONSerialization.data(withJSONObject: self.info, options: .prettyPrinted) return String(data: data, encoding: .utf8) ?? "" } catch { return "" } } func messageDecode(string: String) { let json: JSON = JSON(parseJSON: string) if let size = json["size"].string { self.size = CGSizeFromString(size) } if let path = json["path"].string { self.originalLocalPath = path } if let urlstring = json["url"].string, let url = URL(string: urlstring) { self.originalURL = url } } }
5dc78d158732b42049b6c268879f976d
22.136364
101
0.556974
false
false
false
false
corchwll/amos-ss15-proj5_ios
refs/heads/master
MobileTimeAccounting/BusinessLogic/Recording/SessionTimer.swift
agpl-3.0
1
/* Mobile Time Accounting Copyright (C) 2015 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation protocol SessionTimerDelegate { func didUpdateTimer(elapsedTime: String) } class SessionTimer: NSObject { var timerTask: NSTimer! var delegate: SessionTimerDelegate! var startTime: NSDate! var stopTime: NSDate! var isPaused = false var isRunning = false /* Initializer for session timer object. Sets session timer delegate. @methodtype Constructor @pre Requires session timer delegate @post Delegate is set */ init(delegate: SessionTimerDelegate) { self.delegate = delegate } /* Starts session timer by setting start time and starting internal timer task. @methodtype Command @pre Timer must be stopped and not paused @post Session timer started */ func start()->NSDate { startTime = NSDate() isRunning = true isPaused = false timerTask = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("onTimerUpdate"), userInfo: nil, repeats: true) return startTime } /* Callback function, called when timer task is updated. Calculates elapsed time by using start time and current time and calls delegate function. @methodtype Command @pre - @post Calculate elapsed time and call delegate */ func onTimerUpdate() { let currentTimeInSeconds = Int(NSDate().timeIntervalSince1970) let seconds = currentTimeInSeconds - Int(startTime.timeIntervalSince1970) delegate.didUpdateTimer(formatTimeToString(seconds)) } /* Formats a given time interval in seconds to a string representation e.g. '128' -> '2 m 08 s'. @methodtype Convert @pre Time interval in seconds @post Converted string, representing the time */ func formatTimeToString(elapsedTime : Int) -> String { var minutes = elapsedTime/60 var seconds = elapsedTime%60 return String(format: "%d:%0.2d", minutes, seconds) } /* Stops session timer by invalidating timer task and removing timer task object. @methodtype Command @pre Session timer needs to be in running state @post Stops session timer */ func stop()->NSDate { stopTime = NSDate() isPaused = false invalidateTimer() return stopTime } /* Resumes timer task by creating new timer task and setting running true. @methodtype Command @pre Session timer needs to be in pause state @post Resumes timer task */ func resume() { if isPaused { isPaused = false isRunning = true timerTask = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("onTimerUpdate"), userInfo: nil, repeats: true) } } /* Pauses session timer by invalidating timer task and removing timer task object. @methodtype Command @pre Timer must be in running state @post Pauses timer */ func pause() { if isRunning { isPaused = true invalidateTimer() } } /* Invalidates timer task and set running to false. Also removes timer task object by setting value to nil. @methodtype Command @pre Timer must be running @post Invalidates timer task and sets timer task object ot nil */ private func invalidateTimer() { isRunning = false if timerTask != nil { timerTask.invalidate() timerTask = nil } } }
9a58d70c0e66a34dc8e6154be5e24b86
25.560694
146
0.612103
false
false
false
false
Tueno/IconHUD
refs/heads/develop
IconHUD/Functions.swift
mit
1
// // Functions.swift // Summaricon // // Created by tueno on 2017/04/25. // Copyright © 2017年 Tomonori Ueno. All rights reserved. // import Foundation func shell(launchPath: String, currentDirPath: String?, arguments: [String]) -> String { let task = Process() task.launchPath = launchPath if let currentDirPath = currentDirPath { task.currentDirectoryPath = currentDirPath } task.arguments = arguments let pipe = Pipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: String.Encoding.utf8)! return output.replacingOccurrences(of: "\n", with: "") } @discardableResult func bash(command: String, currentDirPath: String?, arguments: [String]) -> String { let whichPathForCommand = shell(launchPath: "/bin/bash", currentDirPath: nil, arguments: [ "-l", "-c", "which \(command)" ]) return shell(launchPath: whichPathForCommand, currentDirPath: currentDirPath, arguments: arguments) }
39afc8ee1397f5064bcd9d8fa0c94813
33.1875
128
0.670932
false
false
false
false
FullMetalFist/SwiftStructures
refs/heads/master
Source/Structures/AVLTree.swift
mit
10
// // AVLNode.swift // SwiftStructures // // Created by Wayne Bishop on 6/26/14. // Copyright (c) 2014 Arbutus Software Inc. All rights reserved. // import Foundation /* An AVL Tree is another name for a balanced binary search tree*/ public class AVLTree<T: Comparable> { var key: T? var left: AVLTree? var right: AVLTree? var height: Int init() { //set math purposes self.height = -1 } //TODO: Build computed count property for class //function to add item based on its value func addNode(key: T) { //check for the root node if (self.key == nil) { self.key = key self.height = 0 return } //check the left side of the tree if (key < self.key) { if (self.left != nil) { left?.addNode(key) } else { //create a new left node let leftChild : AVLTree = AVLTree() leftChild.key = key leftChild.height = 0 self.left = leftChild } //recalculate node height for hierarchy self.setNodeHeight() print("traversing left side. node \(self.key!) with height: \(self.height)...") //check AVL property self.isValidAVLTree() } //end if //check the left side of the tree if (key > self.key) { if (self.right != nil) { right?.addNode(key) } else { //create a new right node let rightChild : AVLTree = AVLTree() rightChild.key = key rightChild.height = 0 self.right = rightChild } //recalculate node height for hierarchy self.setNodeHeight() print("traversing right side. node \(self.key!) with height: \(self.height)...") //check AVL property self.isValidAVLTree() } //end if } //end function // MARK: - tree balancing algorithms //retrieve the height of a node func getNodeHeight(aNode: AVLTree!) -> Int { if (aNode == nil) { return -1 } else { return aNode.height } } //calculate the height of a node func setNodeHeight() -> Bool { //check for a nil condition if (self.key == nil) { print("no key provided..") return false } //println("key: \(self.key!)") //initialize leaf variables var nodeHeight: Int = 0 //do comparision and calculate node height nodeHeight = max(getNodeHeight(self.left), getNodeHeight(self.right)) + 1 self.height = nodeHeight return true } //determine if the tree is "balanced" - operations on a balanced tree is O(log n) func isTreeBalanced() -> Bool { //check for a nil condition if (self.key == nil) { print("no key provided..") return false } //use absolute value to manage right and left imbalances if (abs(getNodeHeight(self.left) - getNodeHeight(self.right)) <= 1) { return true } else { return false } } //end function //check to ensure node meets avl property func isValidAVLTree() -> Bool! { //check for valid scenario if (self.key == nil) { print("no key provided..") return false } if (self.isTreeBalanced() == true) { print("node \(self.key!) already balanced..") return true } //determine rotation type else { //create a new leaf node let childToUse : AVLTree = AVLTree() childToUse.height = 0 childToUse.key = self.key if (getNodeHeight(self.left) - getNodeHeight(self.right) > 1) { print("\n starting right rotation on \(self.key!)..") //reset the root node self.key = self.left?.key self.height = getNodeHeight(self.left) //assign the new right node self.right = childToUse //adjust the left node self.left = self.left?.left self.left?.height = 0 print("root is: \(self.key!) | left is : \(self.left!.key!) | right is : \(self.right!.key!)..") return true } if (getNodeHeight(self.right) - getNodeHeight(self.left) > 1) { print("\n starting left rotation on \(self.key!)..") //reset the root node self.key = self.right?.key self.height = getNodeHeight(self.right) //assign the new left node self.left = childToUse //adjust the right node self.right = self.right?.right self.right?.height = 0 print("root is: \(self.key!) | left is : \(self.left!.key!) | right is : \(self.right!.key!)..") return true } return nil } //end if } //end function // MARK: traversal algorithms //use dfs with trailing closure to update all values func traverse(formula: AVLTree<T> -> T) { //check for a nil condition if self.key == nil { print("no key provided..") return } //process the left side if self.left != nil { left?.traverse(formula) } //invoke formula - apply results let newKey: T = formula(self) self.key! = newKey print("...the updated value is: \(self.key!) - height: \(self.height)..") //process the right side if self.right != nil { right?.traverse(formula) } } //traverse all values func traverse() { //check for a nil condition if self.key == nil { print("no key provided..") return } //process the left side if self.left != nil { left?.traverse() } print("...the value is: \(self.key!) - height: \(self.height)..") //process the right side if self.right != nil { right?.traverse() } } } //end class
cd7b20c843f899cdf187f8efe4387c11
21.671642
112
0.425336
false
false
false
false
Allow2CEO/browser-ios
refs/heads/development
Storage/CertStore.swift
mpl-2.0
14
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import UIKit import Deferred /// In-memory certificate store. open class CertStore { fileprivate var keys = Set<String>() public init() {} open func addCertificate(_ cert: SecCertificate, forOrigin origin: String) { let data: Data = SecCertificateCopyData(cert) as Data let key = keyForData(data, origin: origin) keys.insert(key) } open func containsCertificate(_ cert: SecCertificate, forOrigin origin: String) -> Bool { let data: Data = SecCertificateCopyData(cert) as Data let key = keyForData(data, origin: origin) return keys.contains(key) } fileprivate func keyForData(_ data: Data, origin: String) -> String { return "\(origin)/\(data.sha256.hexEncodedString)" } }
2456739be684e69bd708b84c20bc6160
31.354839
93
0.678963
false
false
false
false
Constructor-io/constructorio-client-swift
refs/heads/master
AutocompleteClient/FW/API/Parser/Search/SearchResponseParser.swift
mit
1
// // SearchResponseParser.swift // AutocompleteClient // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import Foundation class SearchResponseParser: AbstractSearchResponseParser { func parse(searchResponseData: Data) throws -> CIOSearchResponse { do { let json = try JSONSerialization.jsonObject(with: searchResponseData) as? JSONObject guard let response = json?["response"] as? JSONObject else { throw CIOError(errorType: .invalidResponse) } let facetsObj: [JSONObject]? = response["facets"] as? [JSONObject] let resultsObj: [JSONObject]? = response["results"] as? [JSONObject] let sortOptionsObj: [JSONObject]? = response["sort_options"] as? [JSONObject] let groupsObj = response["groups"] as? [JSONObject] let refinedContentObj = response["refined_content"] as? [JSONObject] let facets: [CIOFilterFacet] = (facetsObj)?.compactMap { obj in return CIOFilterFacet(json: obj) } ?? [] let results: [CIOResult] = (resultsObj)?.compactMap { obj in return CIOResult(json: obj) } ?? [] let sortOptions: [CIOSortOption] = (sortOptionsObj)?.compactMap({ obj in return CIOSortOption(json: obj) }) ?? [] let groups: [CIOFilterGroup] = groupsObj?.compactMap({ obj in return CIOFilterGroup(json: obj) }) ?? [] let totalNumResults = response["total_num_results"] as? Int ?? 0 let resultID = json?["result_id"] as? String ?? "" let resultSources: CIOResultSources? = CIOResultSources(json: response["result_sources"] as? JSONObject) let refinedContent: [CIORefinedContent] = refinedContentObj?.compactMap({ obj in return CIORefinedContent(json: obj) }) ?? [] return CIOSearchResponse( facets: facets, groups: groups, results: results, redirectInfo: CIOSearchRedirectInfo(object: response["redirect"] as? JSONObject), sortOptions: sortOptions, totalNumResults: totalNumResults, resultID: resultID, resultSources: resultSources, refinedContent: refinedContent ) } catch { throw CIOError(errorType: .invalidResponse) } } }
aad75c52dae89cac75a00c1b53456ec4
44.711538
137
0.618847
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Controllers/Subscriptions/SubscriptionsList/SubscriptionsViewController.swift
mit
1
// // SubscriptionsViewController.swift // Rocket.Chat // // Created by Rafael K. Streit on 7/21/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import RealmSwift import SwipeCellKit // swiftlint:disable file_length final class SubscriptionsViewController: BaseViewController { enum SearchState { case searchingLocally case searchingRemotely case notSearching } @IBOutlet weak var tableView: UITableView! @IBOutlet weak var filterSeperator: UIView! @IBOutlet weak var labelSortingTitleDescription: UILabel! { didSet { updateSortingTitleDescription() } } @IBOutlet weak var viewDirectory: UIView! { didSet { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(recognizeDirectoryTapGesture(_:))) viewDirectory.addGestureRecognizer(tapGesture) } } @IBOutlet weak var imageViewDirectory: UIImageView! { didSet { imageViewDirectory.image = imageViewDirectory.image?.imageWithTint(.RCBlue()) } } @IBOutlet weak var labelDirectory: UILabel! { didSet { labelDirectory.text = localized("directory.title") } } weak var sortingView: SubscriptionsSortingView? weak var serversView: ServersListView? weak var titleView: SubscriptionsTitleView? weak var searchController: UISearchController? var searchBar: UISearchBar? { return searchController?.searchBar } var assigned = false var viewModel = SubscriptionsViewModel() var searchText: String = "" let socketHandlerToken = String.random(5) deinit { SocketManager.removeConnectionHandler(token: socketHandlerToken) NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { setupSearchBar() setupTitleView() updateBackButton() startObservingKeyboard() super.viewDidLoad() navigationItem.leftBarButtonItem?.accessibilityLabel = VOLocalizedString("channel.preferences.label") // If the device is not using the SplitView, we want to show // the 3D Touch preview for the cells if splitViewController?.detailViewController as? BaseNavigationController == nil { registerForPreviewing(with: self, sourceView: tableView) } viewModel.didUpdateIndexPaths = { [weak self] changes, completion in guard let tableView = self?.tableView else { return } // Update back button title with the number of unreads self?.updateBackButton() tableView.reload(using: changes, with: .fade, updateRows: { indexPaths in for indexPath in indexPaths { if tableView.indexPathsForVisibleRows?.contains(indexPath) ?? false, let cell = tableView.cellForRow(at: indexPath) as? BaseSubscriptionCell { self?.loadContents(for: cell, at: indexPath) } } }, setData: { completion($0) }) } viewModel.updateVisibleCells = { [weak self] in for indexPath in self?.tableView.indexPathsForVisibleRows ?? [] { if let cell = self?.tableView.cellForRow(at: indexPath) as? BaseSubscriptionCell { self?.loadContents(for: cell, at: indexPath) } } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() serversView?.frame = frameForDropDownOverlay sortingView?.frame = frameForDropDownOverlay } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // This method can stay here, since adding a new connection handler // will override the existing one if there's already one. This is here // to prevent that some connection issue removes all the connection handler. SocketManager.addConnectionHandler(token: socketHandlerToken, handler: self) updateServerInformation() if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: animated) } viewModel.buildSections() titleView?.state = SocketManager.sharedInstance.state } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !(searchBar?.text?.isEmpty ?? true) { searchBar?.perform(#selector(becomeFirstResponder), with: nil, afterDelay: 0.1) } } override func viewDidDisappear(_ animated: Bool) { SocketManager.removeConnectionHandler(token: socketHandlerToken) } // MARK: Storyboard Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Servers" { segue.destination.modalPresentationCapturesStatusBarAppearance = true } } // MARK: Keyboard private func startObservingKeyboard() { NotificationCenter.default.addObserver( self, selector: #selector(onKeyboardFrameWillChange(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(onKeyboardFrameWillChange(_:)), name: UIResponder.keyboardWillHideNotification, object: nil ) } @objc private func onKeyboardFrameWillChange(_ notification: Notification) { guard let userInfo = notification.userInfo, let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { tableView.contentInset.bottom = 0 return } let keyboardFrameInView = view.convert(keyboardFrame, from: nil) let animationDuration: TimeInterval = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue let animationCurve = UIView.AnimationOptions(rawValue: animationCurveRaw) UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { self.tableView.contentInset.bottom = notification.name == UIResponder.keyboardWillHideNotification ? 0 : keyboardFrameInView.height }, completion: nil) } // MARK: Setup Views func updateBackButton() { var unread = 0 Realm.execute({ (realm) in for obj in realm.objects(Subscription.self) { unread += obj.unread } }, completion: { [weak self] in self?.navigationItem.backBarButtonItem = UIBarButtonItem( title: unread == 0 ? "" : "\(unread)", style: .plain, target: nil, action: nil ) }) } func setupSearchBar() { let searchController = UISearchController(searchResultsController: nil) searchController.obscuresBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false navigationController?.navigationBar.prefersLargeTitles = false navigationItem.largeTitleDisplayMode = .never navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = true self.searchController = searchController searchBar?.placeholder = localized("subscriptions.search") searchBar?.delegate = self searchBar?.applyTheme() } func setupTitleView() { if let titleView = SubscriptionsTitleView.instantiateFromNib() { titleView.translatesAutoresizingMaskIntoConstraints = false titleView.layoutIfNeeded() titleView.sizeToFit() updateServerInformation() // This code can be removed when we drop iOS 10 support. titleView.translatesAutoresizingMaskIntoConstraints = true navigationItem.titleView = titleView self.titleView = titleView let tapGesture = UITapGestureRecognizer(target: self, action: #selector(recognizeTitleViewTapGesture(_:))) titleView.addGestureRecognizer(tapGesture) } } } extension SubscriptionsViewController: UISearchBarDelegate { func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) serversView?.close() sortingView?.close() } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { viewModel.searchState = .notSearching } else { viewModel.searchState = .searching(query: searchText) } viewModel.buildSections() } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { viewModel.searchState = .notSearching searchBar.setShowsCancelButton(false, animated: true) searchBar.resignFirstResponder() searchBar.text = "" viewModel.buildSections() } func updateServerInformation() { if let serverName = AuthSettingsManager.settings?.serverName { titleView?.updateServerName(name: serverName) } else if let serverURL = AuthManager.isAuthenticated()?.serverURL { if let host = URL(string: serverURL)?.host { titleView?.updateServerName(name: host) } else { titleView?.updateServerName(name: serverURL) } } else { titleView?.updateServerName(name: "Rocket.Chat") } } private func shouldRespondToTap(recognizer: UITapGestureRecognizer, inset: CGFloat) -> Bool { guard let view = recognizer.view, recognizer.state == .ended else { return false } let tapLocation = recognizer.location(in: view).y return tapLocation > inset && tapLocation < view.bounds.height - inset } // MARK: IBAction @IBAction func recognizeSortingHeaderTapGesture(_ recognizer: UITapGestureRecognizer) { if shouldRespondToTap(recognizer: recognizer, inset: 8) { toggleSortingView() } } @objc func recognizeDirectoryTapGesture(_ recognizer: UITapGestureRecognizer) { guard let controller = UIStoryboard(name: "Directory", bundle: Bundle.main).instantiateInitialViewController() else { return } if UIDevice.current.userInterfaceIdiom == .pad { let nav = BaseNavigationController(rootViewController: controller) nav.modalPresentationStyle = .pageSheet present(nav, animated: true, completion: nil) } else { navigationController?.pushViewController(controller, animated: true) } } @objc func recognizeTitleViewTapGesture(_ recognizer: UITapGestureRecognizer) { guard #available(iOS 11.0, *) else { return toggleServersList() } if shouldRespondToTap(recognizer: recognizer, inset: 6) { toggleServersList() } } func toggleSortingView() { serversView?.close() if let sortingView = sortingView { sortingView.close() } else { sortingView = SubscriptionsSortingView.showIn(view) sortingView?.delegate = self } } func toggleServersList() { if serversView != nil { closeServersList() } else { openServersList() } } func openServersList() { guard serversView == nil && AppManager.supportsMultiServer else { return } sortingView?.close() titleView?.updateTitleImage(reverse: true) serversView = ServersListView.showIn(view, frame: frameForDropDownOverlay) serversView?.delegate = self } func closeServersList() { guard let serversView = serversView else { return } titleView?.updateTitleImage(reverse: false) serversView.close() } private var frameForDropDownOverlay: CGRect { var frameHeight = view.bounds.height let yOffset = view.safeAreaInsets.top frameHeight -= view.safeAreaInsets.top - view.safeAreaInsets.bottom return CGRect(x: 0.0, y: yOffset, width: view.bounds.width, height: view.bounds.height) } } // MARK: UIViewControllerPreviewingDelegate extension SubscriptionsViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { navigationController?.pushViewController(viewControllerToCommit, animated: true) } func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath), let subscription = viewModel.subscriptionForRowAt(indexPath: indexPath) else { return nil } previewingContext.sourceRect = cell.frame if let controller = UIStoryboard.controller(from: "Chat", identifier: "Chat") as? MessagesViewController { controller.subscription = subscription.managedObject return controller } return nil } } extension SubscriptionsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 71 } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 71 } func numberOfSections(in tableView: UITableView) -> Int { return viewModel.numberOfSections } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfRowsInSection(section) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard let cell = cell as? SubscriptionCellProtocol else { return } guard let selectedSubscription = MainSplitViewController.chatViewController?.subscription?.validated() else { return } if cell.subscription?.identifier == selectedSubscription.identifier { tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = viewModel.hasLastMessage ? cellForSubscription(at: indexPath) : cellForSubscriptionCondensed(at: indexPath) (cell as? SwipeTableViewCell)?.delegate = self cell.accessoryType = .none return cell } func cellForSubscription(at indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: SubscriptionCell.identifier) as? SubscriptionCell else { return UITableViewCell() } loadContents(for: cell, at: indexPath) return cell } func cellForSubscriptionCondensed(at indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: SubscriptionCellCondensed.identifier) as? SubscriptionCellCondensed else { return UITableViewCell() } loadContents(for: cell, at: indexPath) return cell } func loadContents(for cell: BaseSubscriptionCell, at indexPath: IndexPath) { if let subscription = viewModel.subscriptionForRowAt(indexPath: indexPath) { cell.subscription = subscription } } } extension SubscriptionsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat(viewModel.heightForHeaderIn(section: section)) } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let view = SubscriptionSectionView.instantiateFromNib() else { return nil } view.setTitle(viewModel.titleForHeaderInSection(section)) return view } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { onSelectRowAt(indexPath) } func onSelectRowAt(_ indexPath: IndexPath) { guard let subscription = viewModel.subscriptionForRowAt(indexPath: indexPath)?.managedObject else { return } guard searchController?.searchBar.isFirstResponder == false else { searchController?.searchBar.resignFirstResponder() searchController?.dismiss(animated: false, completion: { self.openChat(for: subscription) }) return } openChat(for: subscription) } func openChat(for subscription: Subscription) { guard let controller = UIStoryboard.controller(from: "Chat", identifier: "Chat") as? MessagesViewController else { return } controller.subscription = subscription // When using iPads, we override the detail controller creating // a new instance. if parent?.parent?.traitCollection.horizontalSizeClass == .compact { guard navigationController?.topViewController == self else { return } navigationController?.pushViewController(controller, animated: true) } else { let nav = BaseNavigationController(rootViewController: controller) splitViewController?.showDetailViewController(nav, sender: self) } } } extension SubscriptionsViewController: SwipeTableViewCellDelegate { func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? { guard let subscription = viewModel.subscriptionForRowAt(indexPath: indexPath)?.managedObject, subscription.open else { return nil } switch orientation { case .left: if !subscription.alert { let markUnread = SwipeAction(style: .destructive, title: localized("subscriptions.list.actions.unread")) { _, _ in API.current()?.client(SubscriptionsClient.self).markUnread(subscription: subscription) } markUnread.backgroundColor = view.theme?.tintColor ?? #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1) markUnread.image = #imageLiteral(resourceName: "Swipe unread") return [markUnread] } else { let markRead = SwipeAction(style: .destructive, title: localized("subscriptions.list.actions.read")) { _, _ in API.current()?.client(SubscriptionsClient.self).markRead(subscription: subscription) } markRead.backgroundColor = view.theme?.tintColor ?? #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1) markRead.image = #imageLiteral(resourceName: "Swipe read") return [markRead] } case .right: let hide = SwipeAction(style: .destructive, title: localized("subscriptions.list.actions.hide")) { _, _ in API.current()?.client(SubscriptionsClient.self).hideSubscription(subscription: subscription) } hide.backgroundColor = #colorLiteral(red: 0.3294117647, green: 0.3450980392, blue: 0.368627451, alpha: 1) hide.image = #imageLiteral(resourceName: "Swipe hide") let favoriteTitle = subscription.favorite ? "subscriptions.list.actions.unfavorite" : "subscriptions.list.actions.favorite" let favorite = SwipeAction(style: .default, title: localized(favoriteTitle)) { _, _ in API.current()?.client(SubscriptionsClient.self).favoriteSubscription(subscription: subscription) } favorite.hidesWhenSelected = true favorite.backgroundColor = #colorLiteral(red: 1, green: 0.7333333333, blue: 0, alpha: 1) favorite.image = subscription.favorite ? #imageLiteral(resourceName: "Swipe unfavorite") : #imageLiteral(resourceName: "Swipe favorite") return [hide, favorite] } } func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions { var options = SwipeOptions() options.expansionStyle = .selection options.transitionStyle = .border if orientation == .left { options.backgroundColor = view.theme?.tintColor ?? #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1) } return options } } extension SubscriptionsViewController: SubscriptionsSortingViewDelegate { func updateSortingTitleDescription() { if SubscriptionsSortingManager.selectedSortingOption == .alphabetically { labelSortingTitleDescription.text = localized("subscriptions.sorting.title.alphabetical") } else { labelSortingTitleDescription.text = localized("subscriptions.sorting.title.activity") } } func userDidChangeSortingOptions() { let selectedSortingOption = SubscriptionsSortingManager.selectedSortingOption.rawValue let selectedGroupingOptions = SubscriptionsSortingManager.selectedGroupingOptions.map {$0.rawValue} AnalyticsManager.log( event: .updatedSubscriptionSorting( sorting: selectedSortingOption, grouping: selectedGroupingOptions.joined(separator: " | ") ) ) viewModel.buildSections() updateSortingTitleDescription() } } extension SubscriptionsViewController: SocketConnectionHandler { func socketDidChangeState(state: SocketConnectionState) { Log.debug("[SubscriptionsViewController] socketDidChangeState: \(state)") titleView?.state = state } } extension SubscriptionsViewController: ServerListViewDelegate { func serverListViewDidClose() { titleView?.updateTitleImage(reverse: false) } } // MARK: Themeable extension SubscriptionsViewController { override func applyTheme() { super.applyTheme() guard let theme = view.theme else { return } navigationController?.view.backgroundColor = theme.backgroundColor searchBar?.applyTheme() if serversView != nil { titleView?.updateTitleImage(reverse: true) } else { titleView?.updateTitleImage(reverse: false) } } } // MARK: Room Selection Helpers extension SubscriptionsViewController { func selectRoomAt(_ index: Int) { guard let indexPath = viewModel.indexPathForAbsoluteIndex(index), indexPath.row >= 0 && indexPath.section >= 0 else { return } tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) onSelectRowAt(indexPath) DispatchQueue.main.async { [weak self] in self?.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true) } } func selectNextRoom() { if let indexPath = tableView.indexPathsForSelectedRows?.first { selectRoomAt(viewModel.absoluteIndexForIndexPath(indexPath) + 1) } } func selectPreviousRoom() { if let indexPath = tableView.indexPathsForSelectedRows?.first { selectRoomAt(viewModel.absoluteIndexForIndexPath(indexPath) - 1) } } }
36b2962194e4e4dc60e3f79153ca7f07
34.559767
153
0.657293
false
false
false
false
iOSTestApps/Cherry
refs/heads/master
Cherry WatchKit Extension/InterfaceControllers/KTWatchGlanceInterfaceController.swift
mit
1
// // KTWatchGlanceInterfaceController.swift // Cherry // // Created by Kenny Tang on 2/24/15. // // import WatchKit import Foundation class KTWatchGlanceInterfaceController: WKInterfaceController { @IBOutlet weak var timerRingGroup:WKInterfaceGroup? @IBOutlet weak var timeLabel:WKInterfaceLabel? @IBOutlet weak var activityNameLabel:WKInterfaceLabel? var currentBackgroundImageString:String? override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) self.currentBackgroundImageString = "circles_background"; } override func willActivate() { super.willActivate() self.updateInterfaceWithActiveActivity() self.updateUserActivityForHandOff() } // MARK: willActivate helper methods func updateInterfaceWithActiveActivity() { if let activity = KTActivityManager.sharedInstance.activeActivityInSharedStorage() { self.activityNameLabel!.setText(activity.activityName) let displayMinutesString = KTTimerFormatter.formatTimeIntToTwoDigitsString(KTTimerFormatter.formatPomoRemainingMinutes(activity.elapsedSecs)) let displaySecsString = KTTimerFormatter.formatTimeIntToTwoDigitsString(KTTimerFormatter.formatPomoRemainingSecsInCurrentMinute(activity.elapsedSecs)) self.timeLabel!.setText("\(displayMinutesString):\(displaySecsString)") self.updateTimerBackgroundImage(activity.elapsedSecs) } } func updateUserActivityForHandOff() { if let activity = KTActivityManager.sharedInstance.activeActivityInSharedStorage() { let userInfo = ["type" : "bb.com.corgitoergosum.KTPomodoro.select_activity", "activityID" : activity.activityID] self.updateUserActivity("bb.com.corgitoergosum.KTPomodoro.active_task", userInfo: userInfo, webpageURL: nil) } } // MARK: updateInterfaceWithActiveActivity helper methods func updateTimerBackgroundImage(elapsedSecs:Int) { let elapsedSections = elapsedSecs/((KTSharedUserDefaults.pomoDuration*60)/12) let backgroundImageString = "circles_\(elapsedSections)" println("backgroundImageString: \(backgroundImageString)") if (backgroundImageString != self.currentBackgroundImageString!) { self.currentBackgroundImageString = backgroundImageString self.timerRingGroup!.setBackgroundImageNamed(backgroundImageString) } } }
a8386ac902fb2e0a40e18f23f7cfb765
35.850746
162
0.738761
false
false
false
false
rnystrom/GitHawk
refs/heads/master
Classes/Issues/DiffHunk/IssueDiffHunkPreviewCell.swift
mit
1
// // IssueDiffHunkPreviewCell.swift // Freetime // // Created by Ryan Nystrom on 7/3/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit import StyledTextKit final class IssueDiffHunkPreviewCell: IssueCommentBaseCell, ListBindable { static let textViewInset = UIEdgeInsets( top: Styles.Sizes.rowSpacing, left: 0, bottom: Styles.Sizes.rowSpacing, right: 0 ) let scrollView = UIScrollView() let textView = StyledTextView() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(scrollView) scrollView.addSubview(textView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() scrollView.frame = CGRect( x: 0, y: 0, width: contentView.bounds.width, height: scrollView.contentSize.height ) } // MARK: ListBindable func bindViewModel(_ viewModel: Any) { guard let viewModel = viewModel as? StyledTextRenderer else { return } let width: CGFloat = 0 scrollView.contentSize = viewModel.viewSize(in: width) textView.configure(with: viewModel, width: width) } }
2e3eb2f4180cd3835703e848091f4ee5
23.672727
78
0.641857
false
false
false
false
ftiff/CasperSplash
refs/heads/master
SplashBuddy/Views/Main/MainViewController_Actions.swift
gpl-3.0
1
// // Copyright © 2018 Amaris Technologies GmbH. All rights reserved. // import Foundation extension MainViewController { /// User pressed the continue (or restart, logout…) button @IBAction func pressedContinueButton(_ sender: AnyObject) { Preferences.sharedInstance.setupDone = true Preferences.sharedInstance.continueAction.pressed(sender) } /// Set the initial state of the view func setupInstalling() { indeterminateProgressIndicator.startAnimation(self) indeterminateProgressIndicator.isHidden = false statusLabel.isHidden = false statusLabel.stringValue = NSLocalizedString("actions.preparing_your_mac") sidebarView.isHidden = Preferences.sharedInstance.sidebar continueButton.isEnabled = false } /// reset the status label to "We are preparing your Mac…" @objc func resetStatusLabel() { statusLabel.stringValue = NSLocalizedString("actions.preparing_your_mac") } /// sets the status label to display an error @objc func errorWhileInstalling() { Preferences.sharedInstance.errorWhileInstalling = true guard let error = SoftwareArray.sharedInstance.localizedErrorStatus else { return } statusLabel.textColor = .red statusLabel.stringValue = error } /// all critical software is installed @objc func canContinue() { Preferences.sharedInstance.criticalDone = true self.continueButton.isEnabled = true } /// all software is installed (failed or success) @objc func doneInstalling() { Preferences.sharedInstance.allInstalled = true indeterminateProgressIndicator.stopAnimation(self) indeterminateProgressIndicator.isHidden = true if Preferences.sharedInstance.labMode { self.sidebarView.isHidden = true if let labComplete = Preferences.sharedInstance.labComplete { self.webView.loadFileURL(labComplete, allowingReadAccessTo: Preferences.sharedInstance.assetPath) } else { let errorMsg = NSLocalizedString("error.create_complete_html_file") self.webView.loadHTMLString(errorMsg, baseURL: nil) } } } /// all software is sucessfully installed @objc func allSuccess() { Preferences.sharedInstance.allSuccessfullyInstalled = true statusLabel.textColor = .labelColor statusLabel.stringValue = Preferences.sharedInstance.continueAction.localizedSuccessStatus } }
e08f10b48a5dd0b8abe0e569d26c2165
34.027397
113
0.690653
false
false
false
false
calebd/ReactiveCocoa
refs/heads/master
ReactiveCocoaTests/UIKit/UIControlSpec.swift
mit
2
import ReactiveSwift import ReactiveCocoa import UIKit import Quick import Nimble import enum Result.NoError class UIControlSpec: QuickSpec { override func spec() { var control: UIControl! weak var _control: UIControl? beforeEach { control = UIControl(frame: .zero) _control = control } afterEach { control = nil expect(_control).to(beNil()) } it("should accept changes from bindings to its enabling state") { control.isEnabled = false let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() control.reactive.isEnabled <~ SignalProducer(signal: pipeSignal) observer.send(value: true) expect(control.isEnabled) == true observer.send(value: false) expect(control.isEnabled) == false } it("should accept changes from bindings to its selecting state") { control.isSelected = false let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() control.reactive.isSelected <~ SignalProducer(signal: pipeSignal) observer.send(value: true) expect(control.isSelected) == true observer.send(value: false) expect(control.isSelected) == false } it("should accept changes from bindings to its highlighting state") { control.isHighlighted = false let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() control.reactive.isHighlighted <~ SignalProducer(signal: pipeSignal) observer.send(value: true) expect(control.isHighlighted) == true observer.send(value: false) expect(control.isHighlighted) == false } it("should accept changes from mutliple bindings to its states") { control.isSelected = false control.isEnabled = false let (pipeSignalSelected, observerSelected) = Signal<Bool, NoError>.pipe() let (pipeSignalEnabled, observerEnabled) = Signal<Bool, NoError>.pipe() control.reactive.isSelected <~ SignalProducer(signal: pipeSignalSelected) control.reactive.isEnabled <~ SignalProducer(signal: pipeSignalEnabled) observerSelected.send(value: true) observerEnabled.send(value: true) expect(control.isEnabled) == true expect(control.isSelected) == true observerSelected.send(value: false) expect(control.isEnabled) == true expect(control.isSelected) == false observerEnabled.send(value: false) expect(control.isEnabled) == false expect(control.isSelected) == false } } }
f7463e24589dcd2cc638c37de579448f
26.761905
76
0.727273
false
false
false
false
solszl/Shrimp500px
refs/heads/master
Shrimp500px/ViewControllers/Discover/UserView/UserView.swift
mit
1
// // UserView.swift // Shrimp500px // // Created by 振亮 孙 on 16/3/7. // Copyright © 2016年 papa.studio. All rights reserved. // import UIKit class UserView: UIView { var tableView: UITableView! var userVM = UserViewModel() override init(frame: CGRect) { tableView = UITableView() super.init(frame: frame) self.addSubview(tableView) tableView.snp_makeConstraints { (make) -> Void in make.size.equalTo(self) make.center.equalTo(self) } tableView.registerClass(RecommendUser.self, forCellReuseIdentifier: NibNames.RecommendUser) tableView.estimatedRowHeight = ScreenWidth - 20 tableView.separatorStyle = .None tableView.dataSource = self tableView.delegate = self tableView.allowsSelection = false userVM.fetchNewUser() { self.tableView.reloadData() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension UserView: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return userVM.data.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(NibNames.RecommendUser) as! RecommendUser cell.configWithUserData(userVM.data[indexPath.row] ) return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let h = tableView.fd_heightForCellWithIdentifier(NibNames.RecommendUser) { (obj) -> Void in let cell = obj as! RecommendUser cell.configWithUserData(self.userVM.data[indexPath.row] ) } print(h) return h } } extension UserView: UITableViewDelegate { }
7cff0eb8bde0a6c011e546a6042b4310
26.527027
109
0.631321
false
false
false
false
iostektalk/tektalk-app
refs/heads/master
Source code/Tek Talk/Constant.swift
mit
1
// // Constant.swift // Tek Talk // // Created by Nghia Tran Vinh on 5/20/16. // Copyright © 2016 Zyncas. All rights reserved. // import Foundation // PARSE let k_PARSE_APPLICATION_ID = "xgxj79iZFoq3c7y1Gif2uhbCoQksiVOl4Xwd43WJ" let k_PARSE_CLIENT_KEY = "LcJGIrbZ70W2UIQ6lZodzrAF0XFlP1nFht6wlsbi" // PARSE FIELDS let k_Classname_Event = "Event" let k_Classname_Video = "Video" let k_Classname_Speaker = "Speaker" let k_ClassName_Document = "Document" // EVENT let k_Event_Title = "title" let k_Event_ShortDescription = "shortDescription" let k_Event_StartAt = "startAt" let k_Event_EndAt = "endAt" let k_Event_Speaker = "speaker" let k_Event_Tags = "tags" let k_Event_Documents = "documents" let k_Event_Videos = "videos" let k_Event_Schedules = "schedules" let k_Event_Type = "type" let k_Event_Type_Event = "event" let k_Event_Type_Talk = "talk"
372f9043b6a6ebc057e34e59d437f47b
24.764706
71
0.710857
false
false
false
false
stevewight/DetectorKit
refs/heads/master
DetectorKit/Models/Helpers/CoordConverter.swift
mit
1
// // CoordConverter.swift // Sherlock // // Created by Steve on 12/10/16. // Copyright © 2016 Steve Wight. All rights reserved. // import UIKit class CoordConverter: NSObject { var transform:CGAffineTransform! var imageSize:CGSize! var viewSize:CGSize! init(_ inputImageSize:CGSize,_ inputViewSize:CGSize) { super.init() imageSize = inputImageSize viewSize = inputViewSize transform = executeTransform() } public func convert(_ bounds:CGRect)->CGRect { var newBounds = bounds.applying(transform) let scale = calcScale() newBounds = newBounds.applying(scaleTranform(scale)) newBounds.origin.x += calcOffsetX(scale) newBounds.origin.y += calcOffsetY(scale) return newBounds } private func executeTransform()->CGAffineTransform { let newTransform = CGAffineTransform(scaleX: 1, y: -1) return newTransform.translatedBy(x: 0, y: -imageSize.height) } private func calcScale()->CGFloat { return min(viewSize.width / imageSize.width, viewSize.height / imageSize.height) } private func calcOffsetX(_ scale:CGFloat)->CGFloat { return (viewSize.width - imageSize.width * scale) / 2 } private func calcOffsetY(_ scale:CGFloat)->CGFloat { return (viewSize.height - imageSize.height * scale) / 2 } private func scaleTranform(_ scale:CGFloat)->CGAffineTransform { return CGAffineTransform(scaleX: scale, y: scale) } }
ad3ddc87d998f460cd315f1afac027ef
26.465517
68
0.629002
false
false
false
false
firebase/quickstart-ios
refs/heads/master
firestore/FirestoreExample/StarsView.swift
apache-2.0
1
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit class RatingView: UIControl { var highlightedColor: CGColor = Constants.highlightedColorOrange var rating: Int? { didSet { if let value = rating { setHighlighted(index: value - 1) } else { clearAll() } // highlight the appropriate amount of stars. sendActions(for: .valueChanged) } } private let starLayers: [CAShapeLayer] override init(frame: CGRect) { starLayers = (0 ..< 5).map { let layer = RatingView.starLayer() layer.frame = CGRect(x: $0 * 55, y: 0, width: 25, height: 25) return layer } super.init(frame: frame) starLayers.forEach { layer.addSublayer($0) } } private var starWidth: CGFloat { return intrinsicContentSize.width / 5 } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) guard let touch = touches.first else { return } let point = touch.location(in: self) let index = clamp(Int(point.x / starWidth)) setHighlighted(index: index) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) guard let touch = touches.first else { return } let point = touch.location(in: self) let index = clamp(Int(point.x / starWidth)) setHighlighted(index: index) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) guard let touch = touches.first else { return } let point = touch.location(in: self) let index = clamp(Int(point.x / starWidth)) rating = index + 1 // Ratings are 1-indexed; things can be between 1-5 stars. } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) guard touches.first != nil else { return } // Cancelled touches should preserve the value before the interaction. if let oldRating = rating { let oldIndex = oldRating - 1 setHighlighted(index: oldIndex) } else { clearAll() } } /// This is an awful func name. Index must be within 0 ..< 4, or crash. private func setHighlighted(index: Int) { // Highlight everything up to and including the star at the index. (0 ... index).forEach { let star = starLayers[$0] star.strokeColor = highlightedColor star.fillColor = highlightedColor } // Unhighlight everything after the index, if applicable. guard index < 4 else { return } ((index + 1) ..< 5).forEach { let star = starLayers[$0] star.strokeColor = highlightedColor star.fillColor = nil } } /// Unhighlights every star. private func clearAll() { (0 ..< 5).forEach { let star = starLayers[$0] star.strokeColor = highlightedColor star.fillColor = nil } } private func clamp(_ index: Int) -> Int { if index < 0 { return 0 } if index > 4 { return 4 } return index } override var intrinsicContentSize: CGSize { return CGSize(width: 270, height: 50) } override var isMultipleTouchEnabled: Bool { get { return false } set {} } private static func starLayer() -> CAShapeLayer { let layer = CAShapeLayer() let mutablePath = CGMutablePath() let outerRadius: CGFloat = 18 let outerPoints = stride(from: CGFloat.pi / -5, to: .pi * 2, by: 2 * .pi / 5).map { CGPoint(x: outerRadius * sin($0) + 25, y: outerRadius * cos($0) + 25) } let innerRadius: CGFloat = 6 let innerPoints = stride(from: 0, to: .pi * 2, by: 2 * .pi / 5).map { CGPoint(x: innerRadius * sin($0) + 25, y: innerRadius * cos($0) + 25) } let points = zip(outerPoints, innerPoints) .reduce([CGPoint]()) { (aggregate, pair) -> [CGPoint] in aggregate + [pair.0, pair.1] } mutablePath.move(to: points[0]) points.forEach { mutablePath.addLine(to: $0) } mutablePath.closeSubpath() layer.path = mutablePath.copy() layer.strokeColor = UIColor.gray.cgColor layer.lineWidth = 1 layer.fillColor = nil return layer } @available(*, unavailable) required convenience init?(coder aDecoder: NSCoder) { // coder is ignored. self.init(frame: CGRect(x: 0, y: 0, width: 270, height: 50)) translatesAutoresizingMaskIntoConstraints = false } private enum Constants { static let unhighlightedColor = UIColor.gray.cgColor static let highlightedColorOrange = UIColor( red: 255 / 255, green: 179 / 255, blue: 0 / 255, alpha: 1 ).cgColor } // MARK: Rating View Accessibility override var isAccessibilityElement: Bool { get { return true } set {} } override var accessibilityValue: String? { get { if let rating = rating { return NSLocalizedString( "\(rating) out of 5", comment: "Format string for indicating a variable amount of stars out of five" ) } return NSLocalizedString( "No rating", comment: "Read by VoiceOver to vision-impaired users indicating a rating that hasn't been filled out yet" ) } set {} } override var accessibilityTraits: UIAccessibilityTraits { get { return UIAccessibilityTraits.adjustable } set {} } override func accessibilityIncrement() { let currentRatingIndex = (rating ?? 0) - 1 let highlightedIndex = clamp(currentRatingIndex + 1) rating = highlightedIndex + 1 } override func accessibilityDecrement() { guard let rating = rating else { return } // Doesn't make sense to decrement no rating and get 1. let currentRatingIndex = rating - 1 let highlightedIndex = clamp(currentRatingIndex - 1) self.rating = highlightedIndex + 1 } } // This class is absolutely not immutable, but it's also not user-interactive. class ImmutableStarsView: UIView { override var intrinsicContentSize: CGSize { get { return CGSize(width: 100, height: 20) } set {} } var highlightedColor: CGColor = Constants.highlightedColorOrange var rating: Int? { didSet { if let value = rating { setHighlighted(index: value - 1) } else { clearAll() } } } private let starLayers: [CAShapeLayer] override init(frame: CGRect) { starLayers = (0 ..< 5).map { let layer = ImmutableStarsView.starLayer() layer.frame = CGRect(x: $0 * 20, y: 0, width: 20, height: 20) return layer } super.init(frame: frame) starLayers.forEach { layer.addSublayer($0) } } private var starWidth: CGFloat { return intrinsicContentSize.width / 5 } /// This is an awful func name. Index must be within 0 ..< 4, or crash. private func setHighlighted(index anyIndex: Int) { if anyIndex < 0 { clearAll() return } let index = clamp(anyIndex) // Highlight everything up to and including the star at the index. (0 ... index).forEach { let star = starLayers[$0] star.strokeColor = highlightedColor star.fillColor = highlightedColor } // Unhighlight everything after the index, if applicable. guard index < 4 else { return } ((index + 1) ..< 5).forEach { let star = starLayers[$0] star.strokeColor = Constants.unhighlightedColor star.fillColor = nil } } /// Unhighlights every star. private func clearAll() { (0 ..< 5).forEach { let star = starLayers[$0] star.strokeColor = Constants.unhighlightedColor star.fillColor = nil } } private func clamp(_ index: Int) -> Int { if index < 0 { return 0 } if index >= 5 { return 4 } return index } override var isUserInteractionEnabled: Bool { get { return false } set {} } private static func starLayer() -> CAShapeLayer { let layer = CAShapeLayer() let mutablePath = CGMutablePath() let outerRadius: CGFloat = 9 let outerPoints = stride(from: CGFloat.pi / -5, to: .pi * 2, by: 2 * .pi / 5).map { CGPoint(x: outerRadius * sin($0) + 9, y: outerRadius * cos($0) + 9) } let innerRadius: CGFloat = 4 let innerPoints = stride(from: 0, to: .pi * 2, by: 2 * .pi / 5).map { CGPoint(x: innerRadius * sin($0) + 9, y: innerRadius * cos($0) + 9) } let points = zip(outerPoints, innerPoints) .reduce([CGPoint]()) { (aggregate, pair) -> [CGPoint] in aggregate + [pair.0, pair.1] } mutablePath.move(to: points[0]) points.forEach { mutablePath.addLine(to: $0) } mutablePath.closeSubpath() layer.path = mutablePath.copy() layer.strokeColor = UIColor.gray.cgColor layer.lineWidth = 1 layer.fillColor = nil return layer } @available(*, unavailable) required convenience init?(coder aDecoder: NSCoder) { // coder is ignored. self.init(frame: CGRect(x: 0, y: 0, width: 270, height: 50)) translatesAutoresizingMaskIntoConstraints = false } private enum Constants { static let unhighlightedColor = UIColor.gray.cgColor static let highlightedColorOrange = UIColor( red: 255 / 255, green: 179 / 255, blue: 0 / 255, alpha: 1 ).cgColor } }
f08e867a6aa48ab0ff72e759a68be0e0
26.359116
113
0.633582
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/Foundation/BaseScreen/NavigationRouterAPI.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import Foundation import RxRelay import ToolKit import UIComponentsKit /// Emits a command to return to the previous state public protocol RoutingPreviousStateEmitterAPI: AnyObject { /// Move to the previous state var previousRelay: PublishRelay<Void> { get } } /// Emits a command to move forward to the next state public protocol RoutingNextStateEmitterAPI: AnyObject { /// Move to the next state var nextRelay: PublishRelay<Void> { get } } public protocol NavigationRouterAPI: AnyObject { var navigationControllerAPI: NavigationControllerAPI? { get set } var topMostViewControllerProvider: TopMostViewControllerProviding! { get } func present(viewController: UIViewController, using presentationType: PresentationType) func present(viewController: UIViewController) func dismiss(completion: (() -> Void)?) func dismiss(using presentationType: PresentationType) func dismiss() func pop(animated: Bool) } public enum RoutingType { case modal case embed(inside: NavigationControllerAPI) } public class NavigationRouter: NavigationRouterAPI { public weak var navigationControllerAPI: NavigationControllerAPI? public weak var topMostViewControllerProvider: TopMostViewControllerProviding! public var defaultPresentationType: PresentationType { if navigationControllerAPI != nil { return .navigationFromCurrent } else { return .modalOverTopMost } } public var defaultDismissalType: PresentationType? { guard let navigationControllerAPI = navigationControllerAPI else { return nil } if navigationControllerAPI.viewControllersCount == 1 { return .modalOverTopMost } else { return .navigationFromCurrent } } public init(topMostViewControllerProvider: TopMostViewControllerProviding = resolve()) { self.topMostViewControllerProvider = topMostViewControllerProvider } public func present(viewController: UIViewController) { present(viewController: viewController, using: defaultPresentationType) } private func presentModal(viewController: UIViewController, in parent: ViewControllerAPI) { let navigationController: UINavigationController if let navController = viewController as? UINavigationController { navigationController = navController } else { navigationController = UINavigationController(rootViewController: viewController) } DispatchQueue.main.async { [weak self] in parent.present(navigationController, animated: true, completion: nil) self?.navigationControllerAPI = navigationController } } public func present(viewController: UIViewController, using presentationType: PresentationType) { switch presentationType { case .modal(from: let parentViewController): presentModal(viewController: viewController, in: parentViewController) case .navigation(from: let originViewController): if BuildFlag.isInternal { if originViewController.navigationControllerAPI == nil { // swiftlint:disable line_length fatalError("When presenting a \(type(of: viewController)), originViewController \(type(of: originViewController)), originViewController.navigationControllerAPI was nil.") } } originViewController.navigationControllerAPI?.pushViewController(viewController, animated: true) case .navigationFromCurrent: if BuildFlag.isInternal { if navigationControllerAPI == nil { fatalError("When presenting a \(type(of: viewController)), navigationControllerAPI was nil.") } } navigationControllerAPI?.pushViewController(viewController, animated: true) case .modalOverTopMost: if let parentViewController = topMostViewControllerProvider.topMostViewController { presentModal(viewController: viewController, in: parentViewController) } } } public func dismiss(completion: (() -> Void)?) { navigationControllerAPI?.dismiss(animated: true, completion: completion) } public func dismiss() { dismiss(using: defaultPresentationType) } public func dismiss(using presentationType: PresentationType) { switch presentationType { case .modal, .modalOverTopMost: navigationControllerAPI?.dismiss(animated: true, completion: nil) case .navigation, .navigationFromCurrent: navigationControllerAPI?.popViewController(animated: true) } } public func pop(animated: Bool) { navigationControllerAPI?.popViewController(animated: true) } }
c33933f047e1580606c16bf27700c573
36.839695
190
0.697398
false
false
false
false
Constructor-io/constructorio-client-swift
refs/heads/master
AutocompleteClient/FW/Logic/Result/CIOCollectionData.swift
mit
1
// // CIOCollectionData.swift // Constructor.io // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import Foundation /** Struct encapsulating a collection */ public class CIOCollectionData: NSObject { /** Id of the collection */ public let id: String /** Display name of the collection */ public let display_name: String /** Additional metadata for the collection */ public let data: [String: Any] /** Create a collection object - Parameters: - json: JSON data from server reponse */ init?(json: JSONObject?) { guard let json = json, let id = json["id"] as? String, let display_name = json["display_name"] as? String else { return nil } let data = json["data"] as? [String: Any] ?? [:] self.id = id self.display_name = display_name self.data = data } }
5a7688358a95aa541c8222730ea52b28
19.717391
120
0.579224
false
false
false
false
ReduxKit/ReduxKit
refs/heads/master
ReduxKitPlayground.playground/Pages/Custom store creator.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import ReduxKit // ---------------------------------------------------------------------------- // // MARK: - Setup struct AppState { var count: Int! } struct CountAction: Action { let payload: Int init(_ payload: Int = 1) { self.payload = payload } } func reducer(state: AppState? = nil, action: Action) -> AppState { switch action { case let action as CountAction: return AppState(count: (state?.count ?? 0) + action.payload) default: return state ?? AppState(count: 0) } } // ---------------------------------------------------------------------------- // // MARK: - Store creator func createBasicStore<State>(reducer: (State?, Action) -> State, state: State?) -> Store<State> { typealias Subscriber = State -> () var currentState = state ?? reducer(state, DefaultAction()) var nextToken = 0 var subscribers = [Int: Subscriber]() let dispatch: (Action) -> Action = { action in currentState = reducer(currentState, action) subscribers.map { $1(currentState) } return action } let disposable: (Int) -> ReduxDisposable = { token in SimpleReduxDisposable( disposed: { subscribers[token] != nil }, dispose: { subscribers.removeValueForKey(token) }) } let subscribe: (State -> ()) -> ReduxDisposable = { subscriber in let token = nextToken nextToken += 1 subscribers[token] = subscriber return disposable(token) } return Store(dispatch: dispatch, subscribe: subscribe, getState: { currentState }) } let store = createBasicStore(reducer, state: nil) // ---------------------------------------------------------------------------- // // MARK: - Test let dump: () -> String = { "\(store.state)" } let count: () -> () = { store.dispatch(CountAction()) } let countAndDump: () -> String = { _ in count() return dump() } // ---------------------------------------------------------------------------- dump() // -> AppState(count: 0) countAndDump() // -> AppState(count: 1) countAndDump() // -> AppState(count: 2) //: [Next](@next)
54dba8c9aed6e19c37be4204f36a9812
23.727273
97
0.514706
false
false
false
false
mathiasquintero/Pushie
refs/heads/master
Pushie/Classes/State.swift
mit
1
// // State.swift // PDA // // Created by Mathias Quintero on 7/8/16. // Copyright © 2016 Mathias Quintero. All rights reserved. // import Foundation /// State in PDA public class State<T> { let final: Bool var transitions: [StackElement:TransitionManager<T>] var id: String { get { return String(ObjectIdentifier(self).uintValue) } } private init(transitions: [StackElement:TransitionManager<T>] = [:], final: Bool = false) { self.transitions = transitions self.final = final } /** Will instantiate a PDA-State - Parameters: - final: is it a final State (Optional) - Returns: A beautiful PDA. Ready for calculation. */ public init(final: Bool = false) { self.transitions = [:] self.final = final } func handleInput(input: String, stack: Stack, accumulator: Accumulator<T>) -> T? { if input.isEmpty && final { return accumulator.accumulatedObject } if let element = stack.last, transitionsForState = transitions[element]?.dict { let nextOptions = transitionsForState.filter() { (reason, transition) in switch reason { case .Regex(let str): let range = input.rangeOfString(str, options: .RegularExpressionSearch) if let index = range?.startIndex { return index == input.startIndex } return false default: return true } } for option in nextOptions { switch option.0 { case .Regex(let expr): let ranges = input.matchesForRegexAtStart(for: expr) for range in ranges { let text = input.stringByReplacingCharactersInRange(input.rangeFromNSRange(range)!, withString: "") let copy = accumulator.copy() copy.append(input.substringWithRange(input.rangeFromNSRange(range)!)) let newStack = stack.copy() let state = option.1.handle(newStack, accumulator: copy) ?? self if let result = state.handleInput(text, stack: newStack, accumulator: copy) { return result } } default: let copy = accumulator.copy() let newStack = stack.copy() let state = option.1.handle(newStack, accumulator: copy) ?? self if let result = state.handleInput(input, stack: newStack, accumulator: copy) { return result } } } } return nil } /** Will create a new Transition for a specific Stack Element - Parameters: - element: Stack Element as String - Returns: A Transition Manager to keep editing the transition. */ public func when(element: String) -> TransitionMaker<T> { let stackElement = StackElement(identifier: element) return when(stackElement) } /** Will create a new Transition for a specific Stack Element - Parameters: - element: Stack Element - Returns: A Transition Manager to keep editing the transition. */ public func when(element: StackElement) -> TransitionMaker<T> { let dict = transitions[element] ?? TransitionManager() transitions[element] = dict return TransitionMaker(state: self, manager: dict) } }
1e2ae7c9fff305ed8172aa591e5e1309
32.168142
123
0.53803
false
false
false
false
tilltue/FSCalendar
refs/heads/custom
Example-Swift/SwiftExample/LoadViewExampleViewController.swift
mit
1
// // LoadViewExampleViewController.swift // SwiftExample // // Created by dingwenchao on 10/17/16. // Copyright © 2016 wenchao. All rights reserved. // import UIKit class LoadViewExampleViewController: UIViewController, FSCalendarDataSource, FSCalendarDelegate { private weak var calendar: FSCalendar! override func loadView() { let view = UIView(frame: UIScreen.main.bounds) view.backgroundColor = UIColor.groupTableViewBackground self.view = view let calendar = FSCalendar(frame: CGRect(x: 0, y: self.navigationController!.navigationBar.frame.maxY, width: self.view.bounds.width, height: 300)) calendar.dataSource = self calendar.delegate = self calendar.backgroundColor = UIColor.white calendar.scopeGesture.isEnabled = true self.view.addSubview(calendar) self.calendar = calendar } override func viewDidLoad() { super.viewDidLoad() self.title = "FSCalendar" } // Update your frame func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) { calendar.frame = CGRect(x: 0, y: self.navigationController!.navigationBar.frame.maxY, width: bounds.width, height: bounds.height) } }
8b7c352a1d4b30f1d2d52aa8200f60d0
30.731707
154
0.677171
false
false
false
false
shahmishal/swift
refs/heads/master
test/attr/require_explicit_availability.swift
apache-2.0
2
// RUN: %swift -typecheck -parse-stdlib -target x86_64-apple-macosx10.10 -verify -require-explicit-availability -require-explicit-availability-target "macOS 10.10" %s // RUN: %swift -typecheck -parse-stdlib -target x86_64-apple-macosx10.10 -warnings-as-errors %s public struct S { // expected-warning {{public declarations should have an availability attribute with -require-explicit-availability}} public func method() { } } public func foo() { bar() } // expected-warning {{public declarations should have an availability attribute with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @usableFromInline func bar() { } // expected-warning {{public declarations should have an availability attribute with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.1, *) public func ok() { } @available(macOS, deprecated: 10.10) public func missingIntro() { } // expected-warning {{public declarations should have an availability attribute with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} func privateFunc() { } @_alwaysEmitIntoClient public func alwaysEmitted() { } @available(macOS 10.1, *) struct SOk { public func okMethod() { } } precedencegroup MediumPrecedence {} infix operator + : MediumPrecedence public func +(lhs: S, rhs: S) -> S { } // expected-warning {{public declarations should have an availability attribute with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public enum E { } // expected-warning {{public declarations should have an availability attribute with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public class C { } // expected-warning {{public declarations should have an availability attribute with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public protocol P { } // expected-warning {{public declarations should have an availability attribute with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} extension S { // expected-warning {{public declarations should have an availability attribute with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} func ok() { } } open class OpenClass { } // expected-warning {{public declarations should have an availability attribute with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} private class PrivateClass { } extension PrivateClass { }
744bdb0a8a882efb73b187129bd24787
50.041667
193
0.736735
false
false
false
false
VDKA/VKBanner
refs/heads/master
Pods/EZSwiftExtensions/Sources/IntExtentions.swift
mit
1
// // IntExtentions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 16/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit extension Int { /// EZSwiftExtensions public var isEven: Bool { return (self % 2 == 0) } /// EZSwiftExtensions public var isOdd: Bool { return (self % 2 != 0) } /// EZSwiftExtensions public var isPositive: Bool { return (self >= 0) } /// EZSwiftExtensions public var isNegative: Bool { return (self < 0) } /// EZSwiftExtensions public var toDouble: Double { return Double(self) } /// EZSwiftExtensions public var toFloat: Float { return Float(self) } /// EZSwiftExtensions public var toCGFloat: CGFloat { return CGFloat(self) } /// EZSwiftExtensions public var toString: String { return String(self) } /// EZSwiftExtensions public var digits: Int { if self == 0 { return 1 } else if Int(fabs(Double(self))) <= LONG_MAX { return Int(log10(fabs(Double(self)))) + 1 } else { return -1; //out of bound } } /// EZSwiftExtensions - Execute action this many times public func times(action: () -> ()) { if self > 0 { for _ in 0..<self { action() } } } } extension UInt { /// EZSwiftExtensions public var toInt: Int { return Int(self) } }
95693f28f9583cc5b46e1950e0ce3a3d
24.821429
58
0.571923
false
false
false
false
Yvent/QQMusic
refs/heads/master
QQMusic/QQMusic/MineHeadImageCell.swift
mit
1
// // MineHeadImageCell.swift // QQMusic // // Created by 周逸文 on 17/2/16. // Copyright © 2017年 Devil. All rights reserved. // import UIKit class MineHeadImageCell: UITableViewCell ,UICollectionViewDelegate, UICollectionViewDataSource { var headimagebtn: UIButton! var mintuesbtn: UIButton! var becomevipbtn: UIButton! var namelabel: UILabel! var tovipbtn: UIButton! var contentV: UICollectionView! let headheight: CGFloat = 56 var iconnames = ["mymusic_icon_allsongs_normal","mymusic_icon_download_normal","mymusic_icon_history_normal","mymusic_icon_favorite_normal","mymusic_icon_mv_normal","mymusic_icon_paidmusic_normal"] var titles = ["全部歌曲","下载歌曲","最近播放","我喜欢","下载MV","已购音乐"] override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initUI() { headimagebtn = UIButton( nn: "",rd: headheight/2) mintuesbtn = UIButton(yv_nt: "0分钟", ntc: UIColor.black, nn: "", ts: 14, rd: headheight/4, bc: UIColor.white, bdc: RGBSingle(217).cgColor, bdw: 1) becomevipbtn = UIButton(yv_nt: "开通", ntc: UIColor.black, nn: "", ts: 14, rd: headheight/4, bc: UIColor.white, bdc: RGBSingle(217).cgColor, bdw: 1) namelabel = UILabel(yv_lt: "— Devil —", ltc: UIColor.black, ts: 18, alg: .center) tovipbtn = UIButton( nn: "") addSubviews([headimagebtn,mintuesbtn,becomevipbtn,namelabel,tovipbtn]) headimagebtn.snp.makeConstraints { (make) in make.width.height.equalTo(headheight) make.centerX.equalTo(self) make.top.equalTo(self).offset(16) } mintuesbtn.snp.makeConstraints { (make) in make.width.equalTo(71) make.height.equalTo(headheight/2) make.centerY.equalTo(headimagebtn) make.right.equalTo(headimagebtn.snp.left).offset(-40) } becomevipbtn.snp.makeConstraints { (make) in make.width.height.centerY.equalTo(mintuesbtn) make.left.equalTo(headimagebtn.snp.right).offset(40) } namelabel.snp.makeConstraints { (make) in make.width.equalTo(120) make.height.equalTo(25) make.centerX.equalTo(headimagebtn) make.top.equalTo(headimagebtn.snp.bottom).offset(5) } tovipbtn.snp.makeConstraints { (make) in make.width.height.equalTo(25) make.centerX.equalTo(headimagebtn) make.top.equalTo(namelabel.snp.bottom) } let layout = UICollectionViewFlowLayout(sd: .vertical,mls: 0, mis: 0, ise: CGSize(width: ScreenWidth/3, height: MinePlayerFuncCellHeight/2)) contentV = UICollectionView(yv_bc: UIColor.white, any: self,layout: layout) contentView.addSubview(contentV) contentV.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(contentView) make.height.equalTo(MinePlayerFuncCellHeight) } contentV.register(MinePlayerFuncSubCell.self, forCellWithReuseIdentifier: "MinePlayerFuncSubCell") } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 6 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MinePlayerFuncSubCell", for: indexPath) as! MinePlayerFuncSubCell cell.imagev.image = UIImage(named: iconnames[indexPath.row]) cell.title.text = titles[indexPath.row] cell.subtitle.text = "78" return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } } class MinePlayerFuncSubCell: UICollectionViewCell { var imagev: UIImageView! var title: UILabel! var subtitle: UILabel! override init(frame: CGRect) { super.init(frame: frame) initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initUI() { imagev = UIImageView() title = UILabel( ltc: UIColor.black, ts: 16, alg: .center) subtitle = UILabel( ltc: UIColor.black, ts: 12, alg: .center) contentView.addSubviews([imagev,title,subtitle]) imagev.snp.makeConstraints { (make) in make.width.height.equalTo(45) make.centerX.equalTo(contentView) make.top.equalTo(contentView).offset(5) } title.snp.makeConstraints { (make) in make.centerX.equalTo(imagev) make.top.equalTo(imagev.snp.bottom).offset(5) } subtitle.snp.makeConstraints { (make) in make.centerX.equalTo(imagev) make.top.equalTo(title.snp.bottom) } } } let MineRadioCellHeight: CGFloat = 65 class MineRadioCell: UITableViewCell{ var imagev: UIImageView! var title: UILabel! var subtitle: UILabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initUI() { imagev = UIImageView(image: UIImage(named: "7B9F2B84-052E-4575-9EEE-80892FCECB24")) title = UILabel( ltc: UIColor.black, ts: 16, alg: .center) subtitle = UILabel( ltc: RGBSingle(112), ts: 12, alg: .center) contentView.addSubviews([imagev,title,subtitle]) imagev.snp.makeConstraints { (make) in make.width.height.equalTo(MineRadioCellHeight) make.left.centerY.equalTo(contentView) } title.snp.makeConstraints { (make) in make.left.equalTo(imagev.snp.right).offset(10) make.bottom.equalTo(imagev.snp.centerY) } subtitle.snp.makeConstraints { (make) in make.left.equalTo(title) make.top.equalTo(imagev.snp.centerY) } } }
3cce1cca1ce493b7f6b59fd4d0a946aa
34.621622
201
0.635357
false
false
false
false
cemolcay/MotionImageView
refs/heads/master
MotionImageView/MotionImageView.swift
mit
1
// // MotionImageView.swift // MotionImageView // // Created by Cem Olcay on 03/03/15. // Copyright (c) 2015 Cem Olcay. All rights reserved. // import UIKit import CoreMotion extension UIView { var x: CGFloat { get { return self.frame.origin.x } set (value) { self.frame = CGRect (x: value, y: self.y, width: self.w, height: self.h) } } var y: CGFloat { get { return self.frame.origin.y } set (value) { self.frame = CGRect (x: self.x, y: value, width: self.w, height: self.h) } } var w: CGFloat { get { return self.frame.size.width } set (value) { self.frame = CGRect (x: self.x, y: self.y, width: value, height: self.h) } } var h: CGFloat { get { return self.frame.size.height } set (value) { self.frame = CGRect (x: self.x, y: self.y, width: self.w, height: value) } } } class MotionImageView: UIView { private let motionManager = CMMotionManager() private var imageView: UIImageView! private var horizontalDiff: CGFloat = 0 private var verticalDiff: CGFloat = 0 var horizontalMultiplier: Double = 2 var verticalMultiplier: Double = 4 init (frame: CGRect, image: UIImage) { super.init(frame: frame) clipsToBounds = true imageView = UIImageView (image: image) imageView.center = center addSubview(imageView) horizontalDiff = (imageView.w - w)/2 verticalDiff = (imageView.h - h)/2 motionManager.gyroUpdateInterval = 1.0 / 60.0 motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:{ [unowned self] deviceManager, error in let att = deviceManager.attitude let roll = CGFloat (min (1, max(att.roll * horizontalMultiplier, -1))) let pitch = CGFloat (min (1, max(att.pitch * verticalMultiplier, -1))) self.moveImage(roll, vertical: pitch) }) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func moveImage (horizontal: CGFloat, vertical: CGFloat) { imageView.center.x = w/2 + horizontalDiff * horizontal imageView.center.y = h/2 + verticalDiff * vertical } }
4e6a8731b01049d7326d5e155968461e
26.377778
100
0.568994
false
false
false
false
MAARK/Charts
refs/heads/master
ChartsDemo-iOS/Swift/Demos/BarChartViewController.swift
apache-2.0
2
// // BarChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // import UIKit import Charts class BarChartViewController: DemoBaseViewController { @IBOutlet var chartView: BarChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Bar Chart" self.options = [.toggleValues, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleData, .toggleBarBorders] self.setup(barLineChartView: chartView) chartView.delegate = self chartView.drawBarShadowEnabled = false chartView.drawValueAboveBarEnabled = false chartView.maxVisibleCount = 60 let xAxis = chartView.xAxis xAxis.labelPosition = .bottom xAxis.labelFont = .systemFont(ofSize: 10) xAxis.granularity = 1 xAxis.labelCount = 7 xAxis.valueFormatter = DayAxisValueFormatter(chart: chartView) let leftAxisFormatter = NumberFormatter() leftAxisFormatter.minimumFractionDigits = 0 leftAxisFormatter.maximumFractionDigits = 1 leftAxisFormatter.negativeSuffix = " $" leftAxisFormatter.positiveSuffix = " $" let leftAxis = chartView.leftAxis leftAxis.labelFont = .systemFont(ofSize: 10) leftAxis.labelCount = 8 leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: leftAxisFormatter) leftAxis.labelPosition = .outsideChart leftAxis.spaceTop = 0.15 leftAxis.axisMinimum = 0 // FIXME: HUH?? this replaces startAtZero = YES let rightAxis = chartView.rightAxis rightAxis.enabled = true rightAxis.labelFont = .systemFont(ofSize: 10) rightAxis.labelCount = 8 rightAxis.valueFormatter = leftAxis.valueFormatter rightAxis.spaceTop = 0.15 rightAxis.axisMinimum = 0 let l = chartView.legend l.horizontalAlignment = .left l.verticalAlignment = .bottom l.orientation = .horizontal l.drawInside = false l.form = .circle l.formSize = 9 l.font = UIFont(name: "HelveticaNeue-Light", size: 11)! l.xEntrySpace = 4 // chartView.legend = l let marker = XYMarkerView(color: UIColor(white: 180/250, alpha: 1), font: .systemFont(ofSize: 12), textColor: .white, insets: UIEdgeInsets(top: 8, left: 8, bottom: 20, right: 8), xAxisValueFormatter: chartView.xAxis.valueFormatter!) marker.chartView = chartView marker.minimumSize = CGSize(width: 80, height: 40) chartView.marker = marker sliderX.value = 12 sliderY.value = 50 slidersValueChanged(nil) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value) + 1, range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let start = 1 let yVals = (start..<start+count+1).map { (i) -> BarChartDataEntry in let mult = range + 1 let val = Double(arc4random_uniform(mult)) if arc4random_uniform(100) < 25 { return BarChartDataEntry(x: Double(i), y: val, icon: UIImage(named: "icon")) } else { return BarChartDataEntry(x: Double(i), y: val) } } var set1: BarChartDataSet! = nil if let set = chartView.data?.dataSets.first as? BarChartDataSet { set1 = set set1.replaceEntries(yVals) chartView.data?.notifyDataChanged() chartView.notifyDataSetChanged() } else { set1 = BarChartDataSet(entries: yVals, label: "The year 2017") set1.colors = ChartColorTemplates.material() set1.drawValuesEnabled = false let data = BarChartData(dataSet: set1) data.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 10)!) data.barWidth = 0.9 chartView.data = data } // chartView.setNeedsDisplay() } override func optionTapped(_ option: Option) { super.handleOption(option, forChartView: chartView) } // MARK: - Actions @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value + 2))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } }
286f01d5e0f9ef2c61c83a56d662a4ca
33.394737
94
0.571729
false
false
false
false
FengDeng/RxGitHubAPI
refs/heads/master
RxGitHubAPI/RxGitHubAPI/YYPushCommit.swift
apache-2.0
1
// // YYPushCommit.swift // RxGitHubAPI // // Created by 邓锋 on 16/2/2. // Copyright © 2016年 fengdeng. All rights reserved. // import Foundation public class YYPushCommit : NSObject{ public private(set) var sha = "" public private(set) var author_email = "" public private(set) var author_name = "" public private(set) var message = "" public private(set) var distinct = false //api var url = "" }
c9826bf436bed5704f2a9c8765377f18
20.8
52
0.639908
false
false
false
false
icthus/icthus-ios
refs/heads/master
Icthus/SlideFromLeftPresentationController.swift
mit
1
// // SlideFromLeftPresentationController.swift // // // Created by Matthew Lorentz on 6/21/17. // class SlideFromLeftPresentationController: NSObject, UIViewControllerAnimatedTransitioning { @objc var presenting = true func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.2 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! let finalFrameForVC = transitionContext.finalFrame(for: toViewController) let containerView = transitionContext.containerView let bounds = UIScreen.main.bounds if presenting { toViewController.view.frame = finalFrameForVC.offsetBy(dx: -bounds.size.width, dy: 0) containerView.addSubview(toViewController.view) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { toViewController.view.frame = finalFrameForVC }) { (_) in transitionContext.completeTransition(true) } } else { UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { fromViewController.view.frame = finalFrameForVC.offsetBy(dx: -bounds.size.width, dy: 0) }) { (_) in transitionContext.completeTransition(true) } } } }
a9c98316a37231fe16d610e17ad43e18
41.2
117
0.683057
false
false
false
false
codefellows/pdx-c11-iOS
refs/heads/master
sampleCode/day3/day3_app/myTableView_B/ViewController.swift
mit
1
// // ViewController.swift // myTableView_B // // Created by Al on 7/7/15. // Copyright (c) 2015 Al. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var myTableView: UITableView! var food: [String] = ["Lentils", "Carrots", "Black Rice", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r"] let color_reusedCell: Bool = true override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return food.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = myTableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel!.text = self.food[indexPath.row] if color_reusedCell { println("Dequeued cell #\(indexPath.row)") if indexPath.row == 0 { cell.backgroundColor = UIColor.blueColor() } } return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // What Xcode gives you to start with: class ViewController_old: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 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. } }
d5d83c7b06364c3041a01840f7304b4e
34.375
151
0.65
false
false
false
false
alblue/swift
refs/heads/master
test/SILOptimizer/array_contentof_opt.swift
apache-2.0
12
// RUN: %target-swift-frontend -O -sil-verify-all -emit-sil -enforce-exclusivity=unchecked %s | %FileCheck %s // REQUIRES: swift_stdlib_no_asserts,optimized_stdlib // This is an end-to-end test of the array(contentsOf) -> array(Element) optimization // CHECK-LABEL: sil @{{.*}}testInt // CHECK-NOT: apply // CHECK: [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSi_Tg5 // CHECK-NOT: apply // CHECK: apply [[F]] // CHECK-NEXT: tuple // CHECK-NEXT: return public func testInt(_ a: inout [Int]) { a += [1] } // CHECK-LABEL: sil @{{.*}}testThreeInt // CHECK-NOT: apply // CHECK: [[FR:%[0-9]+]] = function_ref @$sSa15reserveCapacityyySiFSi_Tg5 // CHECK-NEXT: apply [[FR]] // CHECK-NOT: apply // CHECK: [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSi_Tg5 // CHECK-NOT: apply // CHECK: apply [[F]] // CHECK-NEXT: apply [[F]] // CHECK-NEXT: apply [[F]] // CHECK-NEXT: tuple // CHECK-NEXT: return public func testThreeInts(_ a: inout [Int]) { a += [1, 2, 3] } // CHECK-LABEL: sil @{{.*}}testTooManyInts // CHECK-NOT: apply // CHECK: [[F:%[0-9]+]] = function_ref @$sSa6append10contentsOfyqd__n_t7ElementQyd__RszSTRd__lFSi_SaySiGTg5Tf4gn_n // CHECK-NOT: apply // CHECK: apply [[F]] // CHECK-NOT: apply // CHECK: return public func testTooManyInts(_ a: inout [Int]) { a += [1, 2, 3, 4, 5, 6, 7] } // CHECK-LABEL: sil @{{.*}}testString // CHECK-NOT: apply // CHECK: [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSS_Tg5 // CHECK-NOT: apply // CHECK: apply [[F]] // CHECK-NOT: apply // CHECK: tuple // CHECK-NEXT: return public func testString(_ a: inout [String], s: String) { a += [s] } // This is not supported yet. Just check that we don't crash on this.` public func dontPropagateContiguousArray(_ a: inout ContiguousArray<UInt8>) { a += [4] }
8c3ba12a66f4f0393982ba3fcd46f607
30.271186
122
0.609214
false
true
false
false
krevi27/TestExerciseProject
refs/heads/master
TestStudyExercise/Cotacao.swift
mit
1
// // Cotacao.swift // WatchOSComplicationSample // // Created by Marcos Fellipe Costa Silva on 19/09/17. // Copyright © 2017 BEPiD. All rights reserved. // import Foundation class Cotacao{ func getDolar(){ var retorno = "" let url = URL(string: "http://api.promasters.net.br/cotacao/v1/valores?moedas=USD&alt=json") URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in guard let data = data, error == nil else { return } do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any] let dados = json["valores"] as! [String: Any] let moeda = dados["USD"] as! [String: Any] let valor = moeda["valor"] retorno = valor! as! String } catch let error as NSError { print(error) } }).resume() } func getBTC(){ var retorno = "" let url = URL(string: "http://api.promasters.net.br/cotacao/v1/valores?moedas=BTC&alt=json") URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in guard let data = data, error == nil else { return } do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any] let dados = json["valores"] as! [String: Any] let moeda = dados["BTC"] as! [String: Any] let valor = moeda["valor"] } catch let error as NSError { print(error) } }).resume() } }
efcfcfa56f3975be1d34146185ab4908
32.307692
114
0.534642
false
false
false
false
rudkx/swift
refs/heads/main
validation-test/Sema/type_checker_crashers_fixed/rdar28235248.swift
apache-2.0
1
// RUN: not %target-swift-frontend %s -typecheck -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=verify -debug-generic-signatures 2>&1 | %FileCheck %s protocol II { associatedtype E } protocol P { associatedtype I : II associatedtype X } // CHECK-LABEL: ExtensionDecl line={{.*}} base=P // CHECK-NEXT: Generic signature: <Self where Self : P, Self.[P]I.[II]E : P, Self.[P]I.[II]E.[P]X == Int> extension P where I.E : P, I.E.X.D == Int, I.E.X == Int {}
9ba7410723dfacb682cd584286bb7e2d
34.857143
191
0.687251
false
false
false
false
rsyncOSX/RsyncOSX
refs/heads/master
RsyncOSX/ViewControllerExtensions.swift
mit
1
// // ViewControllerExtensions.swift // RsyncOSX // // Created by Thomas Evensen on 28.10.2017. // Copyright © 2017 Thomas Evensen. All rights reserved. // import Cocoa import Foundation protocol VcMain { var storyboard: NSStoryboard? { get } } extension VcMain { var storyboard: NSStoryboard? { return NSStoryboard(name: "Main", bundle: nil) } var sheetviewstoryboard: NSStoryboard? { return NSStoryboard(name: "SheetViews", bundle: nil) } // StoryboardOutputID var viewControllerAllOutput: NSViewController? { return (storyboard?.instantiateController(withIdentifier: "StoryboardOutputID") as? NSViewController) } // Sheetviews // Userconfiguration var viewControllerUserconfiguration: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardUserconfigID") as? NSViewController) } // Information about rsync output var viewControllerInformation: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardInformationID") as? NSViewController) } // AssistID var viewControllerAssist: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "AssistID") as? NSViewController) } // Profile var viewControllerProfile: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "ProfileID") as? NSViewController) } // About var viewControllerAbout: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "AboutID") as? NSViewController) } // Remote Info var viewControllerRemoteInfo: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardRemoteInfoID") as? NSViewController) } // Quick backup process var viewControllerQuickBackup: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardQuickBackupID") as? NSViewController) } // local and remote info var viewControllerInformationLocalRemote: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardLocalRemoteID") as? NSViewController) } // Estimating var viewControllerEstimating: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardEstimatingID") as? NSViewController) } // Progressbar process var viewControllerProgress: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardProgressID") as? NSViewController) } // Rsync userparams var viewControllerRsyncParams: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardRsyncParamsID") as? NSViewController) } // Edit var editViewController: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardEditID") as? NSViewController) } // RsyncCommand var rsynccommand: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "RsyncCommand") as? NSViewController) } // Schedules view var schedulesview: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "ViewControllertabSchedule") as? NSViewController) } // Add task var addtaskViewController: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "AddTaskID") as? NSViewController) } } // Protocol for dismissing a viewcontroller protocol DismissViewController: AnyObject { func dismiss_view(viewcontroller: NSViewController) } protocol SetDismisser { func dismissview(viewcontroller: NSViewController, vcontroller: ViewController) } extension SetDismisser { var dismissDelegateMain: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain } var dismissDelegateSchedule: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vcschedule) as? ViewControllerSchedule } var dismissDelegateCopyFiles: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vcrestore) as? ViewControllerRestore } var dimissDelegateSnapshot: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vcsnapshot) as? ViewControllerSnapshots } var dismissDelegateLoggData: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vcloggdata) as? ViewControllerLoggData } var dismissDelegateSsh: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vcssh) as? ViewControllerSsh } func dismissview(viewcontroller _: NSViewController, vcontroller: ViewController) { if vcontroller == .vctabmain { dismissDelegateMain?.dismiss_view(viewcontroller: (self as? NSViewController)!) } else if vcontroller == .vcschedule { dismissDelegateSchedule?.dismiss_view(viewcontroller: (self as? NSViewController)!) } else if vcontroller == .vcrestore { dismissDelegateCopyFiles?.dismiss_view(viewcontroller: (self as? NSViewController)!) } else if vcontroller == .vcsnapshot { dimissDelegateSnapshot?.dismiss_view(viewcontroller: (self as? NSViewController)!) } else if vcontroller == .vcloggdata { dismissDelegateLoggData?.dismiss_view(viewcontroller: (self as? NSViewController)!) } else if vcontroller == .vcssh { dismissDelegateSsh?.dismiss_view(viewcontroller: (self as? NSViewController)!) } } } // Protocol for deselecting rowtable protocol DeselectRowTable: AnyObject { func deselect() } protocol Deselect { var deselectDelegateMain: DeselectRowTable? { get } var deselectDelegateSchedule: DeselectRowTable? { get } } extension Deselect { var deselectDelegateMain: DeselectRowTable? { return SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain } var deselectDelegateSchedule: DeselectRowTable? { return SharedReference.shared.getvcref(viewcontroller: .vcschedule) as? ViewControllerSchedule } func deselectrowtable(vcontroller: ViewController) { if vcontroller == .vctabmain { deselectDelegateMain?.deselect() } else { deselectDelegateSchedule?.deselect() } } } protocol Index { func index() -> Int? } extension Index { func index() -> Int? { weak var getindexDelegate: GetSelecetedIndex? getindexDelegate = SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain return getindexDelegate?.getindex() } } protocol Delay { func delayWithSeconds(_ seconds: Double, completion: @escaping () -> Void) } extension Delay { func delayWithSeconds(_ seconds: Double, completion: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { completion() } } } protocol Connected { func connected(config: Configuration?) -> Bool func connected(server: String?) -> Bool } extension Connected { func connected(config: Configuration?) -> Bool { var port = 22 if let config = config { if config.offsiteServer.isEmpty == false { if let sshport: Int = config.sshport { port = sshport } let success = TCPconnections().verifyTCPconnection(config.offsiteServer, port: port, timeout: 1) return success } else { return true } } return false } func connected(server: String?) -> Bool { if let server = server { let port = 22 if server.isEmpty == false { let success = TCPconnections().verifyTCPconnection(server, port: port, timeout: 1) return success } else { return true } } return false } } protocol Abort { func abort() } extension Abort { func abort() { let view = SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain view?.abortOperations() } } protocol Help { func help() } extension Help { func help() { NSWorkspace.shared.open(URL(string: "https://rsyncosx.netlify.app/post/rsyncosxdocs/")!) } } protocol GetOutput: AnyObject { func getoutput() -> [String] } protocol OutPut { var informationDelegateMain: GetOutput? { get } } extension OutPut { var informationDelegateMain: GetOutput? { return SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain } func getinfo() -> [String] { return (informationDelegateMain?.getoutput()) ?? [""] } } protocol RsyncIsChanged: AnyObject { func rsyncischanged() } protocol NewRsync { func newrsync() } extension NewRsync { func newrsync() { let view = SharedReference.shared.getvcref(viewcontroller: .vcsidebar) as? ViewControllerSideBar view?.rsyncischanged() } } protocol TemporaryRestorePath { func temporaryrestorepath() } protocol ChangeTemporaryRestorePath { func changetemporaryrestorepath() } extension ChangeTemporaryRestorePath { func changetemporaryrestorepath() { let view = SharedReference.shared.getvcref(viewcontroller: .vcrestore) as? ViewControllerRestore view?.temporaryrestorepath() } } extension Sequence { func sorted<T: Comparable>( by keyPath: KeyPath<Element, T>, using comparator: (T, T) -> Bool = (<) ) -> [Element] { sorted { a, b in comparator(a[keyPath: keyPath], b[keyPath: keyPath]) } } }
3fb4d25300f24a19d6bfa101108db91e
29.372781
112
0.683226
false
false
false
false
solinor/paymenthighway-ios-framework
refs/heads/master
PaymentHighway/UIColor+Extensions.swift
mit
1
// // Extensions.swift // PaymentHighway // // Copyright (c) 2018 Payment Highway Oy. All rights reserved. // import Foundation // MARK: Colors extension UIColor { /// Convenience method for initializing with 0-255 color values /// - parameter red: The red color value /// - parameter green: The green color value /// - parameter blue: The blue color value /// - parameter alpha: The alpha value public convenience init(red: Int, green: Int, blue: Int, alpha: Int = 255) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") assert(alpha >= 0 && alpha <= 255, "Invalid alpha component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha) / 255.0) } /// Convenience method for initializing with a 0xFFFFFF-0x000000 color value /// - parameter hexInt: The hexadecimal integer color value public convenience init(hexInt: Int) { self.init(red: (hexInt >> 16) & 0xff, green: (hexInt >> 8) & 0xff, blue: hexInt & 0xff) } }
af422005433775d2106563636befba9e
38.16129
135
0.635914
false
false
false
false
WeMadeCode/ZXPageView
refs/heads/master
Example/Pods/SwifterSwift/Sources/SwifterSwift/UIKit/UITableViewExtensions.swift
mit
1
// // UITableViewExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/22/16. // Copyright © 2016 SwifterSwift // #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Properties public extension UITableView { /// SwifterSwift: Index path of last row in tableView. var indexPathForLastRow: IndexPath? { return indexPathForLastRow(inSection: lastSection) } /// SwifterSwift: Index of last section in tableView. var lastSection: Int { return numberOfSections > 0 ? numberOfSections - 1 : 0 } } // MARK: - Methods public extension UITableView { /// SwifterSwift: Number of all rows in all sections of tableView. /// /// - Returns: The count of all rows in the tableView. func numberOfRows() -> Int { var section = 0 var rowCount = 0 while section < numberOfSections { rowCount += numberOfRows(inSection: section) section += 1 } return rowCount } /// SwifterSwift: IndexPath for last row in section. /// /// - Parameter section: section to get last row in. /// - Returns: optional last indexPath for last row in section (if applicable). func indexPathForLastRow(inSection section: Int) -> IndexPath? { guard section >= 0 else { return nil } guard numberOfRows(inSection: section) > 0 else { return IndexPath(row: 0, section: section) } return IndexPath(row: numberOfRows(inSection: section) - 1, section: section) } /// Reload data with a completion handler. /// /// - Parameter completion: completion handler to run after reloadData finishes. func reloadData(_ completion: @escaping () -> Void) { UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() }) } /// SwifterSwift: Remove TableFooterView. func removeTableFooterView() { tableFooterView = nil } /// SwifterSwift: Remove TableHeaderView. func removeTableHeaderView() { tableHeaderView = nil } /// SwifterSwift: Scroll to bottom of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). func scrollToBottom(animated: Bool = true) { let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height) setContentOffset(bottomOffset, animated: animated) } /// SwifterSwift: Scroll to top of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). func scrollToTop(animated: Bool = true) { setContentOffset(CGPoint.zero, animated: animated) } /// SwifterSwift: Dequeue reusable UITableViewCell using class name /// /// - Parameter name: UITableViewCell type /// - Returns: UITableViewCell object with associated class name. func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: name)) as? T else { fatalError("Couldn't find UITableViewCell for \(String(describing: name)), make sure the cell is registered with table view") } return cell } /// SwifterSwift: Dequeue reusable UITableViewCell using class name for indexPath /// /// - Parameters: /// - name: UITableViewCell type. /// - indexPath: location of cell in tableView. /// - Returns: UITableViewCell object with associated class name. func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: name), for: indexPath) as? T else { fatalError("Couldn't find UITableViewCell for \(String(describing: name)), make sure the cell is registered with table view") } return cell } /// SwifterSwift: Dequeue reusable UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type /// - Returns: UITableViewHeaderFooterView object with associated class name. func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withClass name: T.Type) -> T { guard let headerFooterView = dequeueReusableHeaderFooterView(withIdentifier: String(describing: name)) as? T else { fatalError("Couldn't find UITableViewHeaderFooterView for \(String(describing: name)), make sure the view is registered with table view") } return headerFooterView } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameters: /// - nib: Nib file used to create the header or footer view. /// - name: UITableViewHeaderFooterView type. func register<T: UITableViewHeaderFooterView>(nib: UINib?, withHeaderFooterViewClass name: T.Type) { register(nib, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type func register<T: UITableViewHeaderFooterView>(headerFooterViewClassWith name: T.Type) { register(T.self, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameter name: UITableViewCell type func register<T: UITableViewCell>(cellWithClass name: T.Type) { register(T.self, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameters: /// - nib: Nib file used to create the tableView cell. /// - name: UITableViewCell type. func register<T: UITableViewCell>(nib: UINib?, withCellClass name: T.Type) { register(nib, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell with .xib file using only its corresponding class. /// Assumes that the .xib filename and cell class has the same name. /// /// - Parameters: /// - name: UITableViewCell type. /// - bundleClass: Class in which the Bundle instance will be based on. func register<T: UITableViewCell>(nibWithCellClass name: T.Type, at bundleClass: AnyClass? = nil) { let identifier = String(describing: name) var bundle: Bundle? if let bundleName = bundleClass { bundle = Bundle(for: bundleName) } register(UINib(nibName: identifier, bundle: bundle), forCellReuseIdentifier: identifier) } /// SwifterSwift: Check whether IndexPath is valid within the tableView /// /// - Parameter indexPath: An IndexPath to check /// - Returns: Boolean value for valid or invalid IndexPath func isValidIndexPath(_ indexPath: IndexPath) -> Bool { return indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section) } /// SwifterSwift: Safely scroll to possibly invalid IndexPath /// /// - Parameters: /// - indexPath: Target IndexPath to scroll to /// - scrollPosition: Scroll position /// - animated: Whether to animate or not func safeScrollToRow(at indexPath: IndexPath, at scrollPosition: UITableView.ScrollPosition, animated: Bool) { guard indexPath.section < numberOfSections else { return } guard indexPath.row < numberOfRows(inSection: indexPath.section) else { return } scrollToRow(at: indexPath, at: scrollPosition, animated: animated) } } #endif
c2827d68a28c3ad64c18d30abe8b5114
37.984772
149
0.670052
false
false
false
false
cristianames92/PortalView
refs/heads/master
Sources/Components/Label.swift
mit
2
// // Label.swift // PortalView // // Created by Guido Marucci Blas on 1/27/17. // // import Foundation public struct LabelProperties { public let text: String public let textAfterLayout: String? fileprivate init(text: String, textAfterLayout: String?) { self.text = text self.textAfterLayout = textAfterLayout } } public func label<MessageType>( text: String = "", style: StyleSheet<LabelStyleSheet> = LabelStyleSheet.`default`, layout: Layout = layout()) -> Component<MessageType> { return .label(properties(text: text), style, layout) } public func label<MessageType>( properties: LabelProperties = properties(), style: StyleSheet<LabelStyleSheet> = LabelStyleSheet.`default`, layout: Layout = layout()) -> Component<MessageType> { return .label(properties, style, layout) } public func properties(text: String = "", textAfterLayout: String? = .none) -> LabelProperties { return LabelProperties(text: text, textAfterLayout: textAfterLayout) } // MARK: - Style sheet public struct LabelStyleSheet { static let `default` = StyleSheet<LabelStyleSheet>(component: LabelStyleSheet()) public var textColor: Color public var textFont: Font public var textSize: UInt public var textAligment: TextAligment public var adjustToFitWidth: Bool public var numberOfLines: UInt public var minimumScaleFactor: Float public init( textColor: Color = .black, textFont: Font = defaultFont, textSize: UInt = defaultButtonFontSize, textAligment: TextAligment = .natural, adjustToFitWidth: Bool = false, numberOfLines: UInt = 0, minimumScaleFactor: Float = 0) { self.textColor = textColor self.textFont = textFont self.textSize = textSize self.textAligment = textAligment self.adjustToFitWidth = adjustToFitWidth self.numberOfLines = numberOfLines self.minimumScaleFactor = minimumScaleFactor } } public func labelStyleSheet(configure: (inout BaseStyleSheet, inout LabelStyleSheet) -> () = { _ in }) -> StyleSheet<LabelStyleSheet> { var base = BaseStyleSheet() var component = LabelStyleSheet() configure(&base, &component) return StyleSheet(component: component, base: base) }
c3c16c9284ed382b65dc9472a10af99a
28.607595
135
0.682343
false
false
false
false
sunkanmi-akintoye/todayjournal
refs/heads/master
weather-journal/Models/Post.swift
mit
1
// // Post.swift // weather-journal // // Created by Luke Geiger on 6/29/15. // Copyright (c) 2015 Luke J Geiger. All rights reserved. // import UIKit class Post: PFObject,PFSubclassing { /** The post's text. */ @NSManaged var text: String /** The temperature of the current location of the post. */ @NSManaged var temperatureF: String /** The weather of the post, Cloudy, Sunny, etc. */ @NSManaged var weather: String /** The date first created. */ @NSManaged var creationDate: NSDate /** Who made this? */ @NSManaged var createdBy: PFUser override class func initialize() { struct Static { static var onceToken : dispatch_once_t = 0; } dispatch_once(&Static.onceToken) { self.registerSubclass() } } static func parseClassName() -> String { return "Post" } /** The Display Title of the post which accounts for the date it was created */ func displayTitle()-> String{ var dateFormatter:NSDateFormatter = NSDateFormatter() var string = String() dateFormatter.dateFormat = "EEEE" var dayOfWeek = dateFormatter .stringFromDate(self.creationDate) string += dayOfWeek string += ", " dateFormatter.dateFormat = "MMMM" var month = dateFormatter .stringFromDate(self.creationDate) string += month string += " " dateFormatter.dateFormat = "dd" var dayOfMonth = dateFormatter .stringFromDate(self.creationDate) string += dayOfMonth return string } /** The day of the month in numeric form this post was created. */ func dayOfMonthString()-> String{ var dateFormatter:NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd" return dateFormatter .stringFromDate(self.creationDate) } /** A combined string of the degrees and weather. */ func weatherDisplayString()->NSString{ var string = String() string += self.temperatureF string += " degrees" string += "\n" string += self.weather return string } }
d4c437e54ab886fc70acb2e0da2e6fca
21.542857
76
0.565695
false
false
false
false
wangyuanou/Coastline
refs/heads/master
Coastline/Structure/String+Draw.swift
mit
1
// // String+Draw.swift // Coastline // // Created by 王渊鸥 on 2016/9/25. // Copyright © 2016年 王渊鸥. All rights reserved. // import UIKit public extension String { // 获取字符串的尺寸(单行) public func textSize(_ font:UIFont) -> CGSize { return (self as NSString).size(attributes: [NSFontAttributeName:font]) } // 获取字符串的尺寸(多行) public func textRectInSize(_ size:CGSize, font:UIFont, wordwarp:NSLineBreakMode, kern:CGFloat = 0) -> CGRect { let maxSize = CGSize(width: size.width, height: CGFloat.greatestFiniteMagnitude) let pStyle = NSMutableParagraphStyle() pStyle.lineBreakMode = wordwarp let rect = (self as NSString).boundingRect(with: maxSize, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSFontAttributeName:font, NSParagraphStyleAttributeName:pStyle, NSKernAttributeName:NSNumber(value: Float(kern))], context: nil) return CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: rect.height+1).integral } // 绘制字符串 public func drawInRect(_ rect:CGRect, attr:[String:AnyObject]) { (self as NSString).draw(in: rect, withAttributes: attr) } }
7bddb6c8cd02d95cbe5ba719cb6970cf
35.433333
255
0.73559
false
false
false
false
Hamasn/ARCute
refs/heads/master
CoreML-in-ARKit/CoreML in ARKit/ViewController.swift
apache-2.0
1
// // ViewController.swift // CoreML in ARKit // // Created by Hanley Weng on 14/7/17. // Copyright © 2017 CompanyName. All rights reserved. // import UIKit import SceneKit import ARKit import Vision import AVFoundation class ViewController: UIViewController, ARSCNViewDelegate { // SCENE @IBOutlet var sceneView: ARSCNView! let bubbleDepth : Float = 0.01 // the 'depth' of 3D text var latestPrediction : String = "…" // a variable containing the latest CoreML prediction // COREML var visionRequests = [VNRequest]() let dispatchQueueML = DispatchQueue(label: "com.hw.dispatchqueueml") // A Serial Queue @IBOutlet weak var debugTextView: UITextView! var synth:AVSpeechSynthesizer = AVSpeechSynthesizer() override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true // Create a new scene let scene = SCNScene() // Set the scene to the view sceneView.scene = scene // Enable Default Lighting - makes the 3D text a bit poppier. sceneView.autoenablesDefaultLighting = true ////////////////////////////////////////////////// // Tap Gesture Recognizer let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(gestureRecognize:))) view.addGestureRecognizer(tapGesture) ////////////////////////////////////////////////// // Set up Vision Model guard let inceptionV3Model = try? VNCoreMLModel(for: Inceptionv3().model) else { fatalError("Could not load model. Ensure model has been drag and dropped (copied) to XCode Project from https://developer.apple.com/machine-learning/") } // Set up Vision-CoreML Request let classificationRequest = VNCoreMLRequest(model: inceptionV3Model, completionHandler: classificationCompleteHandler) classificationRequest.imageCropAndScaleOption = VNImageCropAndScaleOption.centerCrop // Crop from centre of images and scale to appropriate size. visionRequests = [classificationRequest] // Begin Loop to Update CoreML loopCoreMLUpdate() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create a session configuration let configuration = ARWorldTrackingConfiguration() // Enable plane detection configuration.planeDetection = .horizontal // Run the view's session sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } // MARK: - ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { DispatchQueue.main.async { // Do any desired updates to SceneKit here. } } // MARK: - Status Bar: Hide override var prefersStatusBarHidden : Bool { return true } // MARK: - Interaction @objc func handleTap(gestureRecognize: UITapGestureRecognizer) { // HIT TEST : REAL WORLD self.updateText() } func updateText(){ DispatchQueue.main.async { // Get Screen Centre let screenCentre : CGPoint = CGPoint(x: self.sceneView.bounds.midX, y: self.sceneView.bounds.midY) let arHitTestResults : [ARHitTestResult] = self.sceneView.hitTest(screenCentre, types: [.featurePoint]) // Alternatively, we could use '.existingPlaneUsingExtent' for more grounded hit-test-points. if let closestResult = arHitTestResults.first { // Get Coordinates of HitTest let transform : matrix_float4x4 = closestResult.worldTransform let worldCoord : SCNVector3 = SCNVector3Make(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z) // Create 3D Text let node : SCNNode = self.createNewBubbleParentNode(self.latestPrediction) self.sceneView.scene.rootNode.addChildNode(node) node.position = worldCoord } } } func createNewBubbleParentNode(_ text : String) -> SCNNode { // Warning: Creating 3D Text is susceptible to crashing. To reduce chances of crashing; reduce number of polygons, letters, smoothness, etc. // TEXT BILLBOARD CONSTRAINT let billboardConstraint = SCNBillboardConstraint() billboardConstraint.freeAxes = SCNBillboardAxis.Y // BUBBLE-TEXT let bubble = SCNText(string: text, extrusionDepth: CGFloat(bubbleDepth)) var font = UIFont(name: "Futura", size: 0.15) font = font?.withTraits(traits: .traitBold) bubble.font = font bubble.alignmentMode = kCAAlignmentCenter bubble.firstMaterial?.diffuse.contents = UIColor.orange bubble.firstMaterial?.specular.contents = UIColor.white bubble.firstMaterial?.isDoubleSided = true // bubble.flatness // setting this too low can cause crashes. bubble.chamferRadius = CGFloat(bubbleDepth) // BUBBLE NODE let (minBound, maxBound) = bubble.boundingBox let bubbleNode = SCNNode(geometry: bubble) // Centre Node - to Centre-Bottom point bubbleNode.pivot = SCNMatrix4MakeTranslation( (maxBound.x - minBound.x)/2, minBound.y, bubbleDepth/2) // Reduce default text size bubbleNode.scale = SCNVector3Make(0.2, 0.2, 0.2) // CENTRE POINT NODE let sphere = SCNSphere(radius: 0.005) sphere.firstMaterial?.diffuse.contents = UIColor.cyan let sphereNode = SCNNode(geometry: sphere) // BUBBLE PARENT NODE let bubbleNodeParent = SCNNode() bubbleNodeParent.addChildNode(bubbleNode) bubbleNodeParent.addChildNode(sphereNode) bubbleNodeParent.constraints = [billboardConstraint] return bubbleNodeParent } // MARK: - CoreML Vision Handling func loopCoreMLUpdate() { // Continuously run CoreML whenever it's ready. (Preventing 'hiccups' in Frame Rate) dispatchQueueML.async { // 1. Run Update. self.updateCoreML() // 2. Loop this function. self.loopCoreMLUpdate() } } func classificationCompleteHandler(request: VNRequest, error: Error?) { // Catch Errors if error != nil { print("Error: " + (error?.localizedDescription)!) return } guard let observations = request.results else { print("No results") return } // Get Classifications let classifications = observations[0...1] // top 2 results .flatMap({ $0 as? VNClassificationObservation }) .map({ "\($0.identifier) \(String(format:"- %.2f", $0.confidence))" }) .joined(separator: "\n") if let top1Result = observations[0] as? VNClassificationObservation { if top1Result.confidence > 0.5 { self.speak(words: top1Result.identifier) } } DispatchQueue.main.async { // Print Classifications print(classifications) print("--") // Display Debug Text on screen var debugText:String = "" debugText += classifications self.debugTextView.text = debugText // Store the latest prediction var objectName:String = "…" objectName = classifications.components(separatedBy: "-")[0] objectName = objectName.components(separatedBy: ",")[0] self.latestPrediction = objectName } } private func speak(words:String){ if synth.isSpeaking { return } let utterance = AVSpeechUtterance(string: words) utterance.voice = AVSpeechSynthesisVoice(language: "en-US") utterance.rate = 0.75 * AVSpeechUtteranceDefaultSpeechRate synth.speak(utterance) } func updateCoreML() { /////////////////////////// // Get Camera Image as RGB let pixbuff : CVPixelBuffer? = (sceneView.session.currentFrame?.capturedImage) if pixbuff == nil { return } let ciImage = CIImage(cvPixelBuffer: pixbuff!) // Note: Not entirely sure if the ciImage is being interpreted as RGB, but for now it works with the Inception model. // Note2: Also uncertain if the pixelBuffer should be rotated before handing off to Vision (VNImageRequestHandler) - regardless, for now, it still works well with the Inception model. /////////////////////////// // Prepare CoreML/Vision Request let imageRequestHandler = VNImageRequestHandler(ciImage: ciImage, options: [:]) // let imageRequestHandler = VNImageRequestHandler(cgImage: cgImage!, orientation: myOrientation, options: [:]) // Alternatively; we can convert the above to an RGB CGImage and use that. Also UIInterfaceOrientation can inform orientation values. /////////////////////////// // Run Image Request do { try imageRequestHandler.perform(self.visionRequests) } catch { print(error) } } } extension UIFont { // Based on: https://stackoverflow.com/questions/4713236/how-do-i-set-bold-and-italic-on-uilabel-of-iphone-ipad func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont { let descriptor = self.fontDescriptor.withSymbolicTraits(UIFontDescriptorSymbolicTraits(traits)) return UIFont(descriptor: descriptor!, size: 0) } }
342724bb75f089a6bc11447ca60db18e
37.689139
253
0.61365
false
false
false
false
zmian/xcore.swift
refs/heads/main
Sources/Xcore/SwiftUI/Extensions/View+MaskInvert.swift
mit
1
// // Xcore // Copyright © 2021 Xcore // MIT license, see LICENSE file for details // import SwiftUI extension View { /// Invertly masks this view using the given size and corner radius. /// /// ``` /// Rectangle() /// .maskInvert(size: 200, cornerRadius: 30) /// .ignoresSafeArea() /// ``` public func maskInvert(size: CGFloat, cornerRadius: CGFloat) -> some View { maskInvert(size: CGSize(size), cornerRadius: cornerRadius) } /// Invertly masks this view using the given size and corner radius. /// /// ``` /// Rectangle() /// .maskInvert(size: CGSize(width: 200, height: 100), cornerRadius: 30) /// .ignoresSafeArea() /// ``` public func maskInvert(size: CGSize, cornerRadius: CGFloat) -> some View { foregroundColor(Color.black.opacity(0.75)) .maskInvert( RoundedRectangleCorner(radius: cornerRadius, corners: .allCorners), size: size ) } /// Invertly masks this view using the given size and corner radius. /// /// ``` /// Rectangle() /// .maskInvert(Circle(), size: CGSize(width: 200, height: 100)) /// .ignoresSafeArea() /// ``` public func maskInvert<S: Shape>(_ shape: S, size: CGSize) -> some View { mask( InvertedShape(shape, size: size) .fill(style: FillStyle(eoFill: true)) ) } /// Invertly masks this view using the given size and corner radius. /// /// ``` /// Rectangle() /// .maskInvert(Circle(), lineWidth: 20) /// .ignoresSafeArea() /// ``` public func maskInvert<S: Shape>(_ shape: S, lineWidth: CGFloat) -> some View { mask( InvertedShape(shape, lineWidth: lineWidth) .fill(style: FillStyle(eoFill: true)) ) } } // MARK: - InvertedShape private struct InvertedShape<S: Shape>: Shape { private let dimension: Either<CGSize, CGFloat> private let shape: S init(_ shape: S, size: CGSize) { self.shape = shape self.dimension = .left(size) } init(_ shape: S, lineWidth: CGFloat) { self.shape = shape self.dimension = .right(lineWidth) } func path(in rect: CGRect) -> Path { var path = Rectangle().path(in: rect) let innerRect: CGRect switch dimension { case let .left(size): let origin = CGPoint( x: rect.midX - size.width / 2, y: rect.midY - size.height / 2 ) innerRect = CGRect(origin: origin, size: size) case let .right(lineWidth): innerRect = rect.inset(by: .init(lineWidth)) } path.addPath(shape.path(in: innerRect)) return path } }
0c0c8ef61a1c4f026d0072ce4f248791
27.158416
83
0.548875
false
false
false
false
kikettas/Swarkn
refs/heads/master
Swarkn/Classes/LoadingModalViewController.swift
mit
1
// // LoadingModalViewController.swift // // Created by kikettas on 19/10/2016. // Copyright © 2016. All rights reserved. // import Foundation open class LoadingModalViewController: UIViewController { fileprivate let activityView = ActivityView() public init(message: String) { super.init(nibName: nil, bundle: nil) modalTransitionStyle = .crossDissolve modalPresentationStyle = .overFullScreen activityView.messageLabel.text = message view = activityView } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private class ActivityView: UIView { let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) let boundingBoxView = UIView(frame: CGRect.zero) let messageLabel = UILabel(frame: CGRect.zero) init() { super.init(frame: CGRect.zero) backgroundColor = UIColor(white: 0.0, alpha: 0.5) boundingBoxView.backgroundColor = UIColor(white: 0.0, alpha: 0.5) boundingBoxView.layer.cornerRadius = 12.0 activityIndicatorView.startAnimating() messageLabel.font = UIFont.boldSystemFont(ofSize: UIFont.labelFontSize) messageLabel.textColor = UIColor.white messageLabel.textAlignment = .center messageLabel.shadowColor = UIColor.black messageLabel.shadowOffset = CGSize(width: 0.0, height: 1.0) messageLabel.numberOfLines = 0 addSubview(boundingBoxView) addSubview(activityIndicatorView) addSubview(messageLabel) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() boundingBoxView.frame.size.width = 160.0 boundingBoxView.frame.size.height = 160.0 boundingBoxView.frame.origin.x = ceil((bounds.width / 2.0) - (boundingBoxView.frame.width / 2.0)) boundingBoxView.frame.origin.y = ceil((bounds.height / 2.0) - (boundingBoxView.frame.height / 2.0)) activityIndicatorView.frame.origin.x = ceil((bounds.width / 2.0) - (activityIndicatorView.frame.width / 2.0)) activityIndicatorView.frame.origin.y = ceil((bounds.height / 2.0) - (activityIndicatorView.frame.height / 2.0)) let messageLabelSize = messageLabel.sizeThatFits(CGSize(width: 160.0 - 20.0 * 2.0, height: CGFloat.greatestFiniteMagnitude)) messageLabel.frame.size.width = messageLabelSize.width messageLabel.frame.size.height = messageLabelSize.height messageLabel.frame.origin.x = ceil((bounds.width / 2.0) - (messageLabel.frame.width / 2.0)) messageLabel.frame.origin.y = ceil(activityIndicatorView.frame.origin.y + activityIndicatorView.frame.size.height + ((boundingBoxView.frame.height - activityIndicatorView.frame.height) / 4.0) - (messageLabel.frame.height / 2.0)) } }
ec44d19bb2dff77324154df7ba124c6e
38.986842
236
0.677526
false
false
false
false
codercd/DPlayer
refs/heads/master
DPlayer/LocalFolderViewController.swift
mit
1
// // LocalFloderViewController.swift // DPlayer // // Created by LiChendi on 16/4/6. // Copyright © 2016年 LiChendi. All rights reserved. // import UIKit class LocalFolderViewController: UITableViewController { let path: NSString var subFolders = Array<String>() var files = Array<String>() init(path: String) { self.path = path super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView .registerClass(UITableViewCell.self, forCellReuseIdentifier: "LocalFloderViewController") guard let fileArray = try? NSFileManager.defaultManager().contentsOfDirectoryAtPath(path as String) else { subFolders = Array<String>() files = Array<String>() return } var isDirectory = ObjCBool(true) for fileName in fileArray { if fileName.hasPrefix(".") { continue } let fullFileName = path.stringByAppendingPathComponent(fileName) NSFileManager.defaultManager().fileExistsAtPath(fullFileName, isDirectory: &isDirectory) if (isDirectory) { subFolders.append(fileName) } else { files.append(fileName) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows switch section { case 0: return subFolders.count case 1: return files.count default: return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("LocalFloderViewController", forIndexPath: indexPath) switch indexPath.section { case 0: cell.textLabel?.text = subFolders[indexPath.row] case 1: cell.textLabel?.text = files[indexPath.row] default: cell.textLabel?.text = "" } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case 0: let folderPath = path.stringByAppendingPathComponent(subFolders[indexPath.row]) let localFolderViewController = LocalFolderViewController(path:folderPath) self.navigationController?.pushViewController(localFolderViewController, animated: true) // self .presentViewController(localFolderViewController, animated: true, completion: nil) case 1: let filePath = path.stringByAppendingPathComponent(files[indexPath.row]) let moviePlayerController = DPlayerMoviePlayerViewController(url: NSURL(fileURLWithPath: filePath)) // self.navigationController?.pushViewController(playerCon, animated: true) self.presentViewController(moviePlayerController, animated: true, completion: nil) default: return } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
06b896edb31e3d745e31f438d0863c39
34.763158
157
0.652502
false
false
false
false
stefanceriu/SCPageViewController
refs/heads/master
Demo/SwiftDemo/RootViewController.swift
mit
1
// // RootViewController.swift // SCPageViewController // // Created by Stefan Ceriu on 10/14/15. // Copyright © 2015 Stefan Ceriu. All rights reserved. // import Foundation class RootViewController : UIViewController , SCPageViewControllerDataSource, SCPageViewControllerDelegate, MainViewControllerDelegate { var pageViewController : SCPageViewController = SCPageViewController() var viewControllers = [UIViewController?]() override func viewDidLoad() { super.viewDidLoad() for _ in 1...5 { viewControllers.append(nil); } self.pageViewController.setLayouter(SCPageLayouter(), animated: false, completion: nil) self.pageViewController.easingFunction = SCEasingFunction(type: SCEasingFunctionType.linear) //self.pageViewController.scrollView.maximumNumberOfTouches = 1; //self.pageViewController.scrollView.panGestureRecognizer.minimumNumberOfTouches = 2; self.pageViewController.dataSource = self; self.pageViewController.delegate = self; self.addChildViewController(self.pageViewController) self.pageViewController.view.frame = self.view.bounds self.view.addSubview(self.pageViewController.view) self.pageViewController.didMove(toParentViewController: self) } //MARK: - SCPageViewControllerDataSource func numberOfPages(in pageViewController: SCPageViewController!) -> UInt { return UInt(self.viewControllers.count) } func pageViewController(_ pageViewController: SCPageViewController!, viewControllerForPageAt pageIndex: UInt) -> UIViewController! { if let viewController = self.viewControllers[Int(pageIndex)] { return viewController } else { let viewController = MainViewController() viewController.delegate = self; func randomColor () -> UIColor { let hue = CGFloat(arc4random() % 256) / 256.0; // 0.0 to 1.0 let saturation = (CGFloat(arc4random() % 128) / 256.0 ) + 0.5 // 0.5 to 1.0, away from white let brightness = (CGFloat(arc4random() % 128) / 256.0 ) + 0.5 // 0.5 to 1.0, away from black return UIColor.init(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0); } viewController.view.backgroundColor = randomColor() viewController.view.frame = self.view.bounds; self.viewControllers[Int(pageIndex)] = viewController return viewController } } //MARK: - SCPageViewControllerDelegate func pageViewController(_ pageViewController: SCPageViewController!, didNavigateToOffset offset: CGPoint) { func layouterToType(layouter: SCPageLayouterProtocol) -> PageLayouterType { switch layouter { case is SCSlidingPageLayouter: return PageLayouterType.sliding case is SCParallaxPageLayouter: return PageLayouterType.parallax case is SCCardsPageLayouter: return PageLayouterType.cards default: return PageLayouterType.plain } } let layouterType = layouterToType(layouter: self.pageViewController.layouter!); for optionalValue in self.viewControllers { if(optionalValue != nil) { let viewController = optionalValue as! MainViewController viewController.layouterType = layouterType; } } } //MARK: - MainViewControllerDelegate func mainViewControllerDidChangeLayouterType(_ mainViewController: MainViewController) { switch(mainViewController.layouterType!) { case .plain: self.pageViewController.setLayouter(SCPageLayouter(), animated: false, completion: nil) case .sliding: self.pageViewController.setLayouter(SCSlidingPageLayouter(), animated: true, completion: nil) case .parallax: self.pageViewController.setLayouter(SCParallaxPageLayouter(), animated: true, completion: nil) case .cards: self.pageViewController.setLayouter(SCCardsPageLayouter(), animated: true, completion: nil) } } }
a4b43454936dc237c498ffdd569accdf
38.846847
136
0.641194
false
false
false
false
kedu/FULL_COPY
refs/heads/master
xingLangWeiBo/xingLangWeiBo/Classes/Modeul/Discover/DiscoverTableViewController.swift
mit
1
// // DiscoverTableViewController.swift // xingLangWeiBo // // Created by Apple on 16/10/8. // Copyright © 2016年 lkb-求工作qq:1218773641. All rights reserved. // import UIKit class DiscoverTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() vistorLoginView?.setUIInfo("visitordiscover_image_message", title: "发现") // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
546058dd76cdfd4c5dd8e5c9dd37426c
34.094737
157
0.691062
false
false
false
false
SwifterSwift/SwifterSwift
refs/heads/master
Sources/SwifterSwift/CoreGraphics/CGPointExtensions.swift
mit
1
// CGPointExtensions.swift - Copyright 2020 SwifterSwift #if canImport(CoreGraphics) import CoreGraphics // MARK: - Methods public extension CGPoint { /// SwifterSwift: Distance from another CGPoint. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// let distance = point1.distance(from: point2) /// // distance = 28.28 /// /// - Parameter point: CGPoint to get distance from. /// - Returns: Distance between self and given CGPoint. func distance(from point: CGPoint) -> CGFloat { return CGPoint.distance(from: self, to: point) } /// SwifterSwift: Distance between two CGPoints. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// let distance = CGPoint.distance(from: point2, to: point1) /// // distance = 28.28 /// /// - Parameters: /// - point1: first CGPoint. /// - point2: second CGPoint. /// - Returns: distance between the two given CGPoints. static func distance(from point1: CGPoint, to point2: CGPoint) -> CGFloat { // http://stackoverflow.com/questions/6416101/calculate-the-distance-between-two-cgpoints return sqrt(pow(point2.x - point1.x, 2) + pow(point2.y - point1.y, 2)) } } // MARK: - Operators public extension CGPoint { /// SwifterSwift: Add two CGPoints. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// let point = point1 + point2 /// // point = CGPoint(x: 40, y: 40) /// /// - Parameters: /// - lhs: CGPoint to add to. /// - rhs: CGPoint to add. /// - Returns: result of addition of the two given CGPoints. static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } /// SwifterSwift: Add a CGPoints to self. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// point1 += point2 /// // point1 = CGPoint(x: 40, y: 40) /// /// - Parameters: /// - lhs: `self`. /// - rhs: CGPoint to add. static func += (lhs: inout CGPoint, rhs: CGPoint) { lhs.x += rhs.x lhs.y += rhs.y } /// SwifterSwift: Subtract two CGPoints. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// let point = point1 - point2 /// // point = CGPoint(x: -20, y: -20) /// /// - Parameters: /// - lhs: CGPoint to subtract from. /// - rhs: CGPoint to subtract. /// - Returns: result of subtract of the two given CGPoints. static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } /// SwifterSwift: Subtract a CGPoints from self. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// point1 -= point2 /// // point1 = CGPoint(x: -20, y: -20) /// /// - Parameters: /// - lhs: `self`. /// - rhs: CGPoint to subtract. static func -= (lhs: inout CGPoint, rhs: CGPoint) { lhs.x -= rhs.x lhs.y -= rhs.y } /// SwifterSwift: Multiply a CGPoint with a scalar. /// /// let point1 = CGPoint(x: 10, y: 10) /// let scalar = point1 * 5 /// // scalar = CGPoint(x: 50, y: 50) /// /// - Parameters: /// - point: CGPoint to multiply. /// - scalar: scalar value. /// - Returns: result of multiplication of the given CGPoint with the scalar. static func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } /// SwifterSwift: Multiply self with a scalar. /// /// let point1 = CGPoint(x: 10, y: 10) /// point *= 5 /// // point1 = CGPoint(x: 50, y: 50) /// /// - Parameters: /// - point: `self`. /// - scalar: scalar value. /// - Returns: result of multiplication of the given CGPoint with the scalar. static func *= (point: inout CGPoint, scalar: CGFloat) { point.x *= scalar point.y *= scalar } /// SwifterSwift: Multiply a CGPoint with a scalar. /// /// let point1 = CGPoint(x: 10, y: 10) /// let scalar = 5 * point1 /// // scalar = CGPoint(x: 50, y: 50) /// /// - Parameters: /// - scalar: scalar value. /// - point: CGPoint to multiply. /// - Returns: result of multiplication of the given CGPoint with the scalar. static func * (scalar: CGFloat, point: CGPoint) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } } #endif
ef760b544c03bd0e6e62284314f681bf
31.780822
97
0.539699
false
false
false
false
julienbodet/wikipedia-ios
refs/heads/develop
Wikipedia/Code/OnThisDayExploreCollectionViewCell.swift
mit
1
import UIKit public class OnThisDayExploreCollectionViewCell: OnThisDayCollectionViewCell { private var topGradientView: WMFGradientView = WMFGradientView() private var bottomGradientView: WMFGradientView = WMFGradientView() var isFirst: Bool = false var isLast: Bool = false override public func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize { if (apply) { let topGradientHeight: CGFloat = 17 let bottomGradientHeight: CGFloat = 43 let topGradientSize = CGSize(width: timelineView.frame.size.width, height: topGradientHeight) let bottomGradientSize = CGSize(width: timelineView.frame.size.width, height: bottomGradientHeight) topGradientView.frame = CGRect(origin: .zero, size: topGradientSize) bottomGradientView.frame = CGRect(origin: CGPoint(x: 0, y: size.height - bottomGradientHeight), size: bottomGradientSize) topGradientView.isHidden = !isFirst bottomGradientView.isHidden = !isLast } return super.sizeThatFits(size, apply: apply) } override open func setup() { super.setup() timelineView.addSubview(topGradientView) timelineView.addSubview(bottomGradientView) topGradientView.startPoint = CGPoint(x: 0.5, y: 0) topGradientView.endPoint = CGPoint(x: 0.5, y: 1) bottomGradientView.startPoint = CGPoint(x: 0.5, y: 0) bottomGradientView.endPoint = CGPoint(x: 0.5, y: 0.8) } public override func apply(theme: Theme) { super.apply(theme: theme) let opaque = theme.colors.paperBackground let clear = opaque.withAlphaComponent(0) topGradientView.setStart(opaque, end: clear) bottomGradientView.setStart(clear, end: opaque) } }
653ec1e5858b15849026ce58ba9a5f83
43.875
133
0.683008
false
false
false
false
Amazing-Team/GlobeCheckr
refs/heads/master
TinderSwipeCardsSwift/LoginController.swift
mit
1
// // LoginController.swift // TinderSwipeCardsSwift // // Created by Andrei Nevar on 31/10/15. // Copyright © 2015 gcweb. All rights reserved. // import UIKit import Foundation var pricesTotal = [Int]() class LoginController: UIViewController { override func viewWillAppear(animated: Bool) { self.navigationController?.navigationBarHidden = true } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.navigationBarHidden = false } @IBAction func callApi(sender: UIButton) { /* API Structure // Origin airport based from user's location (e.x. ams,bcn) // Date of departure yyyyMMdd(e.x 20150606) // Date of return yyyyMMdd(e.x 20150606) // Price range (e.x. 50-100) // Number of people */ let url = NSURL(string: "http://opendutchhackathon.w3ibm.mybluemix.net/ams/20151101/20151110/100-2000/2") let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in //Table with the destiantions available var destinations = [String]() //Table with the prices of the aller var pricesAller = [Int]() //Table with the prices of the return var pricesRetur = [Int]() //Table with the total prices of the trips //var pricesTotal = [Int]() //Table with the departure times of the aller var departureTimeAller = [String]() //Table with the arrival times of the aller var arrivalTimeAller = [String]() //Table with the departure times of the return var departureTimeRetur = [String]() //Table with the arrival times of the return var arrivalTimeRetur = [String]() do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary destinations = jsonResult!.valueForKeyPath("flightOffer.inboundFlight.departureAirport.locationCode") as! [String]; pricesAller = jsonResult!.valueForKeyPath("flightOffer.inboundFlight.pricingInfo.totalPriceAllPassengers") as! [Int]; pricesRetur = jsonResult!.valueForKeyPath("flightOffer.outboundFlight.pricingInfo.totalPriceAllPassengers") as! [Int]; departureTimeAller = jsonResult!.valueForKeyPath("flightOffer.inboundFlight.departureDateTime") as! [String]; arrivalTimeAller = jsonResult!.valueForKeyPath("flightOffer.inboundFlight.arrivalDateTime") as! [String]; departureTimeRetur = jsonResult!.valueForKeyPath("flightOffer.outboundFlight.departureDateTime") as! [String]; arrivalTimeRetur = jsonResult!.valueForKeyPath("flightOffer.outboundFlight.arrivalDateTime") as! [String]; print(destinations) for (var i = 0; i < pricesAller.count; i++ ){ pricesTotal.append(pricesAller[i] + pricesRetur[i]) } print(pricesTotal) print(departureTimeAller) print(arrivalTimeAller) print(departureTimeRetur) print(arrivalTimeRetur) } catch let error as NSError { print(error) } } task.resume() } }
d14401c2a26c273de5b74dca55eaa1f9
37.046296
148
0.535054
false
false
false
false
amraboelela/swift
refs/heads/master
test/SILGen/inlinable_attribute.swift
apache-2.0
3
// RUN: %target-swift-emit-silgen -module-name inlinable_attribute -emit-verbose-sil -warnings-as-errors %s | %FileCheck %s // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute15fragileFunctionyyF : $@convention(thin) () -> () @inlinable public func fragileFunction() { } public struct MySt { // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStV6methodyyF : $@convention(method) (MySt) -> () @inlinable public func method() {} // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStV8propertySivg : $@convention(method) (MySt) -> Int @inlinable public var property: Int { return 5 } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStVyS2icig : $@convention(method) (Int, MySt) -> Int @inlinable public subscript(x: Int) -> Int { return x } } public class MyCls { // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute5MyClsCfD : $@convention(method) (@owned MyCls) -> () @inlinable deinit {} // Allocating entry point is [serialized] // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute5MyClsC14designatedInitACyt_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls public init(designatedInit: ()) {} // Note -- convenience init is intentionally not [serialized] // CHECK-LABEL: sil [ossa] @$s19inlinable_attribute5MyClsC15convenienceInitACyt_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls public convenience init(convenienceInit: ()) { self.init(designatedInit: ()) } } // Make sure enum case constructors for public and versioned enums are // [serialized]. @usableFromInline enum MyEnum { case c(MySt) } // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] [ossa] @$s19inlinable_attribute6MyEnumO1cyAcA0C2StVcACmFTc : $@convention(thin) (@thin MyEnum.Type) -> @owned @callee_guaranteed (MySt) -> MyEnum @inlinable public func referencesMyEnum() { _ = MyEnum.c } // CHECK-LABEL: sil non_abi [transparent] [serialized] [ossa] @$s19inlinable_attribute15HasInitializersV1xSivpfi : $@convention(thin) () -> Int // CHECK-LABEL: sil non_abi [transparent] [serialized] [ossa] @$s19inlinable_attribute15HasInitializersV1ySivpfi : $@convention(thin) () -> Int @_fixed_layout public struct HasInitializers { public let x = 1234 internal let y = 4321 @inlinable public init() {} } public class Horse { public func gallop() {} } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute15talkAboutAHorse1hyAA5HorseC_tF : $@convention(thin) (@guaranteed Horse) -> () { // CHECK: function_ref @$s19inlinable_attribute5HorseC6gallopyyFTc // CHECK: return // CHECK: } // CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$s19inlinable_attribute5HorseC6gallopyyFTc : $@convention(thin) (@guaranteed Horse) -> @owned @callee_guaranteed () -> () { // CHECK: class_method // CHECK: return // CHECK: } @inlinable public func talkAboutAHorse(h: Horse) { _ = h.gallop } @_fixed_layout public class PublicBase { @inlinable public init(horse: Horse) {} } @usableFromInline @_fixed_layout class UFIBase { @usableFromInline @inlinable init(horse: Horse) {} } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0Cfd : $@convention(method) (@guaranteed PublicDerivedFromPublic) -> @owned Builtin.NativeObject // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0CfD : $@convention(method) (@owned PublicDerivedFromPublic) -> () // Make sure the synthesized delegating initializer is inlinable also // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0C5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PublicDerivedFromPublic) -> @owned PublicDerivedFromPublic @_fixed_layout public class PublicDerivedFromPublic : PublicBase { // Allow @inlinable deinits @inlinable deinit {} } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute20UFIDerivedFromPublicC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned UFIDerivedFromPublic) -> @owned UFIDerivedFromPublic @usableFromInline @_fixed_layout class UFIDerivedFromPublic : PublicBase { } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute17UFIDerivedFromUFIC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned UFIDerivedFromUFI) -> @owned UFIDerivedFromUFI @usableFromInline @_fixed_layout class UFIDerivedFromUFI : UFIBase { // Allow @inlinable deinits @inlinable deinit {} } // CHECK-LABEL: sil hidden [ossa] @$s19inlinable_attribute25InternalDerivedFromPublicC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned InternalDerivedFromPublic) -> @owned InternalDerivedFromPublic class InternalDerivedFromPublic : PublicBase {} // CHECK-LABEL: sil hidden [ossa] @$s19inlinable_attribute22InternalDerivedFromUFIC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned InternalDerivedFromUFI) -> @owned InternalDerivedFromUFI class InternalDerivedFromUFI : UFIBase {} // CHECK-LABEL: sil private [ossa] @$s19inlinable_attribute24PrivateDerivedFromPublic{{.+}}LLC5horseAdA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PrivateDerivedFromPublic) -> @owned PrivateDerivedFromPublic private class PrivateDerivedFromPublic : PublicBase {} // CHECK-LABEL: sil private [ossa] @$s19inlinable_attribute21PrivateDerivedFromUFI{{.+}}LLC5horseAdA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PrivateDerivedFromUFI) -> @owned PrivateDerivedFromUFI private class PrivateDerivedFromUFI : UFIBase {} // Make sure that nested functions are also serializable. // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute3basyyF @inlinable public func bas() { // CHECK-LABEL: sil shared [serializable] [ossa] @$s19inlinable_attribute3basyyF3zimL_yyF func zim() { // CHECK-LABEL: sil shared [serializable] [ossa] @$s19inlinable_attribute3basyyF3zimL_yyF4zangL_yyF func zang() { } } // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute3bas{{[_0-9a-zA-Z]*}}U_ let zung = { // CHECK-LABEL: sil shared [serializable] [ossa] @$s19inlinable_attribute3basyyFyycfU_7zippityL_yyF func zippity() { } } } // CHECK-LABEL: sil [ossa] @$s19inlinable_attribute6globalyS2iF : $@convention(thin) (Int) -> Int public func global(_ x: Int) -> Int { return x } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF : $@convention(thin) () -> () @inlinable func cFunctionPointer() { // CHECK: function_ref @$s19inlinable_attribute6globalyS2iFTo let _: @convention(c) (Int) -> Int = global // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_To let _: @convention(c) (Int) -> Int = { return $0 } func local(_ x: Int) -> Int { return x } // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iFTo let _: @convention(c) (Int) -> Int = local } // CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$s19inlinable_attribute6globalyS2iFTo : $@convention(c) (Int) -> Int // CHECK: function_ref @$s19inlinable_attribute6globalyS2iF // CHECK: return // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_ : $@convention(thin) (Int) -> Int { // CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_To : $@convention(c) (Int) -> Int { // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_ // CHECK: return // CHECK-LABEL: sil shared [serializable] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iF : $@convention(thin) (Int) -> Int { // CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iFTo : $@convention(c) (Int) -> Int { // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iF // CHECK: return
0d6d070e08d224b5996284f1b00ec839
42.038043
221
0.740498
false
false
false
false
SmallPlanetSwift/PlanetSwift
refs/heads/master
Sources/PlanetSwift/GaxbTypes/String+Bundle.swift
mit
1
// // String+Bundle.swift // PlanetSwift // // Created by Brad Bambara on 1/13/15. // Copyright (c) 2015 Small Planet. All rights reserved. // import Foundation extension String { public init(bundlePath: String) { self.init() let pathComponents = bundlePath.components(separatedBy: ":/") switch pathComponents[0] { case "bundle": if let resourcePath = Bundle.main.resourcePath { self = NSString(string: resourcePath).appendingPathComponent(pathComponents[1]) } case "documents": let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] self = NSString(string: documentsPath).appendingPathComponent(pathComponents[1]) case "cache": let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] self = NSString(string: cachePath).appendingPathComponent(pathComponents[1]) default: self = bundlePath } } }
00b887056d5927064de98ce7e46aca68
31.8125
113
0.657143
false
false
false
false
WEIHOME/CoreDataDemo-Swift
refs/heads/master
CoreDataDemo/AppDelegate.swift
mit
1
// // AppDelegate.swift // CoreDataDemo // // Created by Weihong Chen on 02/05/2015. // Copyright (c) 2015 Weihong. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.weihong.CoreDataDemo" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("CoreDataDemo", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext!.hasChanges { do { try managedObjectContext!.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
662878982045d905e3df106bf8e06660
50.39823
285
0.709194
false
false
false
false
movielala/TVOSButton
refs/heads/master
TVOSButton/TVOSButtonShadow.swift
apache-2.0
1
// // TVOSButtonShadow.swift // TVOSButton // // Created by Cem Olcay on 12/02/16. // Copyright © 2016 MovieLaLa. All rights reserved. // import UIKit public enum TVOSButtonShadow { case Custom(color: UIColor?, offset: CGSize?, opacity: Float?, radius: CGFloat?, path: UIBezierPath?) case Default(offsetX: CGFloat, offsetY: CGFloat, radius: CGFloat) case Focused case Highlighted case TitleLabel public func getStyle(withHeight height: CGFloat) -> TVOSButtonShadowStyle { switch self { case .Custom(let color, let offset, let opacity, let radius, let path): return TVOSButtonShadowStyle( color: color, offset: offset, opacity: opacity, radius: radius, path: path) case .Default(let x, let y, let r): return TVOSButtonShadowStyle( color: UIColor.blackColor(), offset: CGSize(width: x, height: y), opacity: 0.2, radius: r, path: nil) case .Focused: return TVOSButtonShadow.Default( offsetX: 0, offsetY: 25, radius: 10) .getStyle(withHeight: height) case .Highlighted: return TVOSButtonShadow.Default( offsetX: 0, offsetY: 5, radius: 10) .getStyle(withHeight: height) case .TitleLabel: return TVOSButtonShadow.Default( offsetX: 0, offsetY: 2, radius: 3) .getStyle(withHeight: height) } } public func applyStyle(onLayer layer: CALayer?) { guard let layer = layer else { return } let style = getStyle(withHeight: layer.frame.height) layer.shadowColor = style.color?.CGColor layer.shadowOffset = style.offset ?? CGSize.zero layer.shadowOpacity = style.opacity ?? 1 layer.shadowPath = style.path?.CGPath layer.shadowRadius = style.radius ?? 0 } public static func resetStyle(onLayer layer: CALayer?) { guard let layer = layer else { return } layer.shadowColor = nil layer.shadowOffset = CGSize.zero layer.shadowOpacity = 0 layer.shadowPath = nil layer.shadowRadius = 0 } } public struct TVOSButtonShadowStyle { public var color: UIColor? public var offset: CGSize? public var opacity: Float? public var radius: CGFloat? public var path: UIBezierPath? }
6a9caa228d64e0bd62b284b8df06b603
25.776471
103
0.65246
false
false
false
false
naokits/my-programming-marathon
refs/heads/master
ParseLoginDemo/ParseLoginDemo/ViewController.swift
mit
1
// // ViewController.swift // ParseLoginDemo // // Created by Naoki Tsutsui on 1/15/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import UIKit import ParseUI class ViewController: UIViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) guard let currentUser = User.currentUser() else { login() return } print("ログイン中のユーザ: \(currentUser)") currentUser.japaneseDate = NSDate() currentUser.saveInBackground() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func signup() { let controller = PFSignUpViewController() controller.delegate = self self.presentViewController(controller, animated:false, completion: nil) } func login() { let controller = PFLogInViewController() // controller.logInView?.logo = UIImageView(image: UIImage(named: "")) controller.delegate = self self.presentViewController(controller, animated:true, completion: nil) } // MARK:- PFSignUpViewControllerDelegate func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) { guard let e = error else { return } print("サインアップエラー: \(e)") } func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) { print("サインアップ成功: \(user)") } func signUpViewController(signUpController: PFSignUpViewController, shouldBeginSignUp info: [String : String]) -> Bool { print("Info: \(info)") return true } func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) { print("サインアップがキャンセルされた") } // MARK:- PFLogInViewControllerDelegate func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) { guard let e = error else { return } print("ログインエラー: \(e)") } func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) { print("ログイン成功: \(user)") dismissViewControllerAnimated(true, completion: nil) } func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool { print("Info: \(username)") return true } func logInViewControllerDidCancelLogIn(logInController: PFLogInViewController) { print("ログインがキャンセルされた") } // MARK:- Location func saveCurrentLocation() { let location = Location() location.japaneseDate = NSDate() location.geo = PFGeoPoint(latitude: 0.0, longitude: 0.0) location.saveInBackground().continueWithBlock { (task) -> AnyObject? in if let error = task.error { print("保存失敗: \(error)") } else { print("保存成功") } return nil } } }
160b50d1f7fc586072da452caa93d16f
28.791304
143
0.637186
false
false
false
false
szysz3/ios-timetracker
refs/heads/master
TimeTracker/AddTaskCellCollectionViewCell.swift
mit
1
// // AddTaskCellCollectionViewCell.swift // TimeTracker // // Created by Michał Szyszka on 21.09.2016. // Copyright © 2016 Michał Szyszka. All rights reserved. // import UIKit class AddTaskCellCollectionViewCell: UICollectionViewCell { //MARK: Outlets @IBOutlet weak var imgTick: UIImageView! @IBOutlet weak var background: UIView! //MARK: Fields static let tag = "AddTaskCellCollectionViewCell" //MARK: Functions override func awakeFromNib() { super.awakeFromNib() initialize() } func setColor(_ color: UIColor){ background.backgroundColor = color } func setCellSelected(_ isSelected: Bool){ imgTick.isHidden = !isSelected } private func initialize(){ background.layer.cornerRadius = UIConsts.cornerRadius background.layer.borderWidth = UIConsts.borderWidth background.layer.borderColor = UIColor.lightGray.cgColor } }
61ef53fa980125a45994176a57a7a73d
22.428571
64
0.659553
false
false
false
false
rugheid/Swift-MathEagle
refs/heads/master
MathEagle/Functions/NumberProperties.swift
mit
1
// // NumberProperties.swift // MathEagle // // Created by Rugen Heidbuchel on 05/12/15. // Copyright © 2015 Jorestha Solutions. All rights reserved. // /** Returns an array containing the digits of the given number from most to least significant digits. - parameter number: The number to get the digits of. */ public func digits(_ number: Int) -> [Int] { //TODO: Benchmark this method. return "\(abs(number))".map{ Int("\($0)")! } } /** Returns an array containing the digits of the given big int from most to least significant digits. - parameter bigInt: The big int to get the digits of. */ public func digits(_ bigInt: BigInt) -> [Int] { var stringValue = bigInt.stringValue if stringValue.hasPrefix("-") { stringValue.remove(at: stringValue.startIndex) } return stringValue.map{ Int("\($0)")! } } /** Returns the number of digits of the given number. - parameter number: The number to get the number of digits of. */ public func numberOfDigits(_ number: Int) -> Int { // TODO: Make generic? var n = abs(number) var nr = 1 while n > 10 { if n > 100000000 { nr += 8 n /= 100000000 } if n > 10000 { nr += 4 n /= 10000 } if n > 100 { nr += 2 n /= 100 } if n > 10 { nr += 1 n /= 10 } } return nr } /** Returns the number of digits of the given number. - parameter number: The number to get the number of digits of. */ public func numberOfDigits(_ number: BigInt) -> Int { return number.numberOfDigits } /** Returns whether the given number is pandigital. - parameter number: The number to check. - parameter includeZero: Whether or not zero should be included. - examples: 12345678 is a pandigital number without zero. 10234568 is a pandigtal number with zero. */ public func isPandigital(_ number: Int, includeZero: Bool = false) -> Bool { var digitsPassed = Set<Int>() let digitsArray = digits(number) var maximum = digitsArray.count if includeZero { maximum -= 1 } for digit in digitsArray { if digitsPassed.contains(digit) || digit > maximum || (!includeZero && digit == 0) { return false } digitsPassed.insert(digit) } return true }
980842c2073feeae3fbab1451543ec1f
21
99
0.583604
false
false
false
false
ls1intum/sReto
refs/heads/master
Source/sReto/Core/Routing/FloodingPacketManager.swift
mit
1
// // FloodingPacketManager.swift // sReto // // Created by Julian Asamer on 14/08/14. // Copyright (c) 2014 - 2016 Chair for Applied Software Engineering // // Licensed under the MIT License // // 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 /** * A FloodingPacket is a packet that floods any other packet through the network. * The pair of sequenceNumber and originIdentifier are required to ensure that packets are not flooded indefinitely. See the FloodingPacketManager for more information. */ struct FloodingPacket: Packet { let sequenceNumber: Int32 let originIdentifier: UUID let payload: Data static func getType() -> PacketType { return PacketType.floodPacket } static func getLength() -> Int { return MemoryLayout<PacketType>.size + MemoryLayout<Int32>.size + MemoryLayout<UUID>.size } static func deserialize(_ data: DataReader) -> FloodingPacket? { if !Packets.check(data: data, expectedType: self.getType(), minimumLength: self.getLength()) { return nil } return FloodingPacket(sequenceNumber: data.getInteger(), originIdentifier: data.getUUID(), payload: data.getData() as Data) } func serialize() -> Data { let data = DataWriter(length: type(of: self).getLength() + payload.count) data.add(type(of: self).getType().rawValue) data.add(self.sequenceNumber) data.add(self.originIdentifier) data.add(self.payload) return data.getData() as Data } } /** * A function that can be called when a packet is received. */ typealias PacketHandlerFunction = (DataReader, PacketType) -> () /** * The FloodingPacketManager implements the Flooding algorithm used to distribute packets through the network. * When a packet is received, and it or a newer one has been seen before, it is discarded. This is accomplished by storing the last seen sequence number * for each sender. * If the packet is new, it is forwarded to all direct neighbors of the local peer. */ class FloodingPacketManager: NSObject { /** The Router responsible for this flooding packet manager. */ weak var router: Router? /** The next sequence number that will be used for packets sent from this peer. */ var currentSequenceNumber: Int32 = 0 /** The highest sequence number seen for each remote peer. */ var sequenceNumbers: [UUID: Int32] = [:] /** The packet handlers registered with this flooding packet manager */ var packetHandlers: [PacketType: PacketHandlerFunction] = [:] /** Constructs a new FloodingPacketManager */ init(router: Router) { self.router = router } /** Adds a packet handler for a given type. */ func addPacketHandler(_ packetType: PacketType, handler: @escaping PacketHandlerFunction) { self.packetHandlers[packetType] = handler } /** Handles a received packet from a given source. If the packet is new, it is forwarded and handled, otherwise it is dismissed. */ func handlePacket(_ sourceIdentifier: UUID, data: DataReader, packetType: PacketType) { let packet = FloodingPacket.deserialize(data) if let packet = packet { if let mostRecentSequenceNumber = self.sequenceNumbers[packet.originIdentifier] { if mostRecentSequenceNumber >= packet.sequenceNumber { return } } self.sequenceNumbers[packet.originIdentifier] = packet.sequenceNumber for neighbor in router?.neighbors ?? [] { if neighbor.identifier == sourceIdentifier { continue } neighbor.sendPacket(packet) } if let packetType = PacketType(rawValue: DataReader(packet.payload).getInteger()) { if let packetHandler = self.packetHandlers[packetType] { packetHandler(DataReader(packet.payload), packetType) } else { log(.high, error: "Error in FloodingPacketManager: No packet handler for packet type \(packetType)") } } else { log(.high, error: "Error in FloodingPacketManager: Payload contains invalid packet type.") } } } /** Floods a new packet through the network. Increases the sequence number and sends the packet to all neighbors. */ func floodPacket(_ packet: Packet) { if let router = self.router { let floodingPacket = FloodingPacket(sequenceNumber: self.currentSequenceNumber, originIdentifier: router.identifier, payload: packet.serialize() as Data) self.sequenceNumbers[router.identifier] = self.currentSequenceNumber self.currentSequenceNumber += 1 for neighbor in router.neighbors { neighbor.sendPacket(floodingPacket) } } } }
3700cfe23634a0d075ee9a18eb3ed7ac
46.253968
167
0.678367
false
false
false
false
JesusAntonioGil/OnTheMap
refs/heads/master
OnTheMap/Data/DTO/UpdateLocationDTO.swift
mit
1
// // UpdateLocationDTO.swift // OnTheMap // // Created by Jesus Antonio Gil on 23/4/16. // Copyright © 2016 Jesús Antonio Gil. All rights reserved. // import UIKit class UpdateLocationDTO: NSObject { var objectId: String var uniqueKey: String var firstName: String var lastName: String var mapString: String var mediaURL: String var latitude: String var longitude: String init(objectId: String, uniqueKey: String, firstName: String, lastName: String, mapString: String, mediaURL: String, latitude: String, longitude: String) { self.objectId = objectId self.uniqueKey = uniqueKey self.firstName = firstName self.lastName = lastName self.mapString = mapString self.mediaURL = mediaURL self.latitude = latitude self.longitude = longitude } var parameters: String { return objectId } var body: String { return "{\"uniqueKey\": \"\(uniqueKey)\", \"firstName\": \"\(firstName)\", \"lastName\": \"\(lastName)\",\"mapString\": \"\(mapString)\", \"mediaURL\": \"\(mediaURL)\",\"latitude\": \(latitude), \"longitude\": \(longitude)}" } }
cc7cbfaed81d3ef08ed905783018d441
26.860465
232
0.623539
false
false
false
false
6ag/WeiboSwift-mvvm
refs/heads/master
WeiboSwift/Classes/View/Main/NavigationController.swift
mit
1
// // NavigationViewController.swift // WeiboSwift // // Created by 周剑峰 on 2017/1/16. // Copyright © 2017年 周剑峰. All rights reserved. // import UIKit class NavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() // 隐藏系统的导航栏 navigationBar.isHidden = true } } extension NavigationController { /// 拦截系统push操作 /// /// - Parameters: /// - viewController: 即将进入的界面 /// - animated: 是否有push动画 override func pushViewController(_ viewController: UIViewController, animated: Bool) { if childViewControllers.count > 0 { // 隐藏底部tabBar viewController.hidesBottomBarWhenPushed = true // 设置导航栏返回按钮 if let vc = viewController as? BaseViewController { var title = "返回" if childViewControllers.count == 1 { title = childViewControllers.first?.title ?? "返回" } vc.navItem.leftBarButtonItem = UIBarButtonItem(title: title, target: self, action: #selector(back), isBack: true) } } super.pushViewController(viewController, animated: animated) } /// 返回上一级界面 @objc private func back() { popViewController(animated: true) } }
f45c3e76044403edd6c4346a2d4e6143
23.666667
129
0.558321
false
false
false
false
huonw/swift
refs/heads/master
stdlib/public/SDK/Foundation/Data.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 // //===----------------------------------------------------------------------===// #if DEPLOYMENT_RUNTIME_SWIFT #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import CoreFoundation internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) { munmap(mem, length) } internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) { free(mem) } internal func __NSDataIsCompact(_ data: NSData) -> Bool { return data._isCompact() } #else @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims import _SwiftCoreFoundationOverlayShims internal func __NSDataIsCompact(_ data: NSData) -> Bool { if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { return data._isCompact() } else { var compact = true let len = data.length data.enumerateBytes { (_, byteRange, stop) in if byteRange.length != len { compact = false } stop.pointee = true } return compact } } #endif @usableFromInline internal final class _DataStorage { @usableFromInline enum Backing { // A mirror of the Objective-C implementation that is suitable to inline in Swift case swift // these two storage points for immutable and mutable data are reserved for references that are returned by "known" // cases from Foundation in which implement the backing of struct Data, these have signed up for the concept that // the backing bytes/mutableBytes pointer does not change per call (unless mutated) as well as the length is ok // to be cached, this means that as long as the backing reference is retained no further objc_msgSends need to be // dynamically dispatched out to the reference. case immutable(NSData) // This will most often (perhaps always) be NSConcreteData case mutable(NSMutableData) // This will often (perhaps always) be NSConcreteMutableData // These are reserved for foreign sources where neither Swift nor Foundation are fully certain whom they belong // to from an object inheritance standpoint, this means that all bets are off and the values of bytes, mutableBytes, // and length cannot be cached. This also means that all methods are expected to dynamically dispatch out to the // backing reference. case customReference(NSData) // tracks data references that are only known to be immutable case customMutableReference(NSMutableData) // tracks data references that are known to be mutable } static let maxSize = Int.max >> 1 static let vmOpsThreshold = NSPageSize() * 4 static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? { if clear { return calloc(1, size) } else { return malloc(size) } } @usableFromInline static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) { var dest = dest_ var source = source_ var num = num_ if _DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 { let pages = NSRoundDownToMultipleOfPageSize(num) NSCopyMemoryPages(source!, dest, pages) source = source!.advanced(by: pages) dest = dest.advanced(by: pages) num -= pages } if num > 0 { memmove(dest, source!, num) } } static func shouldAllocateCleared(_ size: Int) -> Bool { return (size > (128 * 1024)) } @usableFromInline var _bytes: UnsafeMutableRawPointer? @usableFromInline var _length: Int @usableFromInline var _capacity: Int @usableFromInline var _needToZero: Bool @usableFromInline var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? @usableFromInline var _backing: Backing = .swift @usableFromInline var _offset: Int @usableFromInline var bytes: UnsafeRawPointer? { @inlinable get { switch _backing { case .swift: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .immutable: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .mutable: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .customReference(let d): return d.bytes.advanced(by: -_offset) case .customMutableReference(let d): return d.bytes.advanced(by: -_offset) } } } @usableFromInline @discardableResult func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customReference(let d): if __NSDataIsCompact(d) { let len = d.length guard len > 0 else { return try apply(UnsafeRawBufferPointer(start: nil, count: 0)) } return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len))) } else { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count) var enumerated = 0 d.enumerateBytes { (ptr, byteRange, stop) in if byteRange.upperBound - _offset < range.lowerBound { // before the range that we are looking for... } else if byteRange.lowerBound - _offset > range.upperBound { stop.pointee = true // we are past the range in question so we need to stop } else { // the byteRange somehow intersects the range in question that we are looking for... let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound) let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound) let len = upper - lower memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len) enumerated += len if upper == range.upperBound { stop.pointee = true } } } return try apply(UnsafeRawBufferPointer(buffer)) } case .customMutableReference(let d): if __NSDataIsCompact(d) { let len = d.length guard len > 0 else { return try apply(UnsafeRawBufferPointer(start: nil, count: 0)) } return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len))) } else { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count) var enumerated = 0 d.enumerateBytes { (ptr, byteRange, stop) in if byteRange.upperBound - _offset < range.lowerBound { // before the range that we are looking for... } else if byteRange.lowerBound - _offset > range.upperBound { stop.pointee = true // we are past the range in question so we need to stop } else { // the byteRange somehow intersects the range in question that we are looking for... let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound) let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound) let len = upper - lower memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len) enumerated += len if upper == range.upperBound { stop.pointee = true } } } return try apply(UnsafeRawBufferPointer(buffer)) } } } @usableFromInline @discardableResult func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { switch _backing { case .swift: fallthrough case .mutable: return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customMutableReference(let d): let len = d.length return try apply(UnsafeMutableRawBufferPointer(start: d.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len))) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData _backing = .mutable(data) _bytes = data.mutableBytes return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customReference(let d): let data = d.mutableCopy() as! NSMutableData _backing = .customMutableReference(data) let len = data.length return try apply(UnsafeMutableRawBufferPointer(start: data.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len))) } } var mutableBytes: UnsafeMutableRawPointer? { @inlinable get { switch _backing { case .swift: return _bytes?.advanced(by: -_offset) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .mutable(data) _bytes = data.mutableBytes return _bytes?.advanced(by: -_offset) case .mutable: return _bytes?.advanced(by: -_offset) case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .customMutableReference(data) return data.mutableBytes.advanced(by: -_offset) case .customMutableReference(let d): return d.mutableBytes.advanced(by: -_offset) } } } @usableFromInline var length: Int { @inlinable get { switch _backing { case .swift: return _length case .immutable: return _length case .mutable: return _length case .customReference(let d): return d.length case .customMutableReference(let d): return d.length } } @inlinable set { setLength(newValue) } } func _freeBytes() { if let bytes = _bytes { if let dealloc = _deallocator { dealloc(bytes, length) } else { free(bytes) } } } func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) { var stopv: Bool = false var data: NSData switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.count, _length)), 0, &stopv) return case .customReference(let d): data = d break case .customMutableReference(let d): data = d break } data.enumerateBytes { (ptr, region, stop) in // any region that is not in the range should be skipped guard range.contains(region.lowerBound) || range.contains(region.upperBound) else { return } var regionAdjustment = 0 if region.lowerBound < range.lowerBound { regionAdjustment = range.lowerBound - (region.lowerBound - _offset) } let bytePtr = ptr.advanced(by: regionAdjustment).assumingMemoryBound(to: UInt8.self) let effectiveLength = Swift.min((region.location - _offset) + region.length, range.upperBound) - (region.location - _offset) block(UnsafeBufferPointer(start: bytePtr, count: effectiveLength - regionAdjustment), region.location + regionAdjustment - _offset, &stopv) if stopv { stop.pointee = true } } } @usableFromInline @inline(never) func _grow(_ newLength: Int, _ clear: Bool) { let cap = _capacity var additionalCapacity = (newLength >> (_DataStorage.vmOpsThreshold <= newLength ? 2 : 1)) if Int.max - additionalCapacity < newLength { additionalCapacity = 0 } var newCapacity = Swift.max(cap, newLength + additionalCapacity) let origLength = _length var allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity) var newBytes: UnsafeMutableRawPointer? = nil if _bytes == nil { newBytes = _DataStorage.allocate(newCapacity, allocateCleared) if newBytes == nil { /* Try again with minimum length */ allocateCleared = clear && _DataStorage.shouldAllocateCleared(newLength) newBytes = _DataStorage.allocate(newLength, allocateCleared) } } else { let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4) if allocateCleared && tryCalloc { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } /* Where calloc/memmove/free fails, realloc might succeed */ if newBytes == nil { allocateCleared = false if _deallocator != nil { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() _deallocator = nil } } else { newBytes = realloc(_bytes!, newCapacity) } } /* Try again with minimum length */ if newBytes == nil { newCapacity = newLength allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity) if allocateCleared && tryCalloc { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } if newBytes == nil { allocateCleared = false newBytes = realloc(_bytes!, newCapacity) } } } if newBytes == nil { /* Could not allocate bytes */ // At this point if the allocation cannot occur the process is likely out of memory // and Bad-Things™ are going to happen anyhow fatalError("unable to allocate memory for length (\(newLength))") } if origLength < newLength && clear && !allocateCleared { memset(newBytes!.advanced(by: origLength), 0, newLength - origLength) } /* _length set by caller */ _bytes = newBytes _capacity = newCapacity /* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */ _needToZero = !allocateCleared } @inlinable func setLength(_ length: Int) { switch _backing { case .swift: let origLength = _length let newLength = length if _capacity < newLength || _bytes == nil { _grow(newLength, true) } else if origLength < newLength && _needToZero { memset(_bytes! + origLength, 0, newLength - origLength) } else if newLength < origLength { _needToZero = true } _length = newLength case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .mutable(data) _length = length _bytes = data.mutableBytes case .mutable(let d): d.length = length _length = length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .customMutableReference(data) case .customMutableReference(let d): d.length = length } } @inlinable func append(_ bytes: UnsafeRawPointer, length: Int) { precondition(length >= 0, "Length of appending bytes must not be negative") switch _backing { case .swift: let origLength = _length let newLength = origLength + length if _capacity < newLength || _bytes == nil { _grow(newLength, false) } _length = newLength _DataStorage.move(_bytes!.advanced(by: origLength), bytes, length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.append(bytes, length: length) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.append(bytes, length: length) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.append(bytes, length: length) _backing = .customMutableReference(data) case .customMutableReference(let d): d.append(bytes, length: length) } } // fast-path for appending directly from another data storage @inlinable func append(_ otherData: _DataStorage, startingAt start: Int, endingAt end: Int) { let otherLength = otherData.length if otherLength == 0 { return } if let bytes = otherData.bytes { append(bytes.advanced(by: start), length: end - start) } } @inlinable func append(_ otherData: Data) { otherData.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, _, _) in append(buffer.baseAddress!, length: buffer.count) } } @inlinable func increaseLength(by extraLength: Int) { if extraLength == 0 { return } switch _backing { case .swift: let origLength = _length let newLength = origLength + extraLength if _capacity < newLength || _bytes == nil { _grow(newLength, true) } else if _needToZero { memset(_bytes!.advanced(by: origLength), 0, extraLength) } _length = newLength case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.increaseLength(by: extraLength) _backing = .mutable(data) _length += extraLength _bytes = data.mutableBytes case .mutable(let d): d.increaseLength(by: extraLength) _length += extraLength _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.increaseLength(by: extraLength) _backing = .customReference(data) case .customMutableReference(let d): d.increaseLength(by: extraLength) } } @usableFromInline func get(_ index: Int) -> UInt8 { switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee case .customReference(let d): if __NSDataIsCompact(d) { return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } else { var byte: UInt8 = 0 d.enumerateBytes { (ptr, range, stop) in if NSLocationInRange(index, range) { let offset = index - range.location - _offset byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee stop.pointee = true } } return byte } case .customMutableReference(let d): if __NSDataIsCompact(d) { return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } else { var byte: UInt8 = 0 d.enumerateBytes { (ptr, range, stop) in if NSLocationInRange(index, range) { let offset = index - range.location - _offset byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee stop.pointee = true } } return byte } } } @inlinable func set(_ index: Int, to value: UInt8) { switch _backing { case .swift: fallthrough case .mutable: _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value default: var theByte = value let range = NSRange(location: index, length: 1) replaceBytes(in: range, with: &theByte, length: 1) } } @inlinable func replaceBytes(in range: NSRange, with bytes: UnsafeRawPointer?) { if range.length == 0 { return } switch _backing { case .swift: if _length < range.location + range.length { let newLength = range.location + range.length if _capacity < newLength { _grow(newLength, false) } _length = newLength } _DataStorage.move(_bytes!.advanced(by: range.location - _offset), bytes!, range.length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _backing = .customMutableReference(data) case .customMutableReference(let d): d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) } } @inlinable func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) { let range = NSRange(location: range_.location - _offset, length: range_.length) let currentLength = _length let resultingLength = currentLength - range.length + replacementLength switch _backing { case .swift: let shift = resultingLength - currentLength var mutableBytes = _bytes if resultingLength > currentLength { setLength(resultingLength) mutableBytes = _bytes! } /* shift the trailing bytes */ let start = range.location let length = range.length if shift != 0 { memmove(mutableBytes! + start + replacementLength, mutableBytes! + start + length, currentLength - start - length) } if replacementLength != 0 { if let replacementBytes = replacementBytes { memmove(mutableBytes! + start, replacementBytes, replacementLength) } else { memset(mutableBytes! + start, 0, replacementLength) } } if resultingLength < currentLength { setLength(resultingLength) } case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .mutable(d) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .customMutableReference(data) case .customMutableReference(let d): d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) } } @inlinable func resetBytes(in range_: NSRange) { let range = NSRange(location: range_.location - _offset, length: range_.length) if range.length == 0 { return } switch _backing { case .swift: if _length < range.location + range.length { let newLength = range.location + range.length if _capacity < newLength { _grow(newLength, false) } _length = newLength } memset(_bytes!.advanced(by: range.location), 0, range.length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.resetBytes(in: range) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.resetBytes(in: range) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.resetBytes(in: range) _backing = .customMutableReference(data) case .customMutableReference(let d): d.resetBytes(in: range) } } @usableFromInline convenience init() { self.init(capacity: 0) } @usableFromInline init(length: Int) { precondition(length < _DataStorage.maxSize) var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } let clear = _DataStorage.shouldAllocateCleared(length) _bytes = _DataStorage.allocate(capacity, clear)! _capacity = capacity _needToZero = !clear _length = 0 _offset = 0 setLength(length) } @usableFromInline init(capacity capacity_: Int) { var capacity = capacity_ precondition(capacity < _DataStorage.maxSize) if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = 0 _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _offset = 0 } @usableFromInline init(bytes: UnsafeRawPointer?, length: Int) { precondition(length < _DataStorage.maxSize) _offset = 0 if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil } else if _DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = _DataStorage.allocate(length, false)! _DataStorage.move(_bytes!, bytes, length) } else { var capacity = length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _DataStorage.move(_bytes!, bytes, length) } } @usableFromInline init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) { precondition(length < _DataStorage.maxSize) _offset = offset if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil if let dealloc = deallocator, let bytes_ = bytes { dealloc(bytes_, length) } } else if !copy { _capacity = length _length = length _needToZero = false _bytes = bytes _deallocator = deallocator } else if _DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = _DataStorage.allocate(length, false)! _DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } else { var capacity = length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } } @usableFromInline init(immutableReference: NSData, offset: Int) { _offset = offset _bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes) _capacity = 0 _needToZero = false _length = immutableReference.length _backing = .immutable(immutableReference) } @usableFromInline init(mutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = mutableReference.mutableBytes _capacity = 0 _needToZero = false _length = mutableReference.length _backing = .mutable(mutableReference) } @usableFromInline init(customReference: NSData, offset: Int) { _offset = offset _bytes = nil _capacity = 0 _needToZero = false _length = 0 _backing = .customReference(customReference) } @usableFromInline init(customMutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = nil _capacity = 0 _needToZero = false _length = 0 _backing = .customMutableReference(customMutableReference) } deinit { switch _backing { case .swift: _freeBytes() default: break } } @inlinable func mutableCopy(_ range: Range<Int>) -> _DataStorage { switch _backing { case .swift: return _DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.count, copy: true, deallocator: nil, offset: range.lowerBound) case .immutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .mutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .customReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .customMutableReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } } } func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T { if range.isEmpty { return try work(NSData()) // zero length data can be optimized as a singleton } switch _backing { case .swift: return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) case .immutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) } return try work(d) case .mutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) } return try work(d) case .customReference(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false)) } return try work(d) case .customMutableReference(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false)) } return try work(d) } } func bridgedReference(_ range: Range<Int>) -> NSData { if range.isEmpty { return NSData() // zero length data can be optimized as a singleton } switch _backing { case .swift: return _NSSwiftData(backing: self, range: range) case .immutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return _NSSwiftData(backing: self, range: range) } return d case .mutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return _NSSwiftData(backing: self, range: range) } return d case .customReference(let d): guard range.lowerBound == 0 && range.upperBound == d.length else { return _NSSwiftData(backing: self, range: range) } return d case .customMutableReference(let d): guard range.lowerBound == 0 && range.upperBound == d.length else { return d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC() } return d.copy() as! NSData } } @usableFromInline func subdata(in range: Range<Data.Index>) -> Data { switch _backing { case .customReference(let d): return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count)) case .customMutableReference(let d): return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count)) default: return Data(bytes: _bytes!.advanced(by: range.lowerBound - _offset), count: range.count) } } } internal class _NSSwiftData : NSData { var _backing: _DataStorage! var _range: Range<Data.Index>! convenience init(backing: _DataStorage, range: Range<Data.Index>) { self.init() _backing = backing _range = range } override var length: Int { return _range.count } override var bytes: UnsafeRawPointer { // NSData's byte pointer methods are not annotated for nullability correctly // (but assume non-null by the wrapping macro guards). This placeholder value // is to work-around this bug. Any indirection to the underlying bytes of an NSData // with a length of zero would have been a programmer error anyhow so the actual // return value here is not needed to be an allocated value. This is specifically // needed to live like this to be source compatible with Swift3. Beyond that point // this API may be subject to correction. guard let bytes = _backing.bytes else { return UnsafeRawPointer(bitPattern: 0xBAD0)! } return bytes.advanced(by: _range.lowerBound) } override func copy(with zone: NSZone? = nil) -> Any { return self } override func mutableCopy(with zone: NSZone? = nil) -> Any { return NSMutableData(bytes: bytes, length: length) } #if !DEPLOYMENT_RUNTIME_SWIFT @objc override func _isCompact() -> Bool { return true } #endif #if DEPLOYMENT_RUNTIME_SWIFT override func _providesConcreteBacking() -> Bool { return true } #else @objc(_providesConcreteBacking) func _providesConcreteBacking() -> Bool { return true } #endif } public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection { public typealias ReferenceType = NSData public typealias ReadingOptions = NSData.ReadingOptions public typealias WritingOptions = NSData.WritingOptions public typealias SearchOptions = NSData.SearchOptions public typealias Base64EncodingOptions = NSData.Base64EncodingOptions public typealias Base64DecodingOptions = NSData.Base64DecodingOptions public typealias Index = Int public typealias Indices = Range<Int> @usableFromInline internal var _backing : _DataStorage @usableFromInline internal var _sliceRange: Range<Index> // A standard or custom deallocator for `Data`. /// /// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated. public enum Deallocator { /// Use a virtual memory deallocator. #if !DEPLOYMENT_RUNTIME_SWIFT case virtualMemory #endif /// Use `munmap`. case unmap /// Use `free`. case free /// Do nothing upon deallocation. case none /// A custom deallocator. case custom((UnsafeMutableRawPointer, Int) -> Void) fileprivate var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) { #if DEPLOYMENT_RUNTIME_SWIFT switch self { case .unmap: return { __NSDataInvokeDeallocatorUnmap($0, $1) } case .free: return { __NSDataInvokeDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return { (ptr, len) in b(ptr, len) } } #else switch self { case .virtualMemory: return { NSDataDeallocatorVM($0, $1) } case .unmap: return { NSDataDeallocatorUnmap($0, $1) } case .free: return { NSDataDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return { (ptr, len) in b(ptr, len) } } #endif } } // MARK: - // MARK: Init methods /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. public init(bytes: UnsafeRawPointer, count: Int) { _backing = _DataStorage(bytes: bytes, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) { let count = MemoryLayout<SourceType>.stride * buffer.count _backing = _DataStorage(bytes: buffer.baseAddress, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) { let count = MemoryLayout<SourceType>.stride * buffer.count _backing = _DataStorage(bytes: buffer.baseAddress, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with a repeating byte pattern /// /// - parameter repeatedValue: A byte to initialize the pattern /// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue public init(repeating repeatedValue: UInt8, count: Int) { self.init(count: count) withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Void in memset(bytes, Int32(repeatedValue), count) } } /// Initialize a `Data` with the specified size. /// /// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. /// /// This method sets the `count` of the data to 0. /// /// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page. /// /// - parameter capacity: The size of the data. public init(capacity: Int) { _backing = _DataStorage(capacity: capacity) _sliceRange = 0..<0 } /// Initialize a `Data` with the specified count of zeroed bytes. /// /// - parameter count: The number of bytes the data initially contains. public init(count: Int) { _backing = _DataStorage(length: count) _sliceRange = 0..<count } /// Initialize an empty `Data`. public init() { _backing = _DataStorage(length: 0) _sliceRange = 0..<0 } /// Initialize a `Data` without copying the bytes. /// /// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed. /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`. public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) { let whichDeallocator = deallocator._deallocator _backing = _DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0) _sliceRange = 0..<count } /// Initialize a `Data` with the contents of a `URL`. /// /// - parameter url: The `URL` to read. /// - parameter options: Options for the read operation. Default value is `[]`. /// - throws: An error in the Cocoa domain, if `url` cannot be read. public init(contentsOf url: URL, options: Data.ReadingOptions = []) throws { let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue)) _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } /// Initialize a `Data` from a Base-64 encoded String using the given options. /// /// Returns nil when the input is not recognized as valid Base-64. /// - parameter base64String: The string to parse. /// - parameter options: Encoding options. Default value is `[]`. public init?(base64Encoded base64String: String, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) { _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } else { return nil } } /// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`. /// /// Returns nil when the input is not recognized as valid Base-64. /// /// - parameter base64Data: Base-64, UTF-8 encoded input data. /// - parameter options: Decoding options. Default value is `[]`. public init?(base64Encoded base64Data: Data, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) { _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } else { return nil } } /// Initialize a `Data` by adopting a reference type. /// /// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation. /// /// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass. /// /// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`. public init(referencing reference: NSData) { #if DEPLOYMENT_RUNTIME_SWIFT let providesConcreteBacking = reference._providesConcreteBacking() #else let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false #endif if providesConcreteBacking { _backing = _DataStorage(immutableReference: reference.copy() as! NSData, offset: 0) _sliceRange = 0..<reference.length } else { _backing = _DataStorage(customReference: reference.copy() as! NSData, offset: 0) _sliceRange = 0..<reference.length } } // slightly faster paths for common sequences @inlinable public init<S: Sequence>(_ elements: S) where S.Iterator.Element == UInt8 { let backing = _DataStorage(capacity: Swift.max(elements.underestimatedCount, 1)) var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: backing._bytes?.bindMemory(to: UInt8.self, capacity: backing._capacity), count: backing._capacity)) backing._length = endIndex while var element = iter.next() { backing.append(&element, length: 1) } self.init(backing: backing, range: 0..<backing._length) } @inlinable public init<S: Sequence>(bytes elements: S) where S.Iterator.Element == UInt8 { self.init(elements) } @usableFromInline internal init(backing: _DataStorage, range: Range<Index>) { _backing = backing _sliceRange = range } @usableFromInline internal func _validateIndex(_ index: Int, message: String? = nil) { precondition(_sliceRange.contains(index), message ?? "Index \(index) is out of bounds of range \(_sliceRange)") } @usableFromInline internal func _validateRange<R: RangeExpression>(_ range: R) where R.Bound == Int { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let r = range.relative(to: lower..<upper) precondition(r.lowerBound >= _sliceRange.lowerBound && r.lowerBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)") precondition(r.upperBound >= _sliceRange.lowerBound && r.upperBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)") } // ----------------------------------- // MARK: - Properties and Functions /// The number of bytes in the data. public var count: Int { get { return _sliceRange.count } set { precondition(count >= 0, "count must not be negative") if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.length = newValue _sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + newValue) } } /// Access the bytes in the data. /// /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try _backing.withUnsafeBytes(in: _sliceRange) { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!) } } /// Mutate the bytes in the data. /// /// This function assumes that you are mutating the contents. /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } return try _backing.withUnsafeMutableBytes(in: _sliceRange) { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!) } } // MARK: - // MARK: Copy Bytes /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { precondition(count >= 0, "count of bytes to copy must not be negative") if count == 0 { return } _backing.withUnsafeBytes(in: _sliceRange) { memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(count, $0.count)) } } private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) { if range.length == 0 { return } _backing.withUnsafeBytes(in: range.lowerBound..<range.upperBound) { memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(range.length, $0.count)) } } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) { _copyBytesHelper(to: pointer, from: NSRange(range)) } // Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : Range<Index> if let r = range { guard !r.isEmpty else { return 0 } copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } _validateRange(copyRange) guard !copyRange.isEmpty else { return 0 } let nsRange = NSRange(location: copyRange.lowerBound, length: copyRange.upperBound - copyRange.lowerBound) _copyBytesHelper(to: buffer.baseAddress!, from: nsRange) return copyRange.count } // MARK: - #if !DEPLOYMENT_RUNTIME_SWIFT private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool { // Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation. if !options.contains(.atomic) { #if os(macOS) return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max) #else return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max) #endif } else { return false } } #endif /// Write the contents of the `Data` to a location. /// /// - parameter url: The location to write the data into. /// - parameter options: Options for writing the data. Default value is `[]`. /// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`. public func write(to url: URL, options: Data.WritingOptions = []) throws { try _backing.withInteriorPointerReference(_sliceRange) { #if DEPLOYMENT_RUNTIME_SWIFT try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue)) #else if _shouldUseNonAtomicWriteReimplementation(options: options) { var error: NSError? = nil guard __NSDataWriteToURL($0, url, options, &error) else { throw error! } } else { try $0.write(to: url, options: options) } #endif } } // MARK: - /// Find the given `Data` in the content of this `Data`. /// /// - parameter dataToFind: The data to be searched for. /// - parameter options: Options for the search. Default value is `[]`. /// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data. /// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found. /// - precondition: `range` must be in the bounds of the Data. public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? { let nsRange : NSRange if let r = range { _validateRange(r) nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound) } else { nsRange = NSRange(location: 0, length: count) } let result = _backing.withInteriorPointerReference(_sliceRange) { $0.range(of: dataToFind, options: options, in: nsRange) } if result.location == NSNotFound { return nil } return (result.location + startIndex)..<((result.location + startIndex) + result.length) } /// Enumerate the contents of the data. /// /// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes. /// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`. public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { _backing.enumerateBytes(in: _sliceRange, block) } @inlinable internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { if buffer.isEmpty { return } if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.replaceBytes(in: NSRange(location: _sliceRange.upperBound, length: _backing.length - (_sliceRange.upperBound - _backing._offset)), with: buffer.baseAddress, length: buffer.count * MemoryLayout<SourceType>.stride) _sliceRange = _sliceRange.lowerBound..<(_sliceRange.upperBound + buffer.count * MemoryLayout<SourceType>.stride) } public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { if count == 0 { return } _append(UnsafeBufferPointer(start: bytes, count: count)) } public mutating func append(_ other: Data) { other.enumerateBytes { (buffer, _, _) in _append(buffer) } } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { _append(buffer) } public mutating func append(contentsOf bytes: [UInt8]) { bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in _append(buffer) } } @inlinable public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Iterator.Element { let underestimatedCount = Swift.max(newElements.underestimatedCount, 1) _withStackOrHeapBuffer(underestimatedCount) { (buffer) in let capacity = buffer.pointee.capacity let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity) var (iter, endIndex) = newElements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity)) _append(UnsafeBufferPointer(start: base, count: endIndex)) while var element = iter.next() { append(&element, count: 1) } } } // MARK: - /// Set a region of the data to `0`. /// /// If `range` exceeds the bounds of the data, then the data is resized to fit. /// - parameter range: The range in the data to set to `0`. public mutating func resetBytes(in range: Range<Index>) { // it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth) precondition(range.lowerBound >= 0, "Ranges must not be negative bounds") precondition(range.upperBound >= 0, "Ranges must not be negative bounds") let range = NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.resetBytes(in: range) if _sliceRange.upperBound < range.upperBound { _sliceRange = _sliceRange.lowerBound..<range.upperBound } } /// Replace a region of bytes in the data with new data. /// /// This will resize the data if required, to fit the entire contents of `data`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append. /// - parameter data: The replacement data. public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) { let cnt = data.count data.withUnsafeBytes { replaceSubrange(subrange, with: $0, count: cnt) } } /// Replace a region of bytes in the data with new bytes from a buffer. /// /// This will resize the data if required, to fit the entire contents of `buffer`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter buffer: The replacement bytes. public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) { guard !buffer.isEmpty else { return } replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride) } /// Replace a region of bytes in the data with new bytes from a collection. /// /// This will resize the data if required, to fit the entire contents of `newElements`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter newElements: The replacement bytes. public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element { _validateRange(subrange) let totalCount: Int = numericCast(newElements.count) _withStackOrHeapBuffer(totalCount) { conditionalBuffer in let buffer = UnsafeMutableBufferPointer(start: conditionalBuffer.pointee.memory.assumingMemoryBound(to: UInt8.self), count: totalCount) var (iterator, index) = newElements._copyContents(initializing: buffer) while let byte = iterator.next() { buffer[index] = byte index = buffer.index(after: index) } replaceSubrange(subrange, with: conditionalBuffer.pointee.memory, count: totalCount) } } public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) { _validateRange(subrange) let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } let upper = _sliceRange.upperBound _backing.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingUpper = upper - nsRange.length + cnt _sliceRange = _sliceRange.lowerBound..<resultingUpper } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. public func subdata(in range: Range<Index>) -> Data { _validateRange(range) if isEmpty { return Data() } return _backing.subdata(in: range) } // MARK: - // /// Returns a Base-64 encoded string. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded string. public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String { return _backing.withInteriorPointerReference(_sliceRange) { return $0.base64EncodedString(options: options) } } /// Returns a Base-64 encoded `Data`. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded data. public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data { return _backing.withInteriorPointerReference(_sliceRange) { return $0.base64EncodedData(options: options) } } // MARK: - // /// The hash value for the data. public var hashValue: Int { var hashValue = 0 let hashRange: Range<Int> = _sliceRange.lowerBound..<Swift.min(_sliceRange.lowerBound + 80, _sliceRange.upperBound) _withStackOrHeapBuffer(hashRange.count + 1) { buffer in if !hashRange.isEmpty { _backing.withUnsafeBytes(in: hashRange) { memcpy(buffer.pointee.memory, $0.baseAddress!, hashRange.count) } } hashValue = Int(bitPattern: CFHashBytes(buffer.pointee.memory.assumingMemoryBound(to: UInt8.self), hashRange.count)) } return hashValue } public func advanced(by amount: Int) -> Data { _validateIndex(startIndex + amount) let length = count - amount precondition(length > 0) return withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data in return Data(bytes: ptr.advanced(by: amount), count: length) } } // MARK: - // MARK: - // MARK: Index and Subscript /// Sets or returns the byte at the specified index. public subscript(index: Index) -> UInt8 { get { _validateIndex(index) return _backing.get(index) } set { _validateIndex(index) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.set(index, to: newValue) } } public subscript(bounds: Range<Index>) -> Data { get { _validateRange(bounds) return Data(backing: _backing, range: bounds) } set { replaceSubrange(bounds, with: newValue) } } public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data where R.Bound: FixedWidthInteger, R.Bound.Stride : SignedInteger { get { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let range = rangeExpression.relative(to: lower..<upper) let start: Int = numericCast(range.lowerBound) let end: Int = numericCast(range.upperBound) let r: Range<Int> = start..<end _validateRange(r) return Data(backing: _backing, range: r) } set { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let range = rangeExpression.relative(to: lower..<upper) let start: Int = numericCast(range.lowerBound) let end: Int = numericCast(range.upperBound) let r: Range<Int> = start..<end _validateRange(r) replaceSubrange(r, with: newValue) } } /// The start `Index` in the data. public var startIndex: Index { get { return _sliceRange.lowerBound } } /// The end `Index` into the data. /// /// This is the "one-past-the-end" position, and will always be equal to the `count`. public var endIndex: Index { get { return _sliceRange.upperBound } } public func index(before i: Index) -> Index { return i - 1 } public func index(after i: Index) -> Index { return i + 1 } public var indices: Range<Int> { get { return startIndex..<endIndex } } public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) { guard !isEmpty else { return (makeIterator(), buffer.startIndex) } guard let p = buffer.baseAddress else { preconditionFailure("Attempt to copy contents into nil buffer pointer") } let cnt = count precondition(cnt <= buffer.count, "Insufficient space allocated to copy Data contents") withUnsafeBytes { p.initialize(from: $0, count: cnt) } return (Iterator(endOf: self), buffer.index(buffer.startIndex, offsetBy: cnt)) } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. public func makeIterator() -> Data.Iterator { return Iterator(self) } public struct Iterator : IteratorProtocol { // Both _data and _endIdx should be 'let' rather than 'var'. // They are 'var' so that the stored properties can be read // independently of the other contents of the struct. This prevents // an exclusivity violation when reading '_endIdx' and '_data' // while simultaneously mutating '_buffer' with the call to // withUnsafeMutablePointer(). Once we support accessing struct // let properties independently we should make these variables // 'let' again. private var _data: Data private var _buffer: ( UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) private var _idx: Data.Index private var _endIdx: Data.Index fileprivate init(_ data: Data) { _data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = data.startIndex _endIdx = data.endIndex } fileprivate init(endOf data: Data) { self._data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = data.endIndex _endIdx = data.endIndex } public mutating func next() -> UInt8? { guard _idx < _endIdx else { return nil } defer { _idx += 1 } let bufferSize = MemoryLayout.size(ofValue: _buffer) return withUnsafeMutablePointer(to: &_buffer) { ptr_ in let ptr = UnsafeMutableRawPointer(ptr_).assumingMemoryBound(to: UInt8.self) let bufferIdx = (_idx - _data.startIndex) % bufferSize if bufferIdx == 0 { // populate the buffer _data.copyBytes(to: ptr, from: _idx..<(_endIdx - _idx > bufferSize ? _idx + bufferSize : _endIdx)) } return ptr[bufferIdx] } } } // MARK: - // @available(*, unavailable, renamed: "count") public var length: Int { get { fatalError() } set { fatalError() } } @available(*, unavailable, message: "use withUnsafeBytes instead") public var bytes: UnsafeRawPointer { fatalError() } @available(*, unavailable, message: "use withUnsafeMutableBytes instead") public var mutableBytes: UnsafeMutableRawPointer { fatalError() } /// Returns `true` if the two `Data` arguments are equal. public static func ==(d1 : Data, d2 : Data) -> Bool { let backing1 = d1._backing let backing2 = d2._backing if backing1 === backing2 { if d1._sliceRange == d2._sliceRange { return true } } let length1 = d1.count if length1 != d2.count { return false } if backing1.bytes == backing2.bytes { if d1._sliceRange == d2._sliceRange { return true } } if length1 > 0 { return d1.withUnsafeBytes { (b1) in return d2.withUnsafeBytes { (b2) in return memcmp(b1, b2, length1) == 0 } } } return true } } extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { /// A human-readable description for the data. public var description: String { return "\(self.count) bytes" } /// A human-readable debug description for the data. public var debugDescription: String { return self.description } public var customMirror: Mirror { let nBytes = self.count var children: [(label: String?, value: Any)] = [] children.append((label: "count", value: nBytes)) self.withUnsafeBytes { (bytes : UnsafePointer<UInt8>) in children.append((label: "pointer", value: bytes)) } // Minimal size data is output as an array if nBytes < 64 { children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)]))) } let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct) return m } } extension Data { @available(*, unavailable, renamed: "copyBytes(to:count:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { } @available(*, unavailable, renamed: "copyBytes(to:from:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { } } /// Provides bridging functionality for struct Data to class NSData and vice-versa. extension Data : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSData { return _backing.bridgedReference(_sliceRange) } public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data { guard let src = source else { return Data() } return Data(referencing: src) } } extension NSData : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self)) } } extension Data : Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() // It's more efficient to pre-allocate the buffer if we can. if let count = container.count { self.init(count: count) // Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space. // We don't want to write past the end of what we allocated. for i in 0 ..< count { let byte = try container.decode(UInt8.self) self[i] = byte } } else { self.init() } while !container.isAtEnd { var byte = try container.decode(UInt8.self) self.append(&byte, count: 1) } } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() // Since enumerateBytes does not rethrow, we need to catch the error, stow it away, and rethrow if we stopped. var caughtError: Error? = nil self.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, byteIndex: Data.Index, stop: inout Bool) in do { try container.encode(contentsOf: buffer) } catch { caughtError = error stop = true } } if let error = caughtError { throw error } } }
9480e3ce44211c63fb4151fe757ebd68
40.47255
352
0.593183
false
false
false
false
1457792186/JWSwift
refs/heads/master
CKMnemonic/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift
apache-2.0
5
// // ArrayExtension.swift // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // extension Array { init(reserveCapacity: Int) { self = Array<Element>() self.reserveCapacity(reserveCapacity) } var slice: ArraySlice<Element> { return self[self.startIndex..<self.endIndex] } } extension Array { /** split in chunks with given chunk size */ public func chunks(size chunksize: Int) -> Array<Array<Element>> { var words = Array<Array<Element>>() words.reserveCapacity(count / chunksize) for idx in stride(from: chunksize, through: count, by: chunksize) { words.append(Array(self[idx - chunksize..<idx])) // slow for large table } let remainder = suffix(count % chunksize) if !remainder.isEmpty { words.append(Array(remainder)) } return words } } extension Array where Element == UInt8 { public init(hex: String) { self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount) var buffer: UInt8? var skip = hex.hasPrefix("0x") ? 2 : 0 for char in hex.unicodeScalars.lazy { guard skip == 0 else { skip -= 1 continue } guard char.value >= 48 && char.value <= 102 else { removeAll() return } let v: UInt8 let c: UInt8 = UInt8(char.value) switch c { case let c where c <= 57: v = c - 48 case let c where c >= 65 && c <= 70: v = c - 55 case let c where c >= 97: v = c - 87 default: removeAll() return } if let b = buffer { append(b << 4 | v) buffer = nil } else { buffer = v } } if let b = buffer { append(b) } } }
c7d246c1cce010cef73a0a142fe0216e
33.107143
217
0.574869
false
false
false
false
rhx/SwiftGLib
refs/heads/main
Sources/GLib/Sequence.swift
bsd-2-clause
1
// // Sequence.swift // GLib // // Created by Rene Hexel on 5/1/21. // Copyright © 2021, 2022 Rene Hexel. All rights reserved. // import CGLib public extension SequenceProtocol { /// Return an iterator representing the start index of the sequence @inlinable var startIndex: Int { 0 } /// Return an iterator representing the start index of the sequence @inlinable var endIndex: Int { getEndIter()?.position ?? 0 } /// Return the number of elements in the sequence @inlinable var count: Int { endIndex - startIndex } /// Return an array of indices valid as subscripts into the sequence @inlinable var indices: [Int] { (startIndex..<endIndex).map { $0 } } /// Create an interator over a`Sequence` /// - Returns: a list iterator @inlinable func makeIterator() -> SequenceIterator { SequenceIterator(getBeginIter()) } /// Get the element at the given position /// - Parameter position: The position in the sequence to retrieve the element from @inlinable subscript(position: Int) -> gpointer! { getIterAt(pos: position)!.sequenceGet() } /// Returns the position immediately after the given index. @inlinable func index(after i: Int) -> Int { i + 1 } /// Returns the position immediately before the given index. @inlinable func index(before i: Int) -> Int { i - 1 } } extension Sequence: Swift.Sequence {} extension SequenceRef: Swift.Sequence {} /// A lightweight iterator over a `Sequence` public struct SequenceIterator: IteratorProtocol { public var iterator: SequenceIterRef? /// Constructor for a `SequenceIterator` /// - Parameter ptr: Optional `GSequenceIter` pointer @inlinable init(_ iter: SequenceIterRef?) { iterator = iter } /// Return the next element in the list /// - Returns: a pointer to the next element in the list or `nil` if the end of the list has been reached @inlinable public mutating func next() -> gpointer? { defer { iterator = iterator?.next() } return iterator?.sequenceGet() } } extension SequenceIterRef: Equatable { /// Compare two sequence iterators for equality /// - Parameters: /// - lhs: left hand side sequence iterator to compare /// - rhs: right hand side sequence iterator to compare /// - Returns: `true` iff the two iterators refer to the same element @inlinable public static func == (lhs: SequenceIterRef, rhs: SequenceIterRef) -> Bool { lhs.ptr == rhs.ptr } } extension SequenceIterRef: Comparable { /// Compare two sequence iterator positions /// - Parameters: /// - lhs: left hand side sequence iterator to compare /// - rhs: right hand side sequence iterator to compare /// - Returns: `true` iff the left hand side iterator is positioned before the right hand side iterator @inlinable public static func < (lhs: SequenceIterRef, rhs: SequenceIterRef) -> Bool { lhs.compare(b: rhs) < 0 } }
39bc87e58645d55392e6cfbbe195d7b5
34.305882
109
0.66911
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/IRGen/generic_types.swift
apache-2.0
3
// RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime // REQUIRES: CPU=x86_64 // CHECK: [[A:%T13generic_types1AC]] = type <{ [[REF:%swift.refcounted]], [[INT:%TSi]] }> // CHECK: [[INT]] = type <{ i64 }> // CHECK: [[B:%T13generic_types1BC]] = type <{ [[REF:%swift.refcounted]], [[UNSAFE:%TSp]] }> // CHECK: [[C:%T13generic_types1CC]] = type // CHECK: [[D:%T13generic_types1DC]] = type // CHECK-LABEL: @_T013generic_types1ACMP = internal global // CHECK: %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_A, // CHECK-native-SAME: i32 160, // CHECK-objc-SAME: i32 344, // CHECK-SAME: i16 1, // CHECK-SAME: i16 16, // CHECK-SAME: [{{[0-9]+}} x i8*] zeroinitializer, // CHECK-SAME: void ([[A]]*)* @_T013generic_types1ACfD, // CHECK-SAME: i8** @_T0BoWV, // CHECK-SAME: i64 0, // CHECK-SAME: %swift.type* null, // CHECK-native-SAME: %swift.opaque* null, // CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-SAME: %swift.opaque* null, // CHECK-SAME: i64 1, // CHECK-SAME: i32 3, // CHECK-SAME: i32 0, // CHECK-SAME: i32 24, // CHECK-SAME: i16 7, // CHECK-SAME: i16 0, // CHECK-SAME: i32 152, // CHECK-SAME: i32 16, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null, // CHECK-SAME: i8* null // CHECK-SAME: } // CHECK-LABEL: @_T013generic_types1BCMP = internal global // CHECK-SAME: %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_B, // CHECK-native-SAME: i32 152, // CHECK-objc-SAME: i32 336, // CHECK-SAME: i16 1, // CHECK-SAME: i16 16, // CHECK-SAME: [{{[0-9]+}} x i8*] zeroinitializer, // CHECK-SAME: void ([[B]]*)* @_T013generic_types1BCfD, // CHECK-SAME: i8** @_T0BoWV, // CHECK-SAME: i64 0, // CHECK-SAME: %swift.type* null, // CHECK-native-SAME: %swift.opaque* null, // CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-SAME: %swift.opaque* null, // CHECK-SAME: i64 1, // CHECK-SAME: i32 3, // CHECK-SAME: i32 0, // CHECK-SAME: i32 24, // CHECK-SAME: i16 7, // CHECK-SAME: i16 0, // CHECK-SAME: i32 144, // CHECK-SAME: i32 16, // CHECK-SAME: %swift.type* null // CHECK-SAME: } // CHECK-LABEL: @_T013generic_types1CCMP = internal global // CHECK-SAME: void ([[C]]*)* @_T013generic_types1CCfD, // CHECK-SAME: i8** @_T0BoWV, // CHECK-SAME: i64 0, // CHECK-SAME: %swift.type* null, // CHECK-native-SAME: %swift.opaque* null, // CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-SAME: %swift.opaque* null, // CHECK-SAME: i64 1, // CHECK-SAME: } // CHECK-LABEL: @_T013generic_types1DCMP = internal global // CHECK-SAME: void ([[D]]*)* @_T013generic_types1DCfD, // CHECK-SAME: i8** @_T0BoWV, // CHECK-SAME: i64 0, // CHECK-SAME: %swift.type* null, // CHECK-native-SAME: %swift.opaque* null, // CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-SAME: %swift.opaque* null, // CHECK-SAME: i64 1, // CHECK-SAME: } // CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_A(%swift.type_pattern*, i8**) {{.*}} { // CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type** // CHECK: %T = load %swift.type*, %swift.type** [[T0]], // CHECK-native: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* null) // CHECK-objc: [[T0:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_SwiftObject" // CHECK-objc: [[SUPER:%.*]] = call %objc_class* @swift_rt_swift_getInitializedObjCClass(%objc_class* [[T0]]) // CHECK-objc: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* [[SUPER]]) // CHECK: [[SELF_ARRAY:%.*]] = bitcast %swift.type* [[METADATA]] to i8** // CHECK: [[T1:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 10 // CHECK: [[T0:%.*]] = bitcast %swift.type* %T to i8* // CHECK: store i8* [[T0]], i8** [[T1]], align 8 // CHECK: ret %swift.type* [[METADATA]] // CHECK: } // CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_B(%swift.type_pattern*, i8**) {{.*}} { // CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type** // CHECK: %T = load %swift.type*, %swift.type** [[T0]], // CHECK-native: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* null) // CHECK-objc: [[T0:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_SwiftObject" // CHECK-objc: [[SUPER:%.*]] = call %objc_class* @swift_rt_swift_getInitializedObjCClass(%objc_class* [[T0]]) // CHECK-objc: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* [[SUPER]]) // CHECK: [[SELF_ARRAY:%.*]] = bitcast %swift.type* [[METADATA]] to i8** // CHECK: [[T1:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 10 // CHECK: [[T0:%.*]] = bitcast %swift.type* %T to i8* // CHECK: store i8* [[T0]], i8** [[T1]], align 8 // CHECK: ret %swift.type* [[METADATA]] // CHECK: } class A<T> { var x = 0 func run(_ t: T) {} init(y : Int) {} } class B<T> { var ptr : UnsafeMutablePointer<T> init(ptr: UnsafeMutablePointer<T>) { self.ptr = ptr } deinit { ptr.deinitialize() } } class C<T> : A<Int> {} class D<T> : A<Int> { override func run(_ t: Int) {} } struct E<T> { var x : Int func foo() { bar() } func bar() {} } class ClassA {} class ClassB {} // This type is fixed-size across specializations, but it needs to use // a different implementation in IR-gen so that types match up. // It just asserts if we get it wrong. struct F<T: AnyObject> { var value: T } func testFixed() { var a = F(value: ClassA()).value var b = F(value: ClassB()).value }
4c0033dde56bb441a1e837f8a6105f96
37.337748
147
0.607704
false
false
false
false
ANCHK/event
refs/heads/master
event/AppDelegate.swift
gpl-2.0
1
// // AppDelegate.swift // event // // Created by patrick on 16/1/15. // Copyright (c) 2015 anchk. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } }
9d200ca49a7a857cbdf8242cde92c98c
51.857143
285
0.75045
false
false
false
false
jterhorst/TacoDemoiOS
refs/heads/master
TacoDemoIOS/TacosWebService.swift
mit
1
// // TacosWebService.swift // TacoDemoIOS // // Created by Jason Terhorst on 3/22/16. // Copyright © 2016 Jason Terhorst. All rights reserved. // import Foundation import CoreData // IMPORTANT: Create Endpoint.plist in your project, and define a string "url" at the root of the plist with your Firebase Realtime Database URL // e.g., "https://tacodemo-12345.firebaseio.com" (no trailing slash) // Don't commit this file in Git. // Make sure read/writes are set to true in the Rules tab in Firebase. Auth isn't covered by this demo. class TacosWebService { func endpointUrl() -> String { var format = PropertyListSerialization.PropertyListFormat.xml let url = Bundle.main.path(forResource: "Endpoint", ofType: "plist") var plistData: [String: AnyObject] = [:] do { plistData = try PropertyListSerialization.propertyList(from: FileManager.default.contents(atPath: url!)!, options: .mutableContainersAndLeaves, format: &format) as! [String: AnyObject] } catch { print("See instructions in code. Plist file is required. You need to set up Firebase.") } return plistData["url"] as! String } func getTacos(moc: NSManagedObjectContext, completion: @escaping (_ result: Array<Taco>) -> Void) { let req = URLRequest(url: URL(string: "\(endpointUrl())/tacos.json")!) let task = URLSession.shared.dataTask(with: req, completionHandler: {(data, response, error) in if (error != nil) { completion(Array()) } else { DispatchQueue.global(qos: .background).async { let child_moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) child_moc.parent = moc let results = self.parseTacosFromData(data: data, moc: moc) do { try child_moc.save() DispatchQueue.main.async { completion(results) } } catch _ { DispatchQueue.main.async { completion(Array()) } } } } }); task.resume() } func destroyTaco(taco: Taco, completion: @escaping (_ error: Error?) -> Void) { if let tacoId = taco.remoteId { var req = URLRequest(url: URL(string: "\(endpointUrl())/tacos/\(tacoId).json")!) req.httpMethod = "DELETE" req.allHTTPHeaderFields!["Content-Type"] = "application/json" let task = URLSession.shared.dataTask(with: req, completionHandler: {(data, response, error) in if let err = error { completion(err) } else { completion(nil) } }); task.resume() } } func createTaco(taco: Taco, moc: NSManagedObjectContext, completion: @escaping (_ error: Error?) -> Void) { var req = URLRequest(url: URL(string: "\(endpointUrl())/tacos.json")!) req.httpMethod = "POST" let payload = taco.dictionaryRepresentation() print("payload: \(payload)") do { req.httpBody = try JSONSerialization.data(withJSONObject: payload, options: []) } catch _ { return } req.allHTTPHeaderFields!["Content-Type"] = "application/json" let task = URLSession.shared.dataTask(with: req, completionHandler: {(data, response, error) in do { let jsonDict = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject] if let tacoRemoteId = jsonDict["name"] as? String { taco.remoteId = tacoRemoteId } try moc.save() } catch _ { } if let err = error { completion(err) } else { completion(nil) } }); task.resume() } func updateTaco(taco: Taco, completion: @escaping (_ error: Error?) -> Void) { if let tacoId = taco.remoteId { var req = URLRequest(url: URL(string: "\(endpointUrl())/tacos/\(tacoId).json")!) req.httpMethod = "PUT" let payload = taco.dictionaryRepresentation() do { req.httpBody = try JSONSerialization.data(withJSONObject: payload, options: []) } catch _ { return } req.allHTTPHeaderFields!["Content-Type"] = "application/json" let task = URLSession.shared.dataTask(with: req, completionHandler: {(data, response, error) in if (error == nil) { try! taco.managedObjectContext?.save() } completion(error) }); task.resume() } } // MARK: - parsing private func parseTacosFromData(data: Data?, moc: NSManagedObjectContext) -> Array<Taco> { var resultingTacos = Array<Taco> () if let tacoData = data { do { let jsonArray = try JSONSerialization.jsonObject(with: tacoData, options: []) as? [String:AnyObject] if let keyedTacoItems = jsonArray { for tacoId in keyedTacoItems.keys { if let tacoPayload = keyedTacoItems[tacoId] as? [String:AnyObject] { if let tacoResult = parseTacoFromPayload(payload: tacoPayload, tacoId: tacoId, moc: moc) { resultingTacos.append(tacoResult) } } } } } catch let error { print("JSON Serialization failed. Error: \(error)") } } return resultingTacos } private func parseTacoFromPayload(payload: [String:AnyObject], tacoId:String, moc: NSManagedObjectContext) -> Taco? { let fetchRequest = NSFetchRequest<NSFetchRequestResult>() // Edit the entity name as appropriate. let entity = NSEntityDescription.entity(forEntityName: "Taco", in: moc) fetchRequest.entity = entity fetchRequest.predicate = NSPredicate.init(format: "remoteId = %@", argumentArray: [tacoId]) let results = try! moc.fetch(fetchRequest) let resultingTaco: Taco? if results.count > 0 { resultingTaco = results.first as? Taco resultingTaco?.updateWithDictionary(json: payload) } else { resultingTaco = NSEntityDescription.insertNewObject(forEntityName: "Taco", into: moc) as? Taco resultingTaco?.remoteId = tacoId resultingTaco?.updateWithDictionary(json: payload) } return resultingTaco } }
30642fc9725d3cda641c8b11922c8250
36.206704
196
0.574775
false
false
false
false
ninewine/SaturnTimer
refs/heads/master
SaturnTimer/View/ActionButton/AnimatableLayer.swift
mit
1
// // STAnimatableLayerProtocol.swift // SaturnTimer // // Created by Tidy Nine on 2/26/16. // Copyright © 2016 Tidy Nine. All rights reserved. // import UIKit import pop class AnimatableLayer : CALayer, HighlightableProtocol { var transitionDuration: Double = 0.5 func setHighlightStatus(_ highlighted: Bool, animated: Bool) { guard let layers = layersNeedToBeHighlighted() else {return} let _ = layers.flatMap { (layer) -> CAShapeLayer in layer.pop_removeAllAnimations() if animated { let type: ShapeLayerColorType = layer.colorType ?? .fill let propertyName = type == .fill ? kPOPShapeLayerFillColor : kPOPShapeLayerStrokeColor let colorAnimation = POPBasicAnimation(propertyNamed: propertyName) colorAnimation?.duration = 0.2 colorAnimation?.toValue = highlighted ? HelperColor.primaryColor.cgColor : HelperColor.lightGrayColor.cgColor layer.pop_add(colorAnimation, forKey: "ColorAnimation") } else { if layer.colorType == .fill { layer.fillColor = highlighted ? HelperColor.primaryColor.cgColor : HelperColor.lightGrayColor.cgColor } else { layer.strokeColor = highlighted ? HelperColor.primaryColor.cgColor : HelperColor.lightGrayColor.cgColor } } return layer } } func layersNeedToBeHighlighted() -> [CAShapeLayer]? { return nil } func transitionIn (_ completion: (()->())?) { if let block = completion { block() } } func transitionOut (_ completion: (()->())?) { if let block = completion { block() } } }
7a402bad770c4e3649ce9f4da870c2d2
27.736842
117
0.656288
false
false
false
false
Aioria1314/WeiBo
refs/heads/master
WeiBo/WeiBo/Classes/Tools/Extension/ZXCTextView+Extension.swift
mit
1
// // ZXCTextView+Extension.swift // WeiBo // // Created by Aioria on 2017/4/8. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit extension ZXCTextView { var emoticonText: String { var sendMessage = "" self.attributedText.enumerateAttributes(in: NSMakeRange(0, self.attributedText.length), options: []) { (info, range, _) in // print(info, NSStringFromRange(range)) if let attachment = info["NSAttachment"] as? ZXCTextAttachment { let emoticonModel = attachment.emoticonModel! let chs = emoticonModel.chs! sendMessage += chs } else { let subAttributedStr = self.attributedText.attributedSubstring(from: range) let text = subAttributedStr.string sendMessage += text } } return sendMessage } func insertEmoticon(emoticonModel: ZXCEmoticonModel) { if emoticonModel.type == "0" { let lastAttributedStr = NSMutableAttributedString(attributedString: self.attributedText) // // let image = UIImage(named: emoticonModel.path!) // // let attachMent = ZXCTextAttachment() // // attachMent.emoticonModel = emoticonModel // // attachMent.image = image // // let linHeight = self.font!.lineHeight // // attachMent.bounds = CGRect(x: 0, y: -4, width: linHeight, height: linHeight) let attributedStr = NSAttributedString.attributedStringWithEmotionModel(emoticonModel: emoticonModel, font: self.font!) var selectedRange = self.selectedRange lastAttributedStr.replaceCharacters(in: selectedRange, with: attributedStr) // lastAttributedStr.append(attributedStr) lastAttributedStr.addAttributes([NSFontAttributeName: self.font!], range: NSMakeRange(0, lastAttributedStr.length)) self.attributedText = lastAttributedStr selectedRange.location += 1 self.selectedRange = selectedRange self.delegate?.textViewDidChange?(self) NotificationCenter.default.post(name: Notification.Name.UITextViewTextDidChange, object: nil) } else { let emoji = (emoticonModel.code! as NSString).emoji()! self.insertText(emoji) } } }
8123905764fea201c861198474b03057
30.178947
139
0.502701
false
false
false
false
scinfu/SwiftSoup
refs/heads/master
Sources/CharacterExt.swift
mit
1
// // CharacterExt.swift // SwifSoup // // Created by Nabil Chatbi on 08/10/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation extension Character { public static let space: Character = " " public static let BackslashT: Character = "\t" public static let BackslashN: Character = "\n" public static let BackslashF: Character = Character(UnicodeScalar(12)) public static let BackslashR: Character = "\r" public static let BackshashRBackslashN: Character = "\r\n" //http://www.unicode.org/glossary/#supplementary_code_point public static let MIN_SUPPLEMENTARY_CODE_POINT: UInt32 = 0x010000 /// True for any space character, and the control characters \t, \n, \r, \f, \v. var isWhitespace: Bool { switch self { case Character.space, Character.BackslashT, Character.BackslashN, Character.BackslashF, Character.BackslashR: return true case Character.BackshashRBackslashN: return true default: return false } } /// `true` if `self` normalized contains a single code unit that is in the category of Decimal Numbers. var isDigit: Bool { return isMemberOfCharacterSet(CharacterSet.decimalDigits) } /// Lowercase `self`. var lowercase: Character { let str = String(self).lowercased() return str[str.startIndex] } /// Return `true` if `self` normalized contains a single code unit that is a member of the supplied character set. /// /// - parameter set: The `NSCharacterSet` used to test for membership. /// - returns: `true` if `self` normalized contains a single code unit that is a member of the supplied character set. func isMemberOfCharacterSet(_ set: CharacterSet) -> Bool { let normalized = String(self).precomposedStringWithCanonicalMapping let unicodes = normalized.unicodeScalars guard unicodes.count == 1 else { return false } return set.contains(UnicodeScalar(unicodes.first!.value)!) } static func convertFromIntegerLiteral(value: IntegerLiteralType) -> Character { return Character(UnicodeScalar(value)!) } static func isLetter(_ char: Character) -> Bool { return char.isLetter() } func isLetter() -> Bool { return self.isMemberOfCharacterSet(CharacterSet.letters) } static func isLetterOrDigit(_ char: Character) -> Bool { return char.isLetterOrDigit() } func isLetterOrDigit() -> Bool { if(self.isLetter()) {return true} return self.isDigit } }
3eeb1e2e6f02edbdde62ce1303c4e52c
30.814815
129
0.675204
false
false
false
false
Tantalum73/XJodel
refs/heads/master
XJodel/XJodel/LoadingProgressIndicatorView.swift
mit
1
// // LoadingProgressIndicatorView.swift // LoadingViewTest // // Created by Andreas Neusüß on 05.04.16. // Copyright © 2016 Cocoawah. All rights reserved. // import Cocoa @IBDesignable /// NSView subclass that draws a given path to display progress of an operation. class LoadingProgressIndicatorView: NSView { /// The path of the figure that will be drawn in order to show progress. var path : CGPath? = LoadingProgressIndicatorPaths.pathComplete.toCGPath() { didSet { prepareLayer() } } /// Color of the path. var strokeColor : NSColor? { didSet { prepareLayer() } } /// Boolean that specifies whether the path should be centered in the view. var shouldBeCentered = true { didSet { prepareLayer() } } /// Line width of path. var lineWidth : CGFloat = 2.0 { didSet { prepareLayer() } } /// The current progress that should be displayed. It automatically updates the path. var progress : Double = 0 { didSet { guard progress >= 0 && progress <= 1 else{return} pathLayer.strokeEnd = CGFloat(progress) } } fileprivate let pathLayer = CAShapeLayer() override init(frame: CGRect) { // pathLayer = CAShapeLayer() super.init(frame: frame) wantsLayer = true } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) wantsLayer = true } override func awakeFromNib() { super.awakeFromNib() wantsLayer = true prepareLayer() } override func prepareForInterfaceBuilder() { prepareLayer() } /** Sets up the components and applies specified values as lineWidth and further. */ fileprivate func prepareLayer() { pathLayer.removeFromSuperlayer() pathLayer.path = path pathLayer.strokeColor = strokeColor?.cgColor ?? NSColor.white.cgColor pathLayer.fillColor = nil pathLayer.lineWidth = lineWidth pathLayer.miterLimit = lineWidth pathLayer.lineCap = kCALineCapRound pathLayer.masksToBounds = true let strokingPath = CGPath(__byStroking: pathLayer.path!, transform: nil, lineWidth: 4, lineCap: CGLineCap.round, lineJoin: CGLineJoin.miter, miterLimit: 4) // print(CGPathGetPathBoundingBox(strokingPath)) pathLayer.bounds = (strokingPath?.boundingBoxOfPath)! if shouldBeCentered { pathLayer.position = CGPoint(x: bounds.midX, y: bounds.midY) } else { pathLayer.frame = bounds } pathLayer.strokeEnd = 0 layer!.addSublayer(pathLayer) } /** Animates to completed state. */ func animateToFinish() { let strokeEnd = CABasicAnimation(keyPath: "strokeEnd") strokeEnd.fromValue = pathLayer.presentation()?.strokeEnd strokeEnd.toValue = 1 strokeEnd.duration = 1.0 strokeEnd.isRemovedOnCompletion = false CATransaction.begin() CATransaction.setCompletionBlock { self.progress = 1 } pathLayer.add(strokeEnd, forKey: "strokeEnd") CATransaction.commit() // pathLayer.strokeEnd = 1 // (pathLayer.modelLayer() as! CAShapeLayer).strokeEnd = 1 } } // MARK: - Extension to convert NSBezierPath to CGPath (fyi UIBezierPath is able to perform this 'transformation' out of the box). extension NSBezierPath { /** Converts the NSBezierPath to CGPath - returns: CGPath from the NSBezierPath or nil if the BezierPath is empty. */ func toCGPath () -> CGPath? { if self.elementCount == 0 { return nil } let path = CGMutablePath() var didClosePath = false for i in 0...self.elementCount-1 { var points = [NSPoint](repeating: NSZeroPoint, count: 3) switch self.element(at: i, associatedPoints: &points) { case .moveToBezierPathElement: //CGPathMoveToPoint(path, nil, points[0].x, points[0].y) path.move(to: points[0]) case .lineToBezierPathElement: //CGPathAddLineToPoint(path, nil, points[0].x, points[0].y) path.addLine(to: points[0]) case .curveToBezierPathElement: //CGPathAddCurveToPoint(path, nil, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y) path.addCurve(to: points[1], control1: points[0], control2: points[2]) case .closePathBezierPathElement:path.closeSubpath() didClosePath = true; } } if !didClosePath { path.closeSubpath() } return path.copy() } }
1427a6dc108035a8b40549a4138e193f
29.052632
163
0.569955
false
false
false
false
passchaos/DSSXMLParser
refs/heads/master
XMLParser/XMLParser/Element.swift
gpl-3.0
2
// // Element.swift // XmlTest // // Created by passchaos on 15/7/20. // Copyright © 2015年 马赛. All rights reserved. // import UIKit class Element: NSObject { /// 结点名称 var name: String? /// 结点内容 lazy var content: String = { return "" }() /// 结点属性 var attributes: [String: String]? /// 父结点 var parent: Element? /// 所有子结点 lazy var children = [Element]() init(parser: NSXMLParser) { super.init() parser.delegate = self } func addChild(child: Element) { children.append(child) child.parent = self } } extension Element: NSXMLParserDelegate { func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { name = elementName attributes = attributeDict addChild(Element(parser: parser)) } func parser(parser: NSXMLParser, foundCharacters string: String) { self.content += string } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { print(self.content) // let parent = self.parent parser.delegate = self.parent } }
13a37f51736a483348f4ed54d872e282
21.333333
173
0.597761
false
false
false
false
slavapestov/swift
refs/heads/master
test/Constraints/generics.swift
apache-2.0
1
// RUN: %target-parse-verify-swift infix operator +++ {} protocol ConcatToAnything { func +++ <T>(lhs: Self, other: T) } func min<T : Comparable>(x: T, y: T) -> T { if y < x { return y } return x } func weirdConcat<T : ConcatToAnything, U>(t: T, u: U) { t +++ u t +++ 1 u +++ t // expected-error{{binary operator '+++' cannot be applied to operands of type 'U' and 'T'}} // expected-note @-1 {{expected an argument list of type '(Self, T)'}} } // Make sure that the protocol operators don't get in the way. var b1, b2 : Bool _ = b1 != b2 extension UnicodeScalar { func isAlpha2() -> Bool { return (self >= "A" && self <= "Z") || (self >= "a" && self <= "z") } } protocol P { static func foo(arg: Self) -> Self } struct S : P { static func foo(arg: S) -> S { return arg } } func foo<T : P>(arg: T) -> T { return T.foo(arg) } // Associated types and metatypes protocol SomeProtocol { associatedtype SomeAssociated } func generic_metatypes<T : SomeProtocol>(x: T) -> (T.Type, T.SomeAssociated.Type) { return (x.dynamicType, x.dynamicType.SomeAssociated.self) } // Inferring a variable's type from a call to a generic. struct Pair<T, U> { } func pair<T, U>(x: T, _ y: U) -> Pair<T, U> { } var i : Int, f : Float var p = pair(i, f) // Conformance constraints on static variables. func f1<S1 : SequenceType>(s1: S1) {} var x : Array<Int> = [1] f1(x) // Inheritance involving generics and non-generics. class X { func f() {} } class Foo<T> : X { func g() { } } class Y<U> : Foo<Int> { } func genericAndNongenericBases(x: Foo<Int>, y: Y<()>) { x.f() y.f() y.g() } func genericAndNongenericBasesTypeParameter<T : Y<()>>(t: T) { t.f() t.g() } protocol P1 {} protocol P2 {} func foo<T : P1>(t: T) -> P2 { return t // expected-error{{return expression of type 'T' does not conform to 'P2'}} } func foo2(p1: P1) -> P2 { return p1 // expected-error{{return expression of type 'P1' does not conform to 'P2'}} } // <rdar://problem/14005696> protocol BinaryMethodWorkaround { associatedtype MySelf } protocol Squigglable : BinaryMethodWorkaround { } infix operator ~~~ { } func ~~~ <T : Squigglable where T.MySelf == T>(lhs: T, rhs: T) -> Bool { return true } extension UInt8 : Squigglable { typealias MySelf = UInt8 } var rdar14005696 : UInt8 rdar14005696 ~~~ 5 // <rdar://problem/15168483> func f1< S: CollectionType where S.Index: BidirectionalIndexType >(seq: S) { let x = (seq.indices).lazy.reverse() PermutationGenerator(elements: seq, indices: x) // expected-warning{{unused}} PermutationGenerator(elements: seq, indices: seq.indices.reverse()) // expected-warning{{unused}} } // <rdar://problem/16078944> func count16078944<C: CollectionType>(x: C) -> Int { return 0 } func test16078944 <T: ForwardIndexType>(lhs: T, args: T) -> Int { return count16078944(lhs..<args) // don't crash } // <rdar://problem/22409190> QoI: Passing unsigned integer to ManagedBuffer elements.destroy() class r22409190ManagedBuffer<Value, Element> { final var value: Value { get {} set {}} func withUnsafeMutablePointerToElements<R>( body: (UnsafeMutablePointer<Element>) -> R) -> R { } } class MyArrayBuffer<Element>: r22409190ManagedBuffer<UInt, Element> { deinit { self.withUnsafeMutablePointerToElements { elems -> Void in elems.destroy(self.value) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} } } } // <rdar://problem/22459135> error: 'print' is unavailable: Please wrap your tuple argument in parentheses: 'print((...))' func r22459135() { func h<S: SequenceType where S.Generator.Element: IntegerType> (sequence: S) -> S.Generator.Element { return 0 } func g(x: Any) {} func f(x: Int) { g(h([3])) } func f2<TargetType: AnyObject>(target: TargetType, handler: TargetType -> ()) { let _: AnyObject -> () = { internalTarget in handler(internalTarget as! TargetType) } } } // <rdar://problem/19710848> QoI: Friendlier error message for "[] as Set" // <rdar://problem/22326930> QoI: "argument for generic parameter 'Element' could not be inferred" lacks context _ = [] as Set // expected-error {{generic parameter 'Element' could not be inferred in cast to 'Set<_>}} //<rdar://problem/22509125> QoI: Error when unable to infer generic archetype lacks greatness func r22509125<T>(a : T?) { // expected-note {{in call to function 'r22509125'}} r22509125(nil) // expected-error {{generic parameter 'T' could not be inferred}} } // <rdar://problem/24267414> QoI: error: cannot convert value of type 'Int' to specified type 'Int' struct R24267414<T> { // expected-note {{'T' declared as parameter to type 'R24267414'}} static func foo() -> Int {} } var _ : Int = R24267414.foo() // expected-error {{generic parameter 'T' could not be inferred}} // https://bugs.swift.org/browse/SR-599 func SR599<T: IntegerType>() -> T.Type { return T.self } // expected-note {{in call to function 'SR599'}} _ = SR599() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/19215114> QoI: Poor diagnostic when we are unable to infer type protocol Q19215114 {} protocol P19215114 {} // expected-note @+1 {{in call to function 'body9215114'}} func body9215114<T: P19215114, U: Q19215114>(t: T) -> (u: U) -> () {} func test9215114<T: P19215114, U: Q19215114>(t: T) -> (U) -> () { //Should complain about not being able to infer type of U. let f = body9215114(t) // expected-error {{generic parameter 'T' could not be inferred}} return f }
948bc51a8582ce9f44187f19f3162b05
25.206573
122
0.655142
false
false
false
false
erikmartens/NearbyWeather
refs/heads/develop
NearbyWeather/Scenes/Shared Scene Objects/Alert Controllers/Amount of Nearby Results/AmountOfNearbyResultsSelectionAlert.swift
mit
1
// // AmountOfNearbyResultsSelectionAlertController.swift // NearbyWeather // // Created by Erik Maximilian Martens on 04.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import UIKit.UIAlertController import RxSwift import RxFlow // MARK: - Delegate protocol AmountOfResultsSelectionAlertDelegate: AnyObject { func didSelectAmountOfResultsOption(_ selectedOption: AmountOfResultsOption) } // MARK: - Dependencies extension AmountOfNearbyResultsSelectionAlert { struct Dependencies { weak var selectionDelegate: AmountOfResultsSelectionAlertDelegate? let selectedOptionValue: AmountOfResultsOptionValue } } // MARK: - Class Definition final class AmountOfNearbyResultsSelectionAlert { // MARK: - Actions fileprivate lazy var tenNearbyResultsSelectionAction = Factory.AlertAction.make(fromType: .standard(title: "\(AmountOfResultsOptionValue.ten.rawValue)", handler: { [dependencies] _ in dependencies.selectionDelegate?.didSelectAmountOfResultsOption(AmountOfResultsOption(value: .ten)) })) fileprivate lazy var twentyNearbyResultsSelectionAction = Factory.AlertAction.make(fromType: .standard(title: "\(AmountOfResultsOptionValue.twenty.rawValue)", handler: { [dependencies] _ in dependencies.selectionDelegate?.didSelectAmountOfResultsOption(AmountOfResultsOption(value: .twenty)) })) fileprivate lazy var thirtyNearbyResultsSelectionAction = Factory.AlertAction.make(fromType: .standard(title: "\(AmountOfResultsOptionValue.thirty.rawValue)", handler: { [dependencies] _ in dependencies.selectionDelegate?.didSelectAmountOfResultsOption(AmountOfResultsOption(value: .thirty)) })) fileprivate lazy var fortyNearbyResultsSelectionAction = Factory.AlertAction.make(fromType: .standard(title: "\(AmountOfResultsOptionValue.forty.rawValue)", handler: { [dependencies] _ in dependencies.selectionDelegate?.didSelectAmountOfResultsOption(AmountOfResultsOption(value: .forty)) })) fileprivate lazy var fiftyNearbyResultsSelectionAction = Factory.AlertAction.make(fromType: .standard(title: "\(AmountOfResultsOptionValue.fifty.rawValue)", handler: { [dependencies] _ in dependencies.selectionDelegate?.didSelectAmountOfResultsOption(AmountOfResultsOption(value: .fifty)) })) fileprivate lazy var cancelAction = Factory.AlertAction.make(fromType: .cancel) // MARK: - Properties let dependencies: Dependencies let alertController: UIAlertController // MARK: - Initialization required init(dependencies: Dependencies) { self.dependencies = dependencies alertController = UIAlertController( title: R.string.localizable.amount_of_results().capitalized, message: nil, preferredStyle: .alert ) alertController.addAction(tenNearbyResultsSelectionAction) alertController.addAction(twentyNearbyResultsSelectionAction) alertController.addAction(thirtyNearbyResultsSelectionAction) alertController.addAction(fortyNearbyResultsSelectionAction) alertController.addAction(fiftyNearbyResultsSelectionAction) alertController.addAction(cancelAction) setCheckmarkForOption(with: dependencies.selectedOptionValue) } deinit { printDebugMessage( domain: String(describing: self), message: "was deinitialized", type: .info ) } } // MARK: - Helpers private extension AmountOfNearbyResultsSelectionAlert { func setCheckmarkForOption(with value: AmountOfResultsOptionValue) { var action: UIAlertAction switch dependencies.selectedOptionValue { case .ten: action = tenNearbyResultsSelectionAction case .twenty: action = twentyNearbyResultsSelectionAction case .thirty: action = thirtyNearbyResultsSelectionAction case .forty: action = fortyNearbyResultsSelectionAction case .fifty: action = fiftyNearbyResultsSelectionAction } action.setValue(true, forKey: Constants.Keys.KeyValueBindings.kChecked) } }
f956574ebeb29e6f14c0cde0f9365d54
35.916667
191
0.776273
false
false
false
false
proversity-org/edx-app-ios
refs/heads/master
Source/SubjectsDiscovery/SubjectsCollectionView.swift
apache-2.0
1
// // SubjectsCollectionView.swift // edX // // Created by Zeeshan Arif on 5/23/18. // Copyright © 2018 edX. All rights reserved. // import UIKit protocol SubjectsCollectionViewDelegate: class { func subjectsCollectionView(_ collectionView: SubjectsCollectionView, didSelect subject: Subject) func didSelectViewAllSubjects(_ collectionView: SubjectsCollectionView) } extension SubjectsCollectionViewDelegate { func didSelectViewAllSubjects(_ collectionView: SubjectsCollectionView) { //this is a empty implementation to allow this method to be optional } } class SubjectsCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource { var subjects: [Subject] = [] { didSet { reloadData() } } weak var subjectsDelegate: SubjectsCollectionViewDelegate? init(with subjects: [Subject], collectionViewLayout layout: UICollectionViewLayout) { self.subjects = subjects super.init(frame: .zero, collectionViewLayout: layout) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } private func setup() { register(SubjectCollectionViewCell.self, forCellWithReuseIdentifier: SubjectCollectionViewCell.identifier) register(ViewAllSubjectsCollectionViewCell.self, forCellWithReuseIdentifier: ViewAllSubjectsCollectionViewCell.identifier) delegate = self dataSource = self backgroundColor = .clear } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return subjects.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SubjectCollectionViewCell.identifier, for: indexPath) as! SubjectCollectionViewCell cell.configure(subject: subjects[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { subjectsDelegate?.subjectsCollectionView(self, didSelect: subjects[indexPath.row]) } } class PopularSubjectsCollectionView: SubjectsCollectionView { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return subjects.count + 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.row >= subjects.count { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ViewAllSubjectsCollectionViewCell.identifier, for: indexPath) as! ViewAllSubjectsCollectionViewCell return cell } return super.collectionView(collectionView, cellForItemAt: indexPath) } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.row >= subjects.count { subjectsDelegate?.didSelectViewAllSubjects(self) } else { super.collectionView(collectionView, didSelectItemAt: indexPath) } } }
17b78a48c298084d3c06c8610dbccb31
36.215054
178
0.716267
false
false
false
false
hovansuit/FoodAndFitness
refs/heads/master
FoodAndFitness/Controllers/TrackingDetail/TrackingDetailViewModel.swift
mit
1
// // TrackingDetailViewModel.swift // FoodAndFitness // // Created by Mylo Ho on 5/29/17. // Copyright © 2017 SuHoVan. All rights reserved. // import UIKit import CoreLocation class TrackingDetailViewModel { let params: TrackingParams init(params: TrackingParams) { self.params = params } func save(completion: @escaping Completion) { if User.me == nil { let error = NSError(message: Strings.Errors.tokenError) completion(.failure(error)) } else { TrackingServices.save(params: params, completion: completion) } } func data() -> TrackingDetailController.Data { let active = Strings.active + ": " + params.active let duration = Strings.duration + ": \(params.duration)" let distance = Strings.distance + ": \(params.distance)" return TrackingDetailController.Data(active: active, duration: duration, distance: distance) } func coordinatesForMap() -> [CLLocationCoordinate2D] { var result: [CLLocationCoordinate2D] = [] for location in params.locations { let clLocation = location.toCLLocation result.append(clLocation.coordinate) } return result } }
07d487b1155d509f456641ad42c33435
27.477273
100
0.636872
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
refs/heads/master
AviasalesSDKTemplate/Source/HotelsSource/Objects/SearchResult.swift
mit
1
import Foundation @objcMembers @objc class SearchResult: NSObject { let variants: [HLResultVariant] let nearbyCities: [HDKCity] let searchInfo: HLSearchInfo var searchId: String? var counters: VariantsCounters = VariantsCounters(variants: []) lazy var allGatesNames: Set<String> = SearchResult.gatesNames(from: self.variants) lazy var allDistrictsNames: Set<String> = SearchResult.districtsNames(from: self.variants) init(searchInfo: HLSearchInfo, variants: [HLResultVariant] = [], nearbyCities: [HDKCity] = []) { self.searchInfo = searchInfo self.variants = variants self.nearbyCities = nearbyCities self.counters = VariantsCounters(variants: self.variants) super.init() } convenience init(searchInfo: HLSearchInfo) { self.init(searchInfo: searchInfo, variants: [], nearbyCities: []) } func hasAnyRoomWithPrice() -> Bool { return variants.index(where: { variant -> Bool in return variant.roomWithMinPrice != nil }) != nil } static func districtsNames(from variants: [HLResultVariant]) -> Set<String> { var districtsNames = Set<String>() for variant in variants { let hotel = variant.hotel if let firstDistrictName = hotel.firstDistrictName() { districtsNames.insert(firstDistrictName) } } return districtsNames } static func gatesNames(from variants: [HLResultVariant]) -> Set<String> { var gatesNames = Set<String>() for variant in variants { if let rooms = variant.roomsCopy() { for room in rooms { if room.hasHotelWebsiteOption { gatesNames.insert(FilterLogic.hotelWebsiteAgencyName()) } else { gatesNames.insert(room.gate.name ?? "") } } } } return gatesNames } }
8308c80a0109a3804c164ab6b5544031
30.825397
100
0.602993
false
false
false
false
digipost/ios
refs/heads/master
Digipost/APIClient+Document.swift
apache-2.0
1
// // Copyright (C) Posten Norge AS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit extension APIClient { @objc func changeName(_ document: POSDocument, newName name: String, success: @escaping () -> Void , failure: @escaping (_ error: APIError) -> ()) { let documentFolder = document.folder let parameters : Dictionary<String,String> = { if documentFolder?.name.lowercased() == Constants.FolderName.inbox.lowercased() { return [Constants.APIClient.AttributeKey.location : Constants.FolderName.inbox, Constants.APIClient.AttributeKey.subject : name] } else { return [Constants.APIClient.AttributeKey.location : Constants.FolderName.folder, Constants.APIClient.AttributeKey.subject : name, Constants.APIClient.AttributeKey.folderId: documentFolder!.folderId.stringValue] } }() validateFullScope { let task = self.urlSessionTask(httpMethod.post, url: document.updateUri, parameters: parameters as Dictionary<String, AnyObject>?, success: success,failure: failure) task.resume() } } @objc func deleteDocument(_ uri: String, success: @escaping () -> Void , failure:@escaping (_ error: APIError) -> ()) { validateFullScope { let task = self.urlSessionTask(httpMethod.delete, url: uri, success: success, failure: failure) task.resume() } } @objc func moveDocument(_ document: POSDocument, toFolder folder: POSFolder, success: @escaping () -> Void , failure: @escaping (_ error: APIError) -> ()) { let firstAttachment = document.attachments.firstObject as! POSAttachment let parameters : Dictionary<String,String> = { if folder.name.lowercased() == Constants.FolderName.inbox.lowercased() { return [Constants.APIClient.AttributeKey.location : Constants.FolderName.inbox, Constants.APIClient.AttributeKey.subject : firstAttachment.subject] } else { return [Constants.APIClient.AttributeKey.location: Constants.FolderName.folder, Constants.APIClient.AttributeKey.subject : firstAttachment.subject, Constants.APIClient.AttributeKey.folderId : folder.folderId.stringValue] } }() validateFullScope { let task = self.urlSessionTask(httpMethod.post, url: document.updateUri, parameters:parameters as Dictionary<String, AnyObject>?, success: success, failure: failure) task.resume() } } @objc func updateDocumentsInFolder(name: String, mailboxDigipostAdress: String, folderUri: String, token: OAuthToken, success: @escaping (Dictionary<String,AnyObject>) -> Void, failure: @escaping (_ error: APIError) -> ()) { validate(token: token) { () -> Void in let task = self.urlSessionJSONTask(url: folderUri, success: success, failure: failure) task.resume() } } @objc func updateDocument(_ document: POSDocument, success: @escaping (Dictionary<String,AnyObject>) -> Void , failure: @escaping (_ error: APIError) -> ()) { validateFullScope { let task = self.urlSessionJSONTask(url: document.updateUri, success: success, failure: failure) task.resume() } } }
e2c0b685833ac66b2a20b4fd58c19409
51.30137
236
0.673127
false
false
false
false
qualaroo/QualarooSDKiOS
refs/heads/master
QualarooTests/Validators/NpsViewValidatorSpec.swift
mit
1
// // AnswerNpsValidatorSpec.swift // QualarooTests // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation import Quick import Nimble @testable import Qualaroo class AnswerNpsValidatorSpec: QuickSpec { override func spec() { super.spec() describe("AnswerNpsValidator") { it("passes if question is not required") { let dict = JsonLibrary.question(type: "text", isRequired: false) let question = try! QuestionFactory(with: dict).build() let validator = AnswerNpsValidator(question: question) var isValid = validator.isValid(selectedId: UISegmentedControlNoSegment) expect(isValid).to(beTrue()) isValid = validator.isValid(selectedId: 1) expect(isValid).to(beTrue()) } it("passes for non-empty answer if question is required") { let answers = [JsonLibrary.answer(), JsonLibrary.answer()] let dict = JsonLibrary.question(type: "dropdown", answerList: answers, isRequired: true) let question = try! QuestionFactory(with: dict).build() let validator = AnswerNpsValidator(question: question) let isValid = validator.isValid(selectedId: 1) expect(isValid).to(beTrue()) } it("failing for answer out of range if question is required") { let answers = [JsonLibrary.answer(), JsonLibrary.answer()] let dict = JsonLibrary.question(type: "dropdown", answerList: answers, isRequired: true) let question = try! QuestionFactory(with: dict).build() let validator = AnswerNpsValidator(question: question) let isValid = validator.isValid(selectedId: 2) expect(isValid).to(beFalse()) } it("failing for empty answer if question is required") { let dict = JsonLibrary.question(type: "text", isRequired: true) let question = try! QuestionFactory(with: dict).build() let validator = AnswerNpsValidator(question: question) let isValid = validator.isValid(selectedId: UISegmentedControlNoSegment) expect(isValid).to(beFalse()) } } } }
994b7f0d6ab90d16dbf674fb7d41fa8a
39.145161
80
0.609482
false
false
false
false
inamiy/VTree
refs/heads/master
Tests/FuncBoxSpec.swift
mit
1
@testable import VTree import Quick import Nimble class FuncBoxSpec: QuickSpec { override func spec() { describe("FuncBox") { it("Basic") { let f1 = { $0 + 1 } let fbox1 = FuncBox(f1) expect(fbox1.impl(0)) == 1 expect(fbox1.impl(1)) == 2 expect(fbox1.impl(2)) == 3 expect(fbox1) == fbox1 let fbox1b = FuncBox(f1) expect(fbox1b) == fbox1 let f2 = f1 let fbox2 = FuncBox(f2) expect(fbox2) == fbox1 let f3 = { $0 + 1 } // new closure let fbox3 = FuncBox(f3) expect(fbox3) != fbox1 // NOTE: `f` and `f3` aren't same func pointer } it("Equatable works inside Array") { let f1 = { $0 + 1 } let f2 = { $0 + 1 } // new closure let fbox1 = FuncBox(f1) let fbox1b = FuncBox(f1) let fbox2 = FuncBox(f2) let arr1 = [fbox1, fbox1, fbox1b, fbox2] expect(arr1[0]) == arr1[0] expect(arr1[1]) == arr1[0] expect(arr1[2]) == arr1[0] expect(arr1[3]) != arr1[0] // NOTE: // Using raw closure inside collection will fail `_peekFunc`'s equality check. // For example: // // let arr2 = [f1, f1] // expect(_peekFunc(arr2[0]) == _peekFunc(arr2[1])).to(beFalse()) } it("FuncBox.map") { let f1 = { $0 + 1 } let map1 = { $0 * 2 } let fbox1 = FuncBox(f1).map(map1) expect(fbox1.impl(0)) == 2 expect(fbox1.impl(1)) == 4 expect(fbox1.impl(2)) == 6 expect(fbox1) == fbox1 let fbox1b = FuncBox(f1).map(map1) expect(fbox1b) == fbox1 let fbox1c = FuncBox(f1).map { $0 * 2 } // new closure expect(fbox1c) != fbox1 let fbox1d = FuncBox { $0 + 1 }.map(map1) // new closure expect(fbox1d) != fbox1 } it("FuncBox.compose") { let f1 = { $0 + 1 } let f2 = { $0 * 2 } let fbox1 = FuncBox(f1).compose(FuncBox(f2)) expect(fbox1.impl(0)) == 2 expect(fbox1.impl(1)) == 4 expect(fbox1.impl(2)) == 6 expect(fbox1) == fbox1 let fbox1b = FuncBox(f1).compose(FuncBox(f2)) expect(fbox1b) == fbox1 let fbox1c = FuncBox(f1).compose(FuncBox { $0 * 2 }) // new closure expect(fbox1c) != fbox1 let fbox1d = FuncBox { $0 + 1 }.compose(FuncBox(f2)) // new closure expect(fbox1d) != fbox1 } describe("Hashable") { let f1 = { $0 + 1 } let f2 = { $0 * 2 } it("FuncBox Set should not increase when inserting existing element") { var set = Set(arrayLiteral: FuncBox(f1), FuncBox(f2)) expect(set.count) == 2 set.insert(FuncBox(f1)) expect(set.count) == 2 } it("FuncBox Sets should be equal when elements are swapped") { let set = Set(arrayLiteral: FuncBox(f1), FuncBox(f2)) let set2 = Set(arrayLiteral: FuncBox(f2), FuncBox(f1)) expect(set) == set2 } it("FuncBox Arrays should not be equal when elements are swapped") { let array = [FuncBox(f1), FuncBox(f2)] let array2 = [FuncBox(f2), FuncBox(f1)] expect(array) != array2 } } } } }
7561bf02e4d4687939521cf369d497b6
29.234848
94
0.419945
false
false
false
false
Alex-ZHOU/XYQSwift
refs/heads/master
XYQSwift/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // XYQSwift // // Created by AlexZHOU on 7/5/16. // Copyright © 2016年 AlexZHOU. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "xiaoai.XYQSwift" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "XYQSwift", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
99b7a99ad186cd8cd57044453775afcf
53.882883
291
0.717006
false
false
false
false
ArthurKK/paper-switch
refs/heads/master
PaperSwitch/RAMPaperSwitch.swift
mit
6
// RAMPaperSwitch.swift // // Copyright (c) 26/11/14 Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class RAMPaperSwitch: UISwitch { @IBInspectable var duration: Double = 0.35 var animationDidStartClosure = {(onAnimation: Bool) -> Void in } var animationDidStopClosure = {(onAnimation: Bool, finished: Bool) -> Void in } private var shape: CAShapeLayer! = CAShapeLayer() private var radius: CGFloat = 0.0 private var oldState = false override var on: Bool { didSet(oldValue) { oldState = on } } override func setOn(on: Bool, animated: Bool) { let changed:Bool = on != self.on super.setOn(on, animated: animated) if changed { if animated { switchChanged() } else { showShapeIfNeed() } } } override func layoutSubviews() { let x:CGFloat = max(frame.midX, superview!.frame.size.width - frame.midX); let y:CGFloat = max(frame.midY, superview!.frame.size.height - frame.midY); radius = sqrt(x*x + y*y); shape.frame = CGRectMake(frame.midX - radius, frame.midY - radius, radius * 2, radius * 2) shape.anchorPoint = CGPointMake(0.5, 0.5); shape.path = UIBezierPath(ovalInRect: CGRectMake(0, 0, radius * 2, radius * 2)).CGPath } override func awakeFromNib() { var shapeColor:UIColor = (onTintColor != nil) ? onTintColor : UIColor.greenColor() layer.borderWidth = 0.5 layer.borderColor = UIColor.whiteColor().CGColor; layer.cornerRadius = frame.size.height / 2; shape.fillColor = shapeColor.CGColor shape.masksToBounds = true superview?.layer.insertSublayer(shape, atIndex: 0) superview?.layer.masksToBounds = true showShapeIfNeed() addTarget(self, action: "switchChanged", forControlEvents: UIControlEvents.ValueChanged) super.awakeFromNib() } private func showShapeIfNeed() { shape.transform = on ? CATransform3DMakeScale(1.0, 1.0, 1.0) : CATransform3DMakeScale(0.0001, 0.0001, 0.0001) } internal func switchChanged() { if on == oldState { return; } oldState = on if on { CATransaction.begin() shape.removeAnimationForKey("scaleDown") var scaleAnimation:CABasicAnimation = animateKeyPath("transform", fromValue: NSValue(CATransform3D: CATransform3DMakeScale(0.0001, 0.0001, 0.0001)), toValue:NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), timing:kCAMediaTimingFunctionEaseIn); shape.addAnimation(scaleAnimation, forKey: "scaleUp") CATransaction.commit(); } else { CATransaction.begin() shape.removeAnimationForKey("scaleUp") var scaleAnimation:CABasicAnimation = animateKeyPath("transform", fromValue: NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), toValue:NSValue(CATransform3D: CATransform3DMakeScale(0.0001, 0.0001, 0.0001)), timing:kCAMediaTimingFunctionEaseOut); shape.addAnimation(scaleAnimation, forKey: "scaleDown") CATransaction.commit(); } } private func animateKeyPath(keyPath: String, fromValue from: AnyObject, toValue to: AnyObject, timing timingFunction: String) -> CABasicAnimation { let animation:CABasicAnimation = CABasicAnimation(keyPath: keyPath) animation.fromValue = from animation.toValue = to animation.repeatCount = 1 animation.timingFunction = CAMediaTimingFunction(name: timingFunction) animation.removedOnCompletion = false animation.fillMode = kCAFillModeForwards animation.duration = duration; animation.delegate = self return animation; } //CAAnimation delegate override func animationDidStart(anim: CAAnimation!){ animationDidStartClosure(on) } override func animationDidStop(anim: CAAnimation!, finished flag: Bool){ animationDidStopClosure(on, flag) } }
1b88b8efc03496281a712a6bbeba237d
34.088608
151
0.627345
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/PersonalizeRuntime/PersonalizeRuntime_Shapes.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension PersonalizeRuntime { // MARK: Enums // MARK: Shapes public struct GetPersonalizedRankingRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the campaign to use for generating the personalized ranking. public let campaignArn: String /// The contextual metadata to use when getting recommendations. Contextual metadata includes any interaction information that might be relevant when getting a user's recommendations, such as the user's current location or device type. public let context: [String: String]? /// The Amazon Resource Name (ARN) of a filter you created to include or exclude items from recommendations for a given user. public let filterArn: String? /// A list of items (by itemId) to rank. If an item was not included in the training dataset, the item is appended to the end of the reranked list. The maximum is 500. public let inputList: [String] /// The user for which you want the campaign to provide a personalized ranking. public let userId: String public init(campaignArn: String, context: [String: String]? = nil, filterArn: String? = nil, inputList: [String], userId: String) { self.campaignArn = campaignArn self.context = context self.filterArn = filterArn self.inputList = inputList self.userId = userId } public func validate(name: String) throws { try self.validate(self.campaignArn, name: "campaignArn", parent: name, max: 256) try self.validate(self.campaignArn, name: "campaignArn", parent: name, pattern: "arn:([a-z\\d-]+):personalize:.*:.*:.+") try self.context?.forEach { try validate($0.key, name: "context.key", parent: name, max: 150) try validate($0.key, name: "context.key", parent: name, pattern: "[A-Za-z\\d_]+") try validate($0.value, name: "context[\"\($0.key)\"]", parent: name, max: 1000) } try self.validate(self.filterArn, name: "filterArn", parent: name, max: 256) try self.validate(self.filterArn, name: "filterArn", parent: name, pattern: "arn:([a-z\\d-]+):personalize:.*:.*:.+") try self.inputList.forEach { try validate($0, name: "inputList[]", parent: name, max: 256) } try self.validate(self.userId, name: "userId", parent: name, max: 256) } private enum CodingKeys: String, CodingKey { case campaignArn case context case filterArn case inputList case userId } } public struct GetPersonalizedRankingResponse: AWSDecodableShape { /// A list of items in order of most likely interest to the user. The maximum is 500. public let personalizedRanking: [PredictedItem]? /// The ID of the recommendation. public let recommendationId: String? public init(personalizedRanking: [PredictedItem]? = nil, recommendationId: String? = nil) { self.personalizedRanking = personalizedRanking self.recommendationId = recommendationId } private enum CodingKeys: String, CodingKey { case personalizedRanking case recommendationId } } public struct GetRecommendationsRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the campaign to use for getting recommendations. public let campaignArn: String /// The contextual metadata to use when getting recommendations. Contextual metadata includes any interaction information that might be relevant when getting a user's recommendations, such as the user's current location or device type. public let context: [String: String]? /// The ARN of the filter to apply to the returned recommendations. For more information, see Using Filters with Amazon Personalize. When using this parameter, be sure the filter resource is ACTIVE. public let filterArn: String? /// The item ID to provide recommendations for. Required for RELATED_ITEMS recipe type. public let itemId: String? /// The number of results to return. The default is 25. The maximum is 500. public let numResults: Int? /// The user ID to provide recommendations for. Required for USER_PERSONALIZATION recipe type. public let userId: String? public init(campaignArn: String, context: [String: String]? = nil, filterArn: String? = nil, itemId: String? = nil, numResults: Int? = nil, userId: String? = nil) { self.campaignArn = campaignArn self.context = context self.filterArn = filterArn self.itemId = itemId self.numResults = numResults self.userId = userId } public func validate(name: String) throws { try self.validate(self.campaignArn, name: "campaignArn", parent: name, max: 256) try self.validate(self.campaignArn, name: "campaignArn", parent: name, pattern: "arn:([a-z\\d-]+):personalize:.*:.*:.+") try self.context?.forEach { try validate($0.key, name: "context.key", parent: name, max: 150) try validate($0.key, name: "context.key", parent: name, pattern: "[A-Za-z\\d_]+") try validate($0.value, name: "context[\"\($0.key)\"]", parent: name, max: 1000) } try self.validate(self.filterArn, name: "filterArn", parent: name, max: 256) try self.validate(self.filterArn, name: "filterArn", parent: name, pattern: "arn:([a-z\\d-]+):personalize:.*:.*:.+") try self.validate(self.itemId, name: "itemId", parent: name, max: 256) try self.validate(self.numResults, name: "numResults", parent: name, min: 0) try self.validate(self.userId, name: "userId", parent: name, max: 256) } private enum CodingKeys: String, CodingKey { case campaignArn case context case filterArn case itemId case numResults case userId } } public struct GetRecommendationsResponse: AWSDecodableShape { /// A list of recommendations sorted in ascending order by prediction score. There can be a maximum of 500 items in the list. public let itemList: [PredictedItem]? /// The ID of the recommendation. public let recommendationId: String? public init(itemList: [PredictedItem]? = nil, recommendationId: String? = nil) { self.itemList = itemList self.recommendationId = recommendationId } private enum CodingKeys: String, CodingKey { case itemList case recommendationId } } public struct PredictedItem: AWSDecodableShape { /// The recommended item ID. public let itemId: String? /// A numeric representation of the model's certainty that the item will be the next user selection. For more information on scoring logic, see how-scores-work. public let score: Double? public init(itemId: String? = nil, score: Double? = nil) { self.itemId = itemId self.score = score } private enum CodingKeys: String, CodingKey { case itemId case score } } }
eb1efb6a54be90238348ce3592e25de6
47.107143
243
0.622742
false
false
false
false
KerryJava/ios-charts
refs/heads/master
Charts/Classes/Charts/BarLineChartViewBase.swift
apache-2.0
3
// // 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, BarLineScatterCandleBubbleChartDataProvider, 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 _data === nil { return } let optionalContext = UIGraphicsGetCurrentContext() guard let context = optionalContext else { return } 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 (!_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (!_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (!_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } // if highlighting is enabled if (valuesToHighlight()) { renderer?.drawHighlighted(context: context, indices: _indicesToHighlight) } // 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() 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 _data === nil { 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.labelRotatedHeight + xAxis.yOffset // 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.labelRotatedWidth) / (_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) } } // 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 _data === nil { return } if (recognizer.state == UIGestureRecognizerState.Ended) { if !self.isHighLightPerTapEnabled { return } 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 _data === nil { return } if (recognizer.state == UIGestureRecognizerState.Ended) { if _data !== nil && _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 _data !== nil && (_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) var canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX var canZoomMoreY = isZoomingOut ? _viewPortHandler.canZoomOutMoreY : _viewPortHandler.canZoomInMoreY if (_isScaling) { canZoomMoreX = canZoomMoreX && _scaleXEnabled && (_gestureScaleAxis == .Both || _gestureScaleAxis == .X); canZoomMoreY = canZoomMoreY && _scaleYEnabled && (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y); if canZoomMoreX || canZoomMoreY { 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 = canZoomMoreX ? recognizer.scale : 1.0 let scaleY = canZoomMoreY ? 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 _data === nil { // If we have no data, we have nothing to pan and no data to highlight return; } // If drag is enabled and we are in a position where there's something to drag: // * If we're zoomed in, then obviously we have something to drag. // * If we have a drag offset - we always have something to drag if self.isDragEnabled && (!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 self.isHighlightPerDragEnabled { // We will only handle highlights on UIGestureRecognizerState.Changed _isDragging = false } } 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 _data === nil || !_dragEnabled || (self.hasNoDragOffset && self.isFullyZoomedOut && !self.isHighlightPerDragEnabled) { return false } } else { #if !os(tvOS) if (gestureRecognizer == _pinchGestureRecognizer) { if _data === nil || (!_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 } // If there is two scrollview together, we pick the superview of the inner scrollview. // In the case of UITableViewWrepperView, the superview will be UITableView if let superViewOfScrollView = scrollView?.superview where superViewOfScrollView.isKindOfClass(UIScrollView) { scrollView = superViewOfScrollView } 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 } /// 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 _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 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 simultaneously 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 } } // MARK: - BarLineScatterCandleBubbleChartDataProvider /// - 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 } } /// 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 } } public func isInverted(axis: ChartYAxis.AxisDependency) -> Bool { return getAxis(axis).isInverted } /// - 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(round(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(round(pt.x)) >= _data.xValCount) ? _data.xValCount - 1 : Int(round(pt.x)) } } /// Default formatter that calculates the position of the filled line. internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter { internal override init() { } internal func getFillLinePosition(dataSet dataSet: LineChartDataSet, dataProvider: LineChartDataProvider) -> CGFloat { var fillMin = CGFloat(0.0) if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0) { fillMin = 0.0 } else { if let data = dataProvider.data { if !dataProvider.getAxis(dataSet.axisDependency).isStartAtZeroEnabled { var max: Double, min: Double if (data.yMax > 0.0) { max = 0.0 } else { max = dataProvider.chartYMax } if (data.yMin < 0.0) { min = 0.0 } else { min = dataProvider.chartYMin } fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max) } else { fillMin = 0.0 } } } return fillMin } }
2d41401f4992e2b879be8ebf86f14bae
35.495775
238
0.575363
false
false
false
false
whitehawks/CommoniOSViews
refs/heads/master
CommoniOSViews/Classes/UIViews/CircleImageView.swift
mit
1
// // CircleView.swift // Pods // // Created by Sharif Khaleel on 6/13/17. // // import Foundation @IBDesignable public class CircleImageView:UIImageView{ var layoutSet = false @IBInspectable var borderWidth: CGFloat = 0 { didSet{ setStyle() } } @IBInspectable var borderColor: UIColor = UIColor.black { didSet{ setStyle() } } override public func layoutSubviews() { if !layoutSet{ self.setStyle() layoutSet = true } } func setStyle(){ self.layer.borderColor = borderColor.cgColor self.layer.borderWidth = borderWidth self.layer.cornerRadius = self.frame.height / 2 self.layer.masksToBounds = true } }
753ae66147d390e79f8c8c9bb4194e4e
18.463415
61
0.565163
false
false
false
false
codercd/DPlayer
refs/heads/master
DPlayer/LinkObject.swift
mit
1
// // LinkObject.swift // // Created by LiChendi on 16/4/21 // Copyright (c) . All rights reserved. // import Foundation import SwiftyJSON import ObjectMapper public class LinkObject: NSObject, Mappable, NSCoding { // MARK: Declaration for string constants to be used to decode and also serialize. internal let kLinkObjectTitleKey: String = "title" internal let kLinkObjectDefaultImageKey: String = "default_image" internal let kLinkObjectLockedViewKey: String = "locked_view" internal let kLinkObjectRecommendImageKey: String = "recommend_image" internal let kLinkObjectCategorySlugKey: String = "category_slug" internal let kLinkObjectPlayAtKey: String = "play_at" internal let kLinkObjectCategoryNameKey: String = "category_name" internal let kLinkObjectWeightAddKey: String = "weight_add" internal let kLinkObjectFollowBakKey: String = "follow_bak" internal let kLinkObjectViewKey: String = "view" internal let kLinkObjectWeightKey: String = "weight" internal let kLinkObjectCoinAddKey: String = "coin_add" internal let kLinkObjectCheckKey: String = "check" internal let kLinkObjectStatusKey: String = "status" internal let kLinkObjectSlugKey: String = "slug" internal let kLinkObjectNickKey: String = "nick" internal let kLinkObjectLevelKey: String = "level" internal let kLinkObjectNegativeViewKey: String = "negative_view" internal let kLinkObjectGradeKey: String = "grade" internal let kLinkObjectCategoryIdKey: String = "category_id" internal let kLinkObjectAppShufflingImageKey: String = "app_shuffling_image" internal let kLinkObjectIntroKey: String = "intro" internal let kLinkObjectAnnouncementKey: String = "announcement" internal let kLinkObjectFollowAddKey: String = "follow_add" internal let kLinkObjectAvatarKey: String = "avatar" internal let kLinkObjectUidKey: String = "uid" internal let kLinkObjectFollowKey: String = "follow" internal let kLinkObjectPlayCountKey: String = "play_count" internal let kLinkObjectFirstPlayAtKey: String = "first_play_at" internal let kLinkObjectLastEndAtKey: String = "last_end_at" internal let kLinkObjectCoinKey: String = "coin" internal let kLinkObjectCreateAtKey: String = "create_at" internal let kLinkObjectThumbKey: String = "thumb" internal let kLinkObjectVideoQualityKey: String = "video_quality" // MARK: Properties public var title: String? public var defaultImage: String? public var lockedView: String? public var recommendImage: String? public var categorySlug: String? public var playAt: String? public var categoryName: String? public var weightAdd: String? public var followBak: String? public var view: String? public var weight: String? public var coinAdd: String? public var check: String? public var status: String? public var slug: String? public var nick: String? public var level: String? public var negativeView: String? public var grade: String? public var categoryId: String? public var appShufflingImage: String? public var intro: String? public var announcement: String? public var followAdd: String? public var avatar: String? public var uid: String? public var follow: String? public var playCount: String? public var firstPlayAt: String? public var lastEndAt: String? public var coin: String? public var createAt: String? public var thumb: String? public var videoQuality: String? // MARK: SwiftyJSON Initalizers /** Initates the class based on the object - parameter object: The object of either Dictionary or Array kind that was passed. - returns: An initalized instance of the class. */ convenience public init(object: AnyObject) { self.init(json: JSON(object)) } /** Initates the class based on the JSON that was passed. - parameter json: JSON object from SwiftyJSON. - returns: An initalized instance of the class. */ public init(json: JSON) { title = json[kLinkObjectTitleKey].string defaultImage = json[kLinkObjectDefaultImageKey].string lockedView = json[kLinkObjectLockedViewKey].string recommendImage = json[kLinkObjectRecommendImageKey].string categorySlug = json[kLinkObjectCategorySlugKey].string playAt = json[kLinkObjectPlayAtKey].string categoryName = json[kLinkObjectCategoryNameKey].string weightAdd = json[kLinkObjectWeightAddKey].string followBak = json[kLinkObjectFollowBakKey].string view = json[kLinkObjectViewKey].string weight = json[kLinkObjectWeightKey].string coinAdd = json[kLinkObjectCoinAddKey].string check = json[kLinkObjectCheckKey].string status = json[kLinkObjectStatusKey].string slug = json[kLinkObjectSlugKey].string nick = json[kLinkObjectNickKey].string level = json[kLinkObjectLevelKey].string negativeView = json[kLinkObjectNegativeViewKey].string grade = json[kLinkObjectGradeKey].string categoryId = json[kLinkObjectCategoryIdKey].string appShufflingImage = json[kLinkObjectAppShufflingImageKey].string intro = json[kLinkObjectIntroKey].string announcement = json[kLinkObjectAnnouncementKey].string followAdd = json[kLinkObjectFollowAddKey].string avatar = json[kLinkObjectAvatarKey].string uid = json[kLinkObjectUidKey].string follow = json[kLinkObjectFollowKey].string playCount = json[kLinkObjectPlayCountKey].string firstPlayAt = json[kLinkObjectFirstPlayAtKey].string lastEndAt = json[kLinkObjectLastEndAtKey].string coin = json[kLinkObjectCoinKey].string createAt = json[kLinkObjectCreateAtKey].string thumb = json[kLinkObjectThumbKey].string videoQuality = json[kLinkObjectVideoQualityKey].string } // MARK: ObjectMapper Initalizers /** Map a JSON object to this class using ObjectMapper - parameter map: A mapping from ObjectMapper */ required public init?(_ map: Map){ } /** Map a JSON object to this class using ObjectMapper - parameter map: A mapping from ObjectMapper */ public func mapping(map: Map) { title <- map[kLinkObjectTitleKey] defaultImage <- map[kLinkObjectDefaultImageKey] lockedView <- map[kLinkObjectLockedViewKey] recommendImage <- map[kLinkObjectRecommendImageKey] categorySlug <- map[kLinkObjectCategorySlugKey] playAt <- map[kLinkObjectPlayAtKey] categoryName <- map[kLinkObjectCategoryNameKey] weightAdd <- map[kLinkObjectWeightAddKey] followBak <- map[kLinkObjectFollowBakKey] view <- map[kLinkObjectViewKey] weight <- map[kLinkObjectWeightKey] coinAdd <- map[kLinkObjectCoinAddKey] check <- map[kLinkObjectCheckKey] status <- map[kLinkObjectStatusKey] slug <- map[kLinkObjectSlugKey] nick <- map[kLinkObjectNickKey] level <- map[kLinkObjectLevelKey] negativeView <- map[kLinkObjectNegativeViewKey] grade <- map[kLinkObjectGradeKey] categoryId <- map[kLinkObjectCategoryIdKey] appShufflingImage <- map[kLinkObjectAppShufflingImageKey] intro <- map[kLinkObjectIntroKey] announcement <- map[kLinkObjectAnnouncementKey] followAdd <- map[kLinkObjectFollowAddKey] avatar <- map[kLinkObjectAvatarKey] uid <- map[kLinkObjectUidKey] follow <- map[kLinkObjectFollowKey] playCount <- map[kLinkObjectPlayCountKey] firstPlayAt <- map[kLinkObjectFirstPlayAtKey] lastEndAt <- map[kLinkObjectLastEndAtKey] coin <- map[kLinkObjectCoinKey] createAt <- map[kLinkObjectCreateAtKey] thumb <- map[kLinkObjectThumbKey] videoQuality <- map[kLinkObjectVideoQualityKey] } /** Generates description of the object in the form of a NSDictionary. - returns: A Key value pair containing all valid values in the object. */ public func dictionaryRepresentation() -> [String : AnyObject ] { var dictionary: [String : AnyObject ] = [ : ] if title != nil { dictionary.updateValue(title!, forKey: kLinkObjectTitleKey) } if defaultImage != nil { dictionary.updateValue(defaultImage!, forKey: kLinkObjectDefaultImageKey) } if lockedView != nil { dictionary.updateValue(lockedView!, forKey: kLinkObjectLockedViewKey) } if recommendImage != nil { dictionary.updateValue(recommendImage!, forKey: kLinkObjectRecommendImageKey) } if categorySlug != nil { dictionary.updateValue(categorySlug!, forKey: kLinkObjectCategorySlugKey) } if playAt != nil { dictionary.updateValue(playAt!, forKey: kLinkObjectPlayAtKey) } if categoryName != nil { dictionary.updateValue(categoryName!, forKey: kLinkObjectCategoryNameKey) } if weightAdd != nil { dictionary.updateValue(weightAdd!, forKey: kLinkObjectWeightAddKey) } if followBak != nil { dictionary.updateValue(followBak!, forKey: kLinkObjectFollowBakKey) } if view != nil { dictionary.updateValue(view!, forKey: kLinkObjectViewKey) } if weight != nil { dictionary.updateValue(weight!, forKey: kLinkObjectWeightKey) } if coinAdd != nil { dictionary.updateValue(coinAdd!, forKey: kLinkObjectCoinAddKey) } if check != nil { dictionary.updateValue(check!, forKey: kLinkObjectCheckKey) } if status != nil { dictionary.updateValue(status!, forKey: kLinkObjectStatusKey) } if slug != nil { dictionary.updateValue(slug!, forKey: kLinkObjectSlugKey) } if nick != nil { dictionary.updateValue(nick!, forKey: kLinkObjectNickKey) } if level != nil { dictionary.updateValue(level!, forKey: kLinkObjectLevelKey) } if negativeView != nil { dictionary.updateValue(negativeView!, forKey: kLinkObjectNegativeViewKey) } if grade != nil { dictionary.updateValue(grade!, forKey: kLinkObjectGradeKey) } if categoryId != nil { dictionary.updateValue(categoryId!, forKey: kLinkObjectCategoryIdKey) } if appShufflingImage != nil { dictionary.updateValue(appShufflingImage!, forKey: kLinkObjectAppShufflingImageKey) } if intro != nil { dictionary.updateValue(intro!, forKey: kLinkObjectIntroKey) } if announcement != nil { dictionary.updateValue(announcement!, forKey: kLinkObjectAnnouncementKey) } if followAdd != nil { dictionary.updateValue(followAdd!, forKey: kLinkObjectFollowAddKey) } if avatar != nil { dictionary.updateValue(avatar!, forKey: kLinkObjectAvatarKey) } if uid != nil { dictionary.updateValue(uid!, forKey: kLinkObjectUidKey) } if follow != nil { dictionary.updateValue(follow!, forKey: kLinkObjectFollowKey) } if playCount != nil { dictionary.updateValue(playCount!, forKey: kLinkObjectPlayCountKey) } if firstPlayAt != nil { dictionary.updateValue(firstPlayAt!, forKey: kLinkObjectFirstPlayAtKey) } if lastEndAt != nil { dictionary.updateValue(lastEndAt!, forKey: kLinkObjectLastEndAtKey) } if coin != nil { dictionary.updateValue(coin!, forKey: kLinkObjectCoinKey) } if createAt != nil { dictionary.updateValue(createAt!, forKey: kLinkObjectCreateAtKey) } if thumb != nil { dictionary.updateValue(thumb!, forKey: kLinkObjectThumbKey) } if videoQuality != nil { dictionary.updateValue(videoQuality!, forKey: kLinkObjectVideoQualityKey) } return dictionary } // MARK: NSCoding Protocol required public init(coder aDecoder: NSCoder) { self.title = aDecoder.decodeObjectForKey(kLinkObjectTitleKey) as? String self.defaultImage = aDecoder.decodeObjectForKey(kLinkObjectDefaultImageKey) as? String self.lockedView = aDecoder.decodeObjectForKey(kLinkObjectLockedViewKey) as? String self.recommendImage = aDecoder.decodeObjectForKey(kLinkObjectRecommendImageKey) as? String self.categorySlug = aDecoder.decodeObjectForKey(kLinkObjectCategorySlugKey) as? String self.playAt = aDecoder.decodeObjectForKey(kLinkObjectPlayAtKey) as? String self.categoryName = aDecoder.decodeObjectForKey(kLinkObjectCategoryNameKey) as? String self.weightAdd = aDecoder.decodeObjectForKey(kLinkObjectWeightAddKey) as? String self.followBak = aDecoder.decodeObjectForKey(kLinkObjectFollowBakKey) as? String self.view = aDecoder.decodeObjectForKey(kLinkObjectViewKey) as? String self.weight = aDecoder.decodeObjectForKey(kLinkObjectWeightKey) as? String self.coinAdd = aDecoder.decodeObjectForKey(kLinkObjectCoinAddKey) as? String self.check = aDecoder.decodeObjectForKey(kLinkObjectCheckKey) as? String self.status = aDecoder.decodeObjectForKey(kLinkObjectStatusKey) as? String self.slug = aDecoder.decodeObjectForKey(kLinkObjectSlugKey) as? String self.nick = aDecoder.decodeObjectForKey(kLinkObjectNickKey) as? String self.level = aDecoder.decodeObjectForKey(kLinkObjectLevelKey) as? String self.negativeView = aDecoder.decodeObjectForKey(kLinkObjectNegativeViewKey) as? String self.grade = aDecoder.decodeObjectForKey(kLinkObjectGradeKey) as? String self.categoryId = aDecoder.decodeObjectForKey(kLinkObjectCategoryIdKey) as? String self.appShufflingImage = aDecoder.decodeObjectForKey(kLinkObjectAppShufflingImageKey) as? String self.intro = aDecoder.decodeObjectForKey(kLinkObjectIntroKey) as? String self.announcement = aDecoder.decodeObjectForKey(kLinkObjectAnnouncementKey) as? String self.followAdd = aDecoder.decodeObjectForKey(kLinkObjectFollowAddKey) as? String self.avatar = aDecoder.decodeObjectForKey(kLinkObjectAvatarKey) as? String self.uid = aDecoder.decodeObjectForKey(kLinkObjectUidKey) as? String self.follow = aDecoder.decodeObjectForKey(kLinkObjectFollowKey) as? String self.playCount = aDecoder.decodeObjectForKey(kLinkObjectPlayCountKey) as? String self.firstPlayAt = aDecoder.decodeObjectForKey(kLinkObjectFirstPlayAtKey) as? String self.lastEndAt = aDecoder.decodeObjectForKey(kLinkObjectLastEndAtKey) as? String self.coin = aDecoder.decodeObjectForKey(kLinkObjectCoinKey) as? String self.createAt = aDecoder.decodeObjectForKey(kLinkObjectCreateAtKey) as? String self.thumb = aDecoder.decodeObjectForKey(kLinkObjectThumbKey) as? String self.videoQuality = aDecoder.decodeObjectForKey(kLinkObjectVideoQualityKey) as? String } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(title, forKey: kLinkObjectTitleKey) aCoder.encodeObject(defaultImage, forKey: kLinkObjectDefaultImageKey) aCoder.encodeObject(lockedView, forKey: kLinkObjectLockedViewKey) aCoder.encodeObject(recommendImage, forKey: kLinkObjectRecommendImageKey) aCoder.encodeObject(categorySlug, forKey: kLinkObjectCategorySlugKey) aCoder.encodeObject(playAt, forKey: kLinkObjectPlayAtKey) aCoder.encodeObject(categoryName, forKey: kLinkObjectCategoryNameKey) aCoder.encodeObject(weightAdd, forKey: kLinkObjectWeightAddKey) aCoder.encodeObject(followBak, forKey: kLinkObjectFollowBakKey) aCoder.encodeObject(view, forKey: kLinkObjectViewKey) aCoder.encodeObject(weight, forKey: kLinkObjectWeightKey) aCoder.encodeObject(coinAdd, forKey: kLinkObjectCoinAddKey) aCoder.encodeObject(check, forKey: kLinkObjectCheckKey) aCoder.encodeObject(status, forKey: kLinkObjectStatusKey) aCoder.encodeObject(slug, forKey: kLinkObjectSlugKey) aCoder.encodeObject(nick, forKey: kLinkObjectNickKey) aCoder.encodeObject(level, forKey: kLinkObjectLevelKey) aCoder.encodeObject(negativeView, forKey: kLinkObjectNegativeViewKey) aCoder.encodeObject(grade, forKey: kLinkObjectGradeKey) aCoder.encodeObject(categoryId, forKey: kLinkObjectCategoryIdKey) aCoder.encodeObject(appShufflingImage, forKey: kLinkObjectAppShufflingImageKey) aCoder.encodeObject(intro, forKey: kLinkObjectIntroKey) aCoder.encodeObject(announcement, forKey: kLinkObjectAnnouncementKey) aCoder.encodeObject(followAdd, forKey: kLinkObjectFollowAddKey) aCoder.encodeObject(avatar, forKey: kLinkObjectAvatarKey) aCoder.encodeObject(uid, forKey: kLinkObjectUidKey) aCoder.encodeObject(follow, forKey: kLinkObjectFollowKey) aCoder.encodeObject(playCount, forKey: kLinkObjectPlayCountKey) aCoder.encodeObject(firstPlayAt, forKey: kLinkObjectFirstPlayAtKey) aCoder.encodeObject(lastEndAt, forKey: kLinkObjectLastEndAtKey) aCoder.encodeObject(coin, forKey: kLinkObjectCoinKey) aCoder.encodeObject(createAt, forKey: kLinkObjectCreateAtKey) aCoder.encodeObject(thumb, forKey: kLinkObjectThumbKey) aCoder.encodeObject(videoQuality, forKey: kLinkObjectVideoQualityKey) } }
b5121260c6099642cdc8fb12237012ae
40.965969
98
0.781361
false
false
false
false
eoger/firefox-ios
refs/heads/master
Client/Frontend/Browser/BrowserViewController/BrowserViewController+WKNavigationDelegate.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Shared private let log = Logger.browserLogger extension WKNavigationAction { /// Allow local requests only if the request is privileged. var isAllowed: Bool { guard let url = request.url else { return true } return !url.isWebPage(includeDataURIs: false) || !url.isLocal || request.isPrivileged } } extension BrowserViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { if tabManager.selectedTab?.webView !== webView { return } updateFindInPageVisibility(visible: false) // If we are going to navigate to a new page, hide the reader mode button. Unless we // are going to a about:reader page. Then we keep it on screen: it will change status // (orange color) as soon as the page has loaded. if let url = webView.url { if !url.isReaderModeURL { urlBar.updateReaderModeState(ReaderModeState.unavailable) hideReaderModeBar(animated: false) } } } // Recognize an Apple Maps URL. This will trigger the native app. But only if a search query is present. Otherwise // it could just be a visit to a regular page on maps.apple.com. fileprivate func isAppleMapsURL(_ url: URL) -> Bool { if url.scheme == "http" || url.scheme == "https" { if url.host == "maps.apple.com" && url.query != nil { return true } } return false } // Recognize a iTunes Store URL. These all trigger the native apps. Note that appstore.com and phobos.apple.com // used to be in this list. I have removed them because they now redirect to itunes.apple.com. If we special case // them then iOS will actually first open Safari, which then redirects to the app store. This works but it will // leave a 'Back to Safari' button in the status bar, which we do not want. fileprivate func isStoreURL(_ url: URL) -> Bool { if url.scheme == "http" || url.scheme == "https" || url.scheme == "itms-apps" { if url.host == "itunes.apple.com" { return true } } return false } // This is the place where we decide what to do with a new navigation action. There are a number of special schemes // and http(s) urls that need to be handled in a different way. All the logic for that is inside this delegate // method. func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url else { decisionHandler(.cancel) return } if url.scheme == "about" { decisionHandler(.allow) return } if !navigationAction.isAllowed && navigationAction.navigationType != .backForward { log.warning("Denying unprivileged request: \(navigationAction.request)") decisionHandler(.cancel) return } // First special case are some schemes that are about Calling. We prompt the user to confirm this action. This // gives us the exact same behaviour as Safari. if url.scheme == "tel" || url.scheme == "facetime" || url.scheme == "facetime-audio" { UIApplication.shared.open(url, options: [:]) decisionHandler(.cancel) return } // Second special case are a set of URLs that look like regular http links, but should be handed over to iOS // instead of being loaded in the webview. Note that there is no point in calling canOpenURL() here, because // iOS will always say yes. TODO Is this the same as isWhitelisted? if isAppleMapsURL(url) { UIApplication.shared.open(url, options: [:]) decisionHandler(.cancel) return } if let tab = tabManager.selectedTab, isStoreURL(url) { decisionHandler(.cancel) let alreadyShowingSnackbarOnThisTab = tab.bars.count > 0 if !alreadyShowingSnackbarOnThisTab { TimerSnackBar.showAppStoreConfirmationBar(forTab: tab, appStoreURL: url) } return } // Handles custom mailto URL schemes. if url.scheme == "mailto" { if let mailToMetadata = url.mailToMetadata(), let mailScheme = self.profile.prefs.stringForKey(PrefsKeys.KeyMailToOption), mailScheme != "mailto" { self.mailtoLinkHandler.launchMailClientForScheme(mailScheme, metadata: mailToMetadata, defaultMailtoURL: url) } else { UIApplication.shared.open(url, options: [:]) } LeanPlumClient.shared.track(event: .openedMailtoLink) decisionHandler(.cancel) return } // This is the normal case, opening a http or https url, which we handle by loading them in this WKWebView. We // always allow this. Additionally, data URIs are also handled just like normal web pages. if ["http", "https", "data", "blob", "file"].contains(url.scheme) { if navigationAction.navigationType == .linkActivated { resetSpoofedUserAgentIfRequired(webView, newURL: url) } else if navigationAction.navigationType == .backForward { restoreSpoofedUserAgentIfRequired(webView, newRequest: navigationAction.request) } pendingRequests[url.absoluteString] = navigationAction.request decisionHandler(.allow) return } UIApplication.shared.open(url, options: [:]) { openedURL in // Do not show error message for JS navigated links or redirect as it's not the result of a user action. if !openedURL, navigationAction.navigationType == .linkActivated { let alert = UIAlertController(title: Strings.UnableToOpenURLErrorTitle, message: Strings.UnableToOpenURLError, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.OKString, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } decisionHandler(.cancel) } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { let response = navigationResponse.response let responseURL = response.url var request: URLRequest? if let url = responseURL { request = pendingRequests.removeValue(forKey: url.absoluteString) } // We can only show this content in the web view if this web view is not pending // download via the context menu. let canShowInWebView = navigationResponse.canShowMIMEType && (webView != pendingDownloadWebView) let forceDownload = webView == pendingDownloadWebView // Check if this response should be handed off to Passbook. if let passbookHelper = OpenPassBookHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) { // Clear the network activity indicator since our helper is handling the request. UIApplication.shared.isNetworkActivityIndicatorVisible = false // Open our helper and cancel this response from the webview. passbookHelper.open() decisionHandler(.cancel) return } // Check if this response should be downloaded. if let downloadHelper = DownloadHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) { // Clear the network activity indicator since our helper is handling the request. UIApplication.shared.isNetworkActivityIndicatorVisible = false // Clear the pending download web view so that subsequent navigations from the same // web view don't invoke another download. pendingDownloadWebView = nil // Open our helper and cancel this response from the webview. downloadHelper.open() decisionHandler(.cancel) return } // If the content type is not HTML, create a temporary document so it can be downloaded and // shared to external applications later. Otherwise, clear the old temporary document. if let tab = tabManager[webView] { if response.mimeType != MIMEType.HTML, let request = request { tab.temporaryDocument = TemporaryDocument(preflightResponse: response, request: request) } else { tab.temporaryDocument = nil } } // If none of our helpers are responsible for handling this response, // just let the webview handle it as normal. decisionHandler(.allow) } /// Invoked when an error occurs while starting to load data for the main frame. func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { // Ignore the "Frame load interrupted" error that is triggered when we cancel a request // to open an external application and hand it over to UIApplication.openURL(). The result // will be that we switch to the external app, for example the app store, while keeping the // original web page in the tab instead of replacing it with an error page. let error = error as NSError if error.domain == "WebKitErrorDomain" && error.code == 102 { return } if checkIfWebContentProcessHasCrashed(webView, error: error as NSError) { return } if error.code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) { if let tab = tabManager[webView], tab === tabManager.selectedTab { urlBar.currentURL = tab.url?.displayURL } return } if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) // If the local web server isn't working for some reason (Firefox cellular data is // disabled in settings, for example), we'll fail to load the session restore URL. // We rely on loading that page to get the restore callback to reset the restoring // flag, so if we fail to load that page, reset it here. if url.aboutComponent == "sessionrestore" { tabManager.tabs.filter { $0.webView == webView }.first?.restoring = false } } } fileprivate func checkIfWebContentProcessHasCrashed(_ webView: WKWebView, error: NSError) -> Bool { if error.code == WKError.webContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" { print("WebContent process has crashed. Trying to reload to restart it.") webView.reload() return true } return false } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { // If this is a certificate challenge, see if the certificate has previously been // accepted by the user. let origin = "\(challenge.protectionSpace.host):\(challenge.protectionSpace.port)" if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust, let cert = SecTrustGetCertificateAtIndex(trust, 0), profile.certStore.containsCertificate(cert, forOrigin: origin) { completionHandler(.useCredential, URLCredential(trust: trust)) return } guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM, let tab = tabManager[webView] else { completionHandler(.performDefaultHandling, nil) return } // If this is a request to our local web server, use our private credentials. if challenge.protectionSpace.host == "localhost" && challenge.protectionSpace.port == Int(WebServer.sharedInstance.server.port) { completionHandler(.useCredential, WebServer.sharedInstance.credentials) return } // The challenge may come from a background tab, so ensure it's the one visible. tabManager.selectTab(tab) let loginsHelper = tab.getContentScript(name: LoginsHelper.name()) as? LoginsHelper Authenticator.handleAuthRequest(self, challenge: challenge, loginsHelper: loginsHelper).uponQueue(.main) { res in if let credentials = res.successValue { completionHandler(.useCredential, credentials.credentials) } else { completionHandler(.rejectProtectionSpace, nil) } } } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { guard let tab = tabManager[webView] else { return } tab.url = webView.url self.scrollController.resetZoomState() if tabManager.selectedTab === tab { updateUIForReaderHomeStateForTab(tab) } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { if let tab = tabManager[webView] { navigateInTab(tab: tab, to: navigation) } } }
19c066edf00ea51d434863e5eead1312
45.016181
185
0.650819
false
false
false
false
Vilyan01/BHResting
refs/heads/develop
Example/Tests/BHRestManagerSpec.swift
mit
1
// // BHRestManagerSpec.swift // BHResting // // Created by Brian Heller on 1/12/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Quick import Nimble @testable import BHResting class BHRestManagerSpec: QuickSpec { override func spec() { describe("When setting the base URI") { it("retrieves the base URI") { BHRestManager.shared().setBaseUri(uri: "http://localhost:3000/") expect(BHRestManager.shared().baseUri()) == "http://localhost:3000/" } } describe("After adding additional path components") { it("has those path components in the full Uri") { BHRestManager.shared().setAdditionalPathComponents(components: ["api","v1"]) expect(BHRestManager.shared().fullUri()) == "http://localhost:3000/api/v1/" } } describe("When adding additional headers") { it("saves the additional headers to a variable") { BHRestManager.shared().addAdditionalHeader(header: ["Accept":"application/json"]) expect(BHRestManager.shared().additionalHeaders()!.count) == 1 } } } }
1ccae8b04d9eff37ec1393be0443a5fc
32.108108
97
0.586122
false
false
false
false
snowpunch/AppLove
refs/heads/develop
App Love/Custom/Theme.swift
mit
1
// // Theme.swift // App Love // // Created by Woodie Dovich on 2016-02-27. // Copyright © 2016 Snowpunch. All rights reserved. // // Theme colors for the app. // // cleaned import UIKit internal struct Theme { // dark pastel blue static let defaultColor = UIColor(red: 43/255, green: 85/255, blue: 127/255, alpha: 1.0) static let lighterDefaultColor = UIColor(red: 73/255, green: 115/255, blue: 157/255, alpha: 1.0) static let lightestDefaultColor = UIColor(red: 103/255, green: 145/255, blue: 197/255, alpha: 1.0) static func navigationBar() { let bar = UINavigationBar.appearance() bar.tintColor = .whiteColor() bar.barTintColor = Theme.defaultColor bar.translucent = false bar.barStyle = .Black } static func mailBar(bar:UINavigationBar) { bar.tintColor = .whiteColor() bar.barTintColor = Theme.defaultColor bar.translucent = false bar.barStyle = .Black } static func toolBar(item:UIToolbar) { item.tintColor = .whiteColor() item.barTintColor = Theme.defaultColor item.translucent = false } static func alertController(item:UIAlertController) { item.view.tintColor = Theme.lighterDefaultColor } static func searchBar(item:UISearchBar) { item.barTintColor = Theme.defaultColor item.backgroundImage = UIImage() item.backgroundColor = Theme.defaultColor } }
6bd3c7f6d3e81dd90b3e98657b143417
27.882353
102
0.648098
false
false
false
false
Gofake1/Color-Picker
refs/heads/master
Color Picker/PaletteCollection.swift
mit
1
// // PaletteCollection.swift // Color Picker // // Created by David Wu on 5/8/17. // Copyright © 2017 Gofake1. All rights reserved. // import Cocoa fileprivate let defaultPalettes = [ Palette(name: "Rainbow", colors: [NSColor.red, NSColor.orange, NSColor.yellow, NSColor.green, NSColor.blue, NSColor.purple]), Palette(name: "Grayscale", colors: [NSColor(red: 1, green: 1, blue: 1, alpha: 1), NSColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 1), NSColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1), NSColor(red: 0.25, green: 0.25, blue: 0.25, alpha: 1), NSColor(red: 0, green: 0, blue: 0, alpha: 1)]) ] class PaletteCollection: NSObject, NSCoding { @objc dynamic var palettes: [Palette] override init() { palettes = defaultPalettes } func addPalette(_ palette: Palette) { palettes.append(palette) } func restoreDefaults() { palettes = defaultPalettes } // MARK: - NSCoding required init?(coder aDecoder: NSCoder) { guard let palettes = aDecoder.decodeObject(forKey: "palettesArray") as? [Palette] else { // TODO: warn user about losing saved palettes self.palettes = [] return } self.palettes = palettes } func encode(with aCoder: NSCoder) { aCoder.encode(palettes, forKey: "palettesArray") } }
553345b8d379c6bbae77dd3e76db6c44
27.056604
96
0.574311
false
false
false
false