repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
thatseeyou/SpriteKitExamples.playground
Pages/Position.xcplaygroundpage/Contents.swift
1
7131
/*: ### SKNode의 위치는 어떻게 결정되는가? #### properties - bounding box : Path나 이미지를 감싸고 있는 box. 명시적인 property로 존재하지는 않는다. - anchorPoint : bounding box내에서의 위치 잡는 기준점. (0,0) ~ (1.0, 1.0) 값을 같는다. SKSpriteNode 이외에는 별도의 property로 존재하지 않는다. (0,0) 아니면 (0.5, 0.5)가 기본. - position : AnchorPoint의 위치. - frame : bounding box의 anchorPoint를 position에 맞추면 결정되는 나의 위치와 크기. 기준은 부모 좌표 (read-only) #### SKShape의 anchorPoint - centered : true * bounding box를 계산 후 중심점을 anchorPoint로 계산한다. * shapeNodeWithPath:centered:true * shapeNodeWithCircleOfRadius * shapeNodeWithEllipseOfSize - centered : false * position을 원점으로 삼아서 그림을 그린다. anchorPoint도 (0,0) #### 회전의 중심 - anchorPoint가 회전의 중심이 된다. - anchorPoint는 position에 위치하게 되므로 결국에는 position이 회전의 중심이 되는 것이다. ### 자식의 위치 - 부모의 position이 자식 좌표의 원점이 된다. 부모의 centered가 true/false에 상관없이 position이 같다면 자식의 위치는 동일하게 된다. */ import UIKit import SpriteKit class GameScene: SKScene { var contentCreated = false func showGuide(_ distance:CGFloat) { let maxX = frame.maxX let maxY = frame.maxY let path = UIBezierPath() var y = distance repeat { path.move(to: CGPoint(x: 0, y: y)) path.addLine(to: CGPoint(x: maxX, y: y)) y += distance } while(y < maxY) var x = distance repeat { path.move(to: CGPoint(x: x, y: 0)) path.addLine(to: CGPoint(x: x, y: maxY)) x += distance } while(x < maxX) let shape = SKShapeNode(path: path.cgPath) addChild(shape) } func rectFromPath(parent: SKNode, position: CGPoint, rect:CGRect, centered: Bool, color:SKColor) -> SKNode { let path = UIBezierPath(rect: rect).cgPath let shape = SKShapeNode(path: path, centered: centered) shape.position = position shape.lineWidth = 0.0 shape.fillColor = color parent.addChild(shape) return shape } func rectFromShape(parent: SKNode, position: CGPoint, rect:CGRect, color:SKColor) -> SKNode { let shape = SKShapeNode(rect: rect) shape.position = position shape.lineWidth = 0.0 shape.fillColor = color parent.addChild(shape) return shape } func circle(parent: SKNode, position: CGPoint, radius:CGFloat, color:SKColor) -> SKNode { let shape = SKShapeNode(circleOfRadius: radius) shape.position = position shape.lineWidth = 0.0 shape.fillColor = color parent.addChild(shape) return shape } override func didMove(to view: SKView) { let center = CGPoint(x: self.frame.midX, y: self.frame.midY) showGuide(50) do { let parent = rectFromPath(parent: self, position: center, rect: CGRect(x: 0,y: 0, width: 100, height: 100), centered: false, color: #colorLiteral(red: 0.7540004253387451, green: 0, blue: 0.2649998068809509, alpha: 0.5036368534482759)) parent.frame parent.position let centerOfShape = CGPoint(x: parent.frame.width / 2.0, y: parent.frame.height / 2.0) let child = circle(parent: parent, position: centerOfShape, radius: 50.0, color: #colorLiteral(red: 0.1991284191608429, green: 0.6028449535369873, blue: 0.9592232704162598, alpha: 1)) child.frame // 회전의 중심도 (0,0). 결국엔 positon let parentCopy = parent.copy() as? SKShapeNode parentCopy?.zRotation = 3.141592 * 45.0 / 180.0 self.addChild(parentCopy!) } do { let parent = rectFromPath(parent: self, position: center, rect: CGRect(x: 0,y: 0, width: 100, height: 100), centered: true, color: #colorLiteral(red: 0.1431525945663452, green: 0.4145618975162506, blue: 0.7041897773742676, alpha: 0.5)) parent.frame parent.position // 부모의 position이 자식의 위치를 결정하기 때문에 위의 centered:false 인 경우와 동일 위치에 원이 그려진다. let centerOfShape = CGPoint(x: parent.frame.width / 2.0, y: parent.frame.height / 2.0) let child = circle(parent: parent, position: centerOfShape, radius: 30.0, color: #colorLiteral(red: 1, green: 0.9999743700027466, blue: 0.9999912977218628, alpha: 1)) child.frame // 회전의 중심도 center. 결국엔 position let parentCopy = parent.copy() as? SKShapeNode parentCopy?.zRotation = 3.141592 * 45.0 / 180.0 self.addChild(parentCopy!) } do { // centered = true 인 경우에는 path의 위치가 중요하지 않다. 아래에서 (-200, -200)은 무시된다. let parent = rectFromPath(parent: self, position: center, rect: CGRect(x: -200, y: -200, width: 90, height: 90), centered: true, color: #colorLiteral(red: 0.6000000238418579, green: 0.4000000059604645, blue: 0.2000000029802322, alpha: 0.513604525862069)) parent.frame parent.position } do { let parent = rectFromPath(parent: self, position: center, rect: CGRect(x: -40, y: -40, width: 80, height: 80), centered: false, color: #colorLiteral(red: 0, green: 1, blue: 0, alpha: 0.5)) parent.frame parent.position } do { let parent = rectFromShape(parent: self, position: center, rect: CGRect(x: 10, y: 10, width: 70, height: 70), color: #colorLiteral(red: 1, green: 0.5, blue: 0, alpha: 0.5033405172413793)) parent.frame parent.position } do { let centeredEllipse = SKShapeNode(ellipseOf: CGSize(width: 100, height: 50)) centeredEllipse.position = CGPoint(x: 100, y: 100) addChild(centeredEllipse) let notCenteredEllipse = SKShapeNode(ellipseIn: CGRect(x: 0, y: 0, width: 100, height: 50)) notCenteredEllipse.position = CGPoint(x: 100, y: 100) addChild(notCenteredEllipse) } } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // add SKView do { let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480)) skView.showsFPS = true //skView.showsPhysics = true //skView.showsNodeCount = true skView.ignoresSiblingOrder = true let scene = GameScene(size: CGSize(width: 320, height: 480)) scene.scaleMode = .aspectFit skView.presentScene(scene) self.view.addSubview(skView) } } } PlaygroundHelper.showViewController(ViewController())
isc
db0500b398d5a57530051915ce8990d3
35.027473
266
0.609578
3.323365
false
false
false
false
Hunter-Li-EF/HLAlbumPickerController
HLAlbumPickerController/Classes/HLImageViewController.swift
1
5549
// // HLImageViewController.swift // Pods // // Created by Hunter Li on 9/9/2016. // // import UIKit internal class HLImageViewController: UIViewController, UIScrollViewDelegate{ override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.black automaticallyAdjustsScrollViewInsets = false setupImageView() setupOverlayView() setupUseButton() setupCancelButton() setupCropView() } var image: UIImage? fileprivate var imageView: UIImageView? fileprivate func setupImageView(){ let scrollView = UIScrollView(frame: view.bounds) scrollView.delegate = self scrollView.maximumZoomScale = 2 scrollView.minimumZoomScale = 1 view.addSubview(scrollView) let imageView = UIImageView(frame: scrollView.bounds) imageView.contentMode = .scaleAspectFit imageView.image = image scrollView.addSubview(imageView) self.imageView = imageView } fileprivate var cropView: UIView? private func setupCropView(){ let height: CGFloat = view.bounds.width let cropView = UIView() cropView.frame = CGRect(x: 0, y: (view.bounds.height - height) / 2, width: view.bounds.width, height: height) cropView.isUserInteractionEnabled = false view.addSubview(cropView) self.cropView = cropView let path = UIBezierPath(rect: cropView.frame) path.append(UIBezierPath(rect: view.bounds)) let maskLayer = CAShapeLayer() maskLayer.frame = view.bounds maskLayer.fillColor = UIColor.black.withAlphaComponent(0.5).cgColor maskLayer.path = path.cgPath maskLayer.fillRule = kCAFillRuleEvenOdd view.layer.addSublayer(maskLayer) } fileprivate var overlayView: UIView? fileprivate func setupOverlayView(){ let height: CGFloat = 100 let overlayView = UIView(frame: CGRect(x: 0, y: view.bounds.height - height, width: view.bounds.width, height: height)) overlayView.backgroundColor = UIColor.gray overlayView.alpha = 0.5 view.addSubview(overlayView) self.overlayView = overlayView } private func setupUseButton(){ guard let overlayView = overlayView else{ return } let useButton = UIButton(type: .custom) useButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10) useButton.setTitle("Use", for: .normal) useButton.titleLabel?.font = UIFont.systemFont(ofSize: 17) useButton.setTitleColor(UIColor.white, for: .normal) useButton.addTarget(self, action: #selector(HLImageViewController.use(_:)), for: .touchUpInside) useButton.sizeToFit() useButton.center = CGPoint(x: overlayView.bounds.width - useButton.bounds.width / 2 - 20, y: overlayView.bounds.height / 2) overlayView.addSubview(useButton) } private func setupCancelButton(){ guard let overlayView = overlayView else{ return } let cancelButton = UIButton(type: .custom) cancelButton.setTitle("Cancel", for: .normal) cancelButton.titleLabel?.font = UIFont.systemFont(ofSize: 17) cancelButton.setTitleColor(UIColor.white, for: .normal) cancelButton.addTarget(self, action: #selector(HLImageViewController.cancel(_:)), for: .touchUpInside) cancelButton.sizeToFit() cancelButton.center = CGPoint(x: cancelButton.bounds.width / 2 + 20, y: overlayView.bounds.height / 2) overlayView.addSubview(cancelButton) } func use(_ button: UIButton) { guard let cropView = cropView else{ return } let scale = UIScreen.main.scale let frame = CGRect(x: cropView.frame.minX * scale, y: cropView.frame.minY * scale, width:cropView.frame.width * scale, height: cropView.frame.height * scale) UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, scale) view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let imageRef = image?.cgImage?.cropping(to: frame) else { return } dismiss(animated: true) { if let nav = self.navigationController as? HLAlbumPickerController{ nav.pickerDelegate?.albumPickerController(picker: nav, didFinishPickingImage: UIImage(cgImage: imageRef)) } } } func cancel(_ button: UIButton) { dismiss(animated: true) { if let nav = self.navigationController as? HLAlbumPickerController{ nav.pickerDelegate?.imagePickerControllerDidCancel(picker: nav) } } } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } } extension HLImageViewController{ override public var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } }
mit
e5e558a86f03ddbaf5793b7dba9e597b
34.8
165
0.647504
5.12373
false
false
false
false
nathawes/swift
test/SILGen/synthesized_conformance_enum.swift
9
5042
// RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 | %FileCheck -check-prefix CHECK -check-prefix CHECK-FRAGILE %s // RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 -enable-library-evolution | %FileCheck -check-prefix CHECK -check-prefix CHECK-RESILIENT %s enum Enum<T> { case a(T), b(T) } // CHECK-LABEL: enum Enum<T> { // CHECK: case a(T), b(T) // CHECK: } enum NoValues { case a, b } // CHECK-LABEL: enum NoValues { // CHECK: case a, b // CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: NoValues, _ b: NoValues) -> Bool // CHECK-RESILIENT: static func == (a: NoValues, b: NoValues) -> Bool // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK-LABEL: extension Enum : Equatable where T : Equatable { // CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Enum<T>, _ b: Enum<T>) -> Bool // CHECK-RESILIENT: static func == (a: Enum<T>, b: Enum<T>) -> Bool // CHECK: } // CHECK-LABEL: extension Enum : Hashable where T : Hashable { // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK-LABEL: extension NoValues : CaseIterable { // CHECK: typealias AllCases = [NoValues] // CHECK: static var allCases: [NoValues] { get } // CHECK: } extension Enum: Equatable where T: Equatable {} // CHECK-FRAGILE-LABEL: // static Enum<A>.__derived_enum_equals(_:_:) // CHECK-FRAGILE-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASQRzlE010__derived_C7_equalsySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Enum<T>, @in_guaranteed Enum<T>, @thin Enum<T>.Type) -> Bool { // CHECK-RESILIENT-LABEL: // static Enum<A>.== infix(_:_:) // CHECK-RESILIENT-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASQRzlE2eeoiySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Enum<T>, @in_guaranteed Enum<T>, @thin Enum<T>.Type) -> Bool { extension Enum: Hashable where T: Hashable {} // CHECK-LABEL: // Enum<A>.hashValue.getter // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASHRzlE9hashValueSivg : $@convention(method) <T where T : Hashable> (@in_guaranteed Enum<T>) -> Int { // CHECK-LABEL: // Enum<A>.hash(into:) // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASHRzlE4hash4intoys6HasherVz_tF : $@convention(method) <T where T : Hashable> (@inout Hasher, @in_guaranteed Enum<T>) -> () { extension NoValues: CaseIterable {} // CHECK-LABEL: // static NoValues.allCases.getter // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum8NoValuesO8allCasesSayACGvgZ : $@convention(method) (@thin NoValues.Type) -> @owned Array<NoValues> { // Witness tables for Enum // CHECK-LABEL: sil_witness_table hidden <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum { // CHECK-NEXT: method #Equatable."==": <Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool : @$s28synthesized_conformance_enum4EnumOyxGSQAASQRzlSQ2eeoiySbx_xtFZTW // protocol witness for static Equatable.== infix(_:_:) in conformance <A> Enum<A> // CHECK-NEXT: conditional_conformance (T: Equatable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Hashable> Enum<T>: Hashable module synthesized_conformance_enum { // CHECK-DAG: base_protocol Equatable: <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum // CHECK-DAG: method #Hashable.hashValue!getter: <Self where Self : Hashable> (Self) -> () -> Int : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH9hashValueSivgTW // protocol witness for Hashable.hashValue.getter in conformance <A> Enum<A> // CHECK-DAG: method #Hashable.hash: <Self where Self : Hashable> (Self) -> (inout Hasher) -> () : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH4hash4intoys6HasherVz_tFTW // protocol witness for Hashable.hash(into:) in conformance <A> Enum<A> // CHECK-DAG: method #Hashable._rawHashValue: <Self where Self : Hashable> (Self) -> (Int) -> Int : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH13_rawHashValue4seedS2i_tFTW // protocol witness for Hashable._rawHashValue(seed:) in conformance <A> Enum<A> // CHECK-DAG: conditional_conformance (T: Hashable): dependent // CHECK: } // Witness tables for NoValues // CHECK-LABEL: sil_witness_table hidden NoValues: CaseIterable module synthesized_conformance_enum { // CHECK-NEXT: associated_type_protocol (AllCases: Collection): [NoValues]: specialize <NoValues> (<Element> Array<Element>: Collection module Swift) // CHECK-NEXT: associated_type AllCases: Array<NoValues> // CHECK-NEXT: method #CaseIterable.allCases!getter: <Self where Self : CaseIterable> (Self.Type) -> () -> Self.AllCases : @$s28synthesized_conformance_enum8NoValuesOs12CaseIterableAAsADP8allCases03AllI0QzvgZTW // protocol witness for static CaseIterable.allCases.getter in conformance NoValues // CHECK-NEXT: }
apache-2.0
7cf515e44cfdc99df26aa7f76cb9f15a
63.641026
296
0.716977
3.418305
false
false
false
false
uber/rides-ios-sdk
source/UberRides/Model/RideReceipt.swift
1
4972
// // RideReceipt.swift // UberRides // // Copyright © 2016 Uber Technologies, Inc. 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. // MARK: RideReceipt /** * Get the receipt information of a completed request that was made with the request endpoint. */ @objc(UBSDKRideReceipt) public class RideReceipt: NSObject, Codable { /// Adjustments made to the charges such as promotions, and fees. @objc public private(set) var chargeAdjustments: [RideCharge]? /// ISO 4217 @objc public private(set) var currencyCode: String? /// Distance of the trip charged. @objc public private(set) var distance: String? /// The localized unit of distance. @objc public private(set) var distanceLabel: String? /// Time duration of the trip. Use only the hour, minute, and second components. @objc public private(set) var duration: DateComponents? /// Unique identifier representing a Request. @objc public private(set) var requestID: String? /// The summation of the normal fare and surge charge amount. @objc public private(set) var subtotal: String? /// The total amount charged to the users payment method. This is the the subtotal (split if applicable) with taxes included. @objc public private(set) var totalCharged: String? /// The total amount still owed after attempting to charge the user. May be 0 if amount was paid in full. @nonobjc public private(set) var totalOwed: Double? /// The total amount still owed after attempting to charge the user. May be 0 if amount was paid in full. @objc(totalOwed) public var objc_totalOwed: NSNumber? { if let totalOwed = totalOwed { return NSNumber(value: totalOwed) } else { return nil } } /// The fare after credits and refunds have been applied. @objc public private(set) var totalFare: String? enum CodingKeys: String, CodingKey { case chargeAdjustments = "charge_adjustments" case currencyCode = "currency_code" case distance = "distance" case distanceLabel = "distance_label" case duration = "duration" case requestID = "request_id" case subtotal = "subtotal" case totalCharged = "total_charged" case totalOwed = "total_owed" case totalFare = "total_fare" } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) chargeAdjustments = try container.decodeIfPresent([RideCharge].self, forKey: .chargeAdjustments) currencyCode = try container.decodeIfPresent(String.self, forKey: .currencyCode) distance = try container.decodeIfPresent(String.self, forKey: .distance) distanceLabel = try container.decodeIfPresent(String.self, forKey: .distanceLabel) requestID = try container.decodeIfPresent(String.self, forKey: .requestID) subtotal = try container.decodeIfPresent(String.self, forKey: .subtotal) totalCharged = try container.decodeIfPresent(String.self, forKey: .totalCharged) totalOwed = try container.decodeIfPresent(Double.self, forKey: .totalOwed) ?? 0.0 totalFare = try container.decodeIfPresent(String.self, forKey: .totalFare) let durationString = try container.decodeIfPresent(String.self, forKey: .duration) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm:ss" dateFormatter.calendar = Calendar.current var date = Date(timeIntervalSince1970: 0) if let durationString = durationString, let dateFromDuration = dateFormatter.date(from: durationString) { date = dateFromDuration } duration = Calendar.current.dateComponents(in: TimeZone.current, from: date) } }
mit
61f38aae6fcd6a63a51b1203c4f81a54
45.457944
129
0.692215
4.564738
false
false
false
false
Punch-In/PunchInIOSApp
PunchIn/MKImageView.swift
1
3464
// // MKImageView.swift // MaterialKit // // Created by Le Van Nghia on 11/29/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit @IBDesignable public class MKImageView: UIImageView { @IBInspectable public var maskEnabled: Bool = true { didSet { mkLayer.enableMask(maskEnabled) } } @IBInspectable public var rippleLocation: MKRippleLocation = .TapLocation { didSet { mkLayer.rippleLocation = rippleLocation } } @IBInspectable public var rippleAniDuration: Float = 0.75 @IBInspectable public var backgroundAniDuration: Float = 1.0 @IBInspectable public var rippleAniTimingFunction: MKTimingFunction = .Linear @IBInspectable public var backgroundAniTimingFunction: MKTimingFunction = .Linear @IBInspectable public var backgroundAniEnabled: Bool = true { didSet { if !backgroundAniEnabled { mkLayer.enableOnlyCircleLayer() } } } @IBInspectable public var ripplePercent: Float = 0.9 { didSet { mkLayer.ripplePercent = ripplePercent } } @IBInspectable public var cornerRadius: CGFloat = 2.5 { didSet { layer.cornerRadius = cornerRadius mkLayer.setMaskLayerCornerRadius(cornerRadius) } } // color @IBInspectable public var rippleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) { didSet { mkLayer.setCircleLayerColor(rippleLayerColor) } } @IBInspectable public var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) { didSet { mkLayer.setBackgroundLayerColor(backgroundLayerColor) } } override public var bounds: CGRect { didSet { mkLayer.superLayerDidResize() } } private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer) required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setup() } override public init(frame: CGRect) { super.init(frame: frame) setup() } override public init(image: UIImage!) { super.init(image: image) setup() } override public init(image: UIImage!, highlightedImage: UIImage?) { super.init(image: image, highlightedImage: highlightedImage) setup() } private func setup() { mkLayer.setCircleLayerColor(rippleLayerColor) mkLayer.setBackgroundLayerColor(backgroundLayerColor) mkLayer.setMaskLayerCornerRadius(cornerRadius) } public func animateRipple(location: CGPoint? = nil) { if let point = location { mkLayer.didChangeTapLocation(point) } else if rippleLocation == .TapLocation { rippleLocation = .Center } mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: rippleAniTimingFunction, duration: CFTimeInterval(self.rippleAniDuration)) mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(self.backgroundAniDuration)) } override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) if let firstTouch = touches.first as UITouch! { let location = firstTouch.locationInView(self) animateRipple(location) } } }
mit
ddabef05a4a0596aa2b40eb1a79642f4
30.207207
153
0.648961
5.094118
false
false
false
false
kazedayo/GaldenApp
GaldenApp/Custom Classes/ThreadList.swift
1
616
// // ThreadList.swift // GaldenApp // // Created by Kin Wa Lam on 30/9/2017. // Copyright © 2017年 1080@galden. All rights reserved. // import UIKit class ThreadList { //Properties var id: String var ident: String var title: String var userName: String var count: String var rate: String var userID: String init(iD: String, iDent: String, tit: String, userN: String, cnt: String, rt: String,uid: String) { id = iD ident = iDent title = tit userName = userN count = cnt rate = rt userID = uid } }
mit
3316177bd4d12c5102b7eb10e584d64b
18.15625
102
0.574225
3.670659
false
false
false
false
cpoutfitters/cpoutfitters
CPOutfitters/Post.swift
1
1155
// // Post.swift // CPOutfitters // // Created by Cory Thompson on 4/6/16. // Copyright © 2016 SnazzyLLama. All rights reserved. // import UIKit import Parse class Post: NSObject { class func postUserImage(image: UIImage?, withCaption caption: NSString?, withCompletion completion: PFBooleanResultBlock?) { let post = PFObject(className: "Post") post["image"] = Article.getPFFileFromImage(image) post["author"] = PFUser.currentUser() post["caption"] = caption post.saveInBackgroundWithBlock(completion) } class func postOutfit(topImage: UIImage?, bottomImage: UIImage?, footwearImage: UIImage?, withCaption caption: NSString?, withCompletion completion: PFBooleanResultBlock?) { let post = PFObject(className: "Post") post["topImage"] = Article.getPFFileFromImage(topImage) post["bottomImage"] = Article.getPFFileFromImage(bottomImage) post["footwearImage"] = Article.getPFFileFromImage(footwearImage) post["author"] = PFUser.currentUser() post["caption"] = caption post.saveInBackgroundWithBlock(completion) } }
apache-2.0
ab2bc333f58c4893ded6e922de68f895
35.0625
177
0.682842
4.371212
false
false
false
false
Molecularts/loopback-sdk-ios-swift2
Source/User.swift
1
3952
// // User.swift // LoopBackSwift // // Created by Oscar Anton on 27/6/16. // Copyright © 2016 Molecularts. All rights reserved. // import Foundation import ObjectMapper import BrightFutures import ObjectMapper public protocol UserModel: PersistedModel{ var realm: String? { get set } var username: String? { get set } var password: String? { get set } var email: String { get set } var emailVerified: Bool { get set } } extension Repository where Model : UserModel{ public func login(email: String, password: String) -> Future<Model?, LoopBackError> { let promise : Promise = Promise<Model?, LoopBackError>() let params:[String: AnyObject] = ["email" : email, "password": password] let request: Request = self.prepareRequest(.POST, absolutePath: Model.modelName() + "/login", parameters: params) request.responseObject { (response : Response<AccessToken, NSError>) in guard (response.result.isSuccess) else{ let jsonString = NSString(data: response.data!, encoding: NSASCIIStringEncoding) var error: LoopBackError? = Mapper<LoopBackError>().map(jsonString!) if error == nil { error = LoopBackError(httpCode:HTTPStatusCode.ServiceUnavailable, message: "") } error?.error = response.result.error promise.failure(error!) return } let model = response.result.value self.client.accessToken = model?.id AccessToken.current = model self.findById((model?.userId)!).onSuccess(callback: { (user: Model?) in self.currentUser = user promise.success(user) }).onFailure(callback: { (error: LoopBackError) in promise.failure(error) }) } return promise.future } public func logout() -> Future<Bool,LoopBackError>{ let promise = Promise<Bool, LoopBackError>() if(self.client.accessToken != nil){ let request: Request = prepareRequest(.POST, absolutePath: Model.modelName() + "/logout", parameters: ["access_token": self.client.accessToken!]) processAnyRequest(request).onSuccess { (anyObject: AnyObject?) in self.client.accessToken = nil AccessToken.current = nil self.currentUser = nil if anyObject != nil { promise.success(true) }else { promise.success(false) } }.onFailure { (error : LoopBackError) in promise.failure(error) } }else{ let error = LoopBackError(httpCode: .UnprocessableEntity, message: "You dont have a valid AccessToken, please login first") promise.failure(error) } return promise.future } public var currentUser: Model?{ get{ return Repository<Model>.currentUser } set { Repository<Model>.currentUser = newValue } } public static var currentUser: Model?{ get{ let defaults = NSUserDefaults.standardUserDefaults() let userDict: NSDictionary? = defaults.objectForKey(LoopBackConstants.currentUserKey) as? NSDictionary return Mapper<Model>().map(userDict) } set(newUser){ let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(newUser?.toJSON(), forKey: LoopBackConstants.currentUserKey) } } }
mit
55dd10ba922f44af408905cff1b0fcaa
30.862903
157
0.543913
5.282086
false
false
false
false
mcddx330/Pumpkin
Pumpkin/PKSceneExtension.swift
1
2060
// // PKSceneExtension.swift // Pumpkin // // Created by dimbow. on 2/6/15. // Copyright (c) 2015 dimbow. All rights reserved. // import SpriteKit extension SKScene{ public func PKshowGridLines(color:UIColor?=UIColor.whiteColor()){ let linevertical = SKSpriteNode(color: color!, size: CGSizeMake(PKPosition.Height.Full.cgfloat, 1)); linevertical.position = CGPoint(x:PKPosition.Width.Middle.cgfloat, y: PKPosition.Height.Middle.cgfloat) let lineverticaldown = SKSpriteNode(color: color!, size: CGSizeMake(PKPosition.Width.Full.cgfloat, 1)); lineverticaldown.position = CGPoint(x:PKPosition.Width.Middle.cgfloat, y: PKPosition.Height.MiddleDown.cgfloat); let lineverticalUp = SKSpriteNode(color: color!, size: CGSizeMake(PKPosition.Width.Full.cgfloat, 1)); lineverticalUp.position = CGPoint(x:PKPosition.Width.Middle.cgfloat, y: PKPosition.Height.MiddleUp.cgfloat); let linehorizonal = SKSpriteNode(color: color!, size: CGSizeMake(1, PKPosition.Height.Full.cgfloat)); linehorizonal.position = CGPoint(x:PKPosition.Width.MiddleLeft.cgfloat, y: PKPosition.Height.Middle.cgfloat) let linehorizonalleft = SKSpriteNode(color: color!, size: CGSizeMake(1, PKPosition.Height.Full.cgfloat)); linehorizonalleft.position = CGPoint(x:PKPosition.Width.Middle.cgfloat, y: PKPosition.Height.Middle.cgfloat); let linehorizonalright = SKSpriteNode(color: color!, size: CGSizeMake(1, PKPosition.Height.Full.cgfloat)); linehorizonalright.position = CGPoint(x:PKPosition.Width.MiddleRight.cgfloat, y: PKPosition.Height.Middle.cgfloat); let lines = [linevertical,lineverticaldown,lineverticalUp,linehorizonal,linehorizonalleft,linehorizonalright]; for (var i=0;i<lines.count;i++){ lines[i].zPosition = CGFloat.max; self.addChild(lines[i]); } } public func PKfetchViewSize()->(Height:CGFloat,Width:CGFloat){ return (PKPosition.Height.Full.cgfloat,PKPosition.Width.Full.cgfloat); } }
mit
bf20eccc129fd348a5a69070667f17ee
54.702703
123
0.718447
3.765996
false
false
false
false
iossocket/TravisDemo
TravisDemoTests/SimpleValidationSpec.swift
1
2003
// // SimpleValidationSpec.swift // TravisDemo // // Created by Xueliang Zhu on 1/26/16. // Copyright © 2016 Xueliang Zhu. All rights reserved. // import Quick import Nimble class SimpleValidationSpec: QuickSpec { override func spec() { describe("userNameValidate") { var validationService: PValidationService! beforeEach { validationService = SimpleValidationService() } it("should return empty error") { let result = validationService.userNameValidate("") expect(result).to(equal(ValidationErrorType.EmptyError)) } it("should return user name error") { let result = validationService.userNameValidate("aa") expect(result).to(equal(ValidationErrorType.UserNameError)) } it("should return no error") { let result = validationService.userNameValidate("[email protected]") expect(result).to(equal(ValidationErrorType.NoError)) } } describe("passwordValidate") { var validationService: PValidationService! beforeEach { validationService = SimpleValidationService() } it("should return empty error") { let result = validationService.passwordValidate("") expect(result).to(equal(ValidationErrorType.EmptyError)) } it("should return password min error") { let result = validationService.passwordValidate("123") expect(result).to(equal(ValidationErrorType.PasswordMinError)) } it("should return no error") { let result = validationService.passwordValidate("12345678") expect(result).to(equal(ValidationErrorType.NoError)) } } } }
mit
7ca5c3ebab46bfac51c237ee29a37433
32.932203
78
0.554945
5.703704
false
false
false
false
fgengine/quickly
Quickly/Compositions/Standart/Placeholders/QPlaceholderImageTitleDetailShapeComposition.swift
1
8106
// // Quickly // open class QPlaceholderImageTitleDetailShapeComposable : QComposable { public var imageStyle: QImageViewStyleSheet public var imageWidth: CGFloat public var imageSpacing: CGFloat public var titleStyle: QPlaceholderStyleSheet public var titleHeight: CGFloat public var titleSpacing: CGFloat public var detailStyle: QPlaceholderStyleSheet public var detailHeight: CGFloat public var shapeModel: QShapeView.Model public var shapeWidth: CGFloat public var shapeSpacing: CGFloat public init( edgeInsets: UIEdgeInsets = UIEdgeInsets.zero, imageStyle: QImageViewStyleSheet, imageWidth: CGFloat = 96, imageSpacing: CGFloat = 4, titleStyle: QPlaceholderStyleSheet, titleHeight: CGFloat, titleSpacing: CGFloat = 4, detailStyle: QPlaceholderStyleSheet, detailHeight: CGFloat, shapeModel: QShapeView.Model, shapeWidth: CGFloat = 16, shapeSpacing: CGFloat = 4 ) { self.imageStyle = imageStyle self.imageWidth = imageWidth self.imageSpacing = imageSpacing self.titleStyle = titleStyle self.titleHeight = titleHeight self.titleSpacing = titleSpacing self.detailStyle = detailStyle self.detailHeight = detailHeight self.shapeModel = shapeModel self.shapeWidth = shapeWidth self.shapeSpacing = shapeSpacing super.init(edgeInsets: edgeInsets) } } open class QPlaceholderImageTitleDetailShapeComposition< Composable: QPlaceholderImageTitleDetailShapeComposable > : QComposition< Composable > { public private(set) lazy var imageView: QImageView = { let view = QImageView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var titleView: QPlaceholderView = { let view = QPlaceholderView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var detailView: QPlaceholderView = { let view = QPlaceholderView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var shapeView: QShapeView = { let view = QShapeView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() private var _edgeInsets: UIEdgeInsets? private var _imageWidth: CGFloat? private var _imageSpacing: CGFloat? private var _titleHeight: CGFloat? private var _titleSpacing: CGFloat? private var _detailHeight: CGFloat? private var _shapeWidth: CGFloat? private var _shapeSpacing: CGFloat? private var _constraints: [NSLayoutConstraint] = [] { willSet { self.contentView.removeConstraints(self._constraints) } didSet { self.contentView.addConstraints(self._constraints) } } private var _imageConstraints: [NSLayoutConstraint] = [] { willSet { self.imageView.removeConstraints(self._imageConstraints) } didSet { self.imageView.addConstraints(self._imageConstraints) } } private var _titleConstraints: [NSLayoutConstraint] = [] { willSet { self.titleView.removeConstraints(self._titleConstraints) } didSet { self.titleView.addConstraints(self._titleConstraints) } } private var _detailConstraints: [NSLayoutConstraint] = [] { willSet { self.detailView.removeConstraints(self._detailConstraints) } didSet { self.detailView.addConstraints(self._detailConstraints) } } private var _shapeConstraints: [NSLayoutConstraint] = [] { willSet { self.shapeView.removeConstraints(self._shapeConstraints) } didSet { self.shapeView.addConstraints(self._shapeConstraints) } } open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize { let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right) let imageSize = composable.imageStyle.size(CGSize(width: composable.imageWidth, height: availableWidth)) let shapeSize = composable.shapeModel.size return CGSize( width: spec.containerSize.width, height: composable.edgeInsets.top + max(imageSize.height, composable.titleHeight + composable.titleSpacing + composable.detailHeight, shapeSize.height) + composable.edgeInsets.bottom ) } open override func preLayout(composable: Composable, spec: IQContainerSpec) { if self._edgeInsets != composable.edgeInsets || self._imageSpacing != composable.imageSpacing || self._titleSpacing != composable.titleSpacing || self._shapeSpacing != composable.shapeSpacing { self._edgeInsets = composable.edgeInsets self._imageSpacing = composable.imageSpacing self._titleSpacing = composable.titleSpacing self._shapeSpacing = composable.shapeSpacing self._constraints = [ self.imageView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.imageView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left), self.imageView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.titleView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing), self.titleView.trailingLayout == self.shapeView.leadingLayout.offset(-composable.shapeSpacing), self.titleView.bottomLayout <= self.detailView.topLayout.offset(-composable.titleSpacing), self.detailView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing), self.detailView.trailingLayout == self.shapeView.leadingLayout.offset(-composable.shapeSpacing), self.detailView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.shapeView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.shapeView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.shapeView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom) ] } if self._imageWidth != composable.imageWidth { self._imageWidth = composable.imageWidth self._imageConstraints = [ self.imageView.widthLayout == composable.imageWidth ] } if self._titleHeight != composable.titleHeight { self._titleHeight = composable.titleHeight self._titleConstraints = [ self.titleView.heightLayout == composable.titleHeight ] } if self._detailHeight != composable.detailHeight { self._detailHeight = composable.detailHeight self._detailConstraints = [ self.detailView.heightLayout == composable.detailHeight ] } if self._shapeWidth != composable.shapeWidth { self._shapeWidth = composable.shapeWidth self._shapeConstraints = [ self.shapeView.widthLayout == composable.shapeWidth ] } } open override func apply(composable: Composable, spec: IQContainerSpec) { self.imageView.apply(composable.imageStyle) self.titleView.apply(composable.titleStyle) self.detailView.apply(composable.detailStyle) self.shapeView.model = composable.shapeModel } }
mit
e18f43659193f0453cbef12c12da61dc
45.586207
201
0.684185
5.636996
false
false
false
false
sync/NearbyTrams
NearbyTramsStorageKit/Source/NSManagedObject+REST.swift
1
2770
// // Copyright (c) 2014 Dblechoc. All rights reserved. // import CoreData public protocol RESTManagedObject: InsertAndFetchManagedObject { class func primaryKeyValueFromRest(dictionary: NSDictionary) -> String? class func insertOrUpdateWithDictionaryFromRest<T where T: NSManagedObject, T: RESTManagedObject>(dictionary: NSDictionary, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> (T?, NSError?) class func insertOrUpdateFromRestArray<T where T: NSManagedObject, T: RESTManagedObject>(array: [NSDictionary], inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> ([T?], [NSError?]) mutating func configureWithDictionaryFromRest(dictionary: NSDictionary) -> Void } public extension NSManagedObject { public class func insertOrUpdateWithDictionaryFromRest<T where T: NSManagedObject, T: RESTManagedObject>(dictionary: NSDictionary, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> (T?, NSError?) { var foundManagedObject: T? let primaryKeyValue : String? = T.primaryKeyValueFromRest(dictionary) if primaryKeyValue.hasValue { let result: (managedObject: T?, error: NSError?) = fetchOneForPrimaryKeyValue(primaryKeyValue!, usingManagedObjectContext: managedObjectContext) foundManagedObject = result.managedObject } else { // FIXME: build a decent error here let error = NSError() return (nil, error) } var managedObject: T if foundManagedObject.hasValue { managedObject = foundManagedObject! } else { managedObject = insertInManagedObjectContext(managedObjectContext) as T managedObject.setValue(primaryKeyValue, forKey: T.primaryKey) managedObjectContext.obtainPermanentIDsForObjects([managedObject], error: nil) } managedObject.configureWithDictionaryFromRest(dictionary as NSDictionary) return (managedObject, nil) } public class func insertOrUpdateFromRestArray<T where T: NSManagedObject, T: RESTManagedObject>(array: [NSDictionary], inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> ([T?], [NSError?]) { var managedObjects: [T?] = [] var errors: [NSError?] = [] for dictionary in array { let result = self.insertOrUpdateWithDictionaryFromRest(dictionary, inManagedObjectContext: managedObjectContext) as (managedObject: T?, error: NSError?) managedObjects.append(result.managedObject) errors.append(result.error) } return (managedObjects, errors) } }
mit
b7cfbada789abee6a6875ca35c9e9d97
42.968254
221
0.69278
5.641548
false
false
false
false
fightjc/Paradise_Lost
Paradise Lost/Classes/Views/Tool/BarCodeView.swift
3
8263
// // BarCodeView.swift // Paradise Lost // // Created by Jason Chen on 5/30/16. // Copyright © 2016 Jason Chen. All rights reserved. // import UIKit protocol BarCodeViewDelegate { func tapSoundImage() func tapVibraImage() func copyButtonAction(_ result: String?) func tapReader() } class BarCodeView: UIView { var delegate: BarCodeViewDelegate? = nil var isSoundOn: Bool { didSet { if isSoundOn { soundImage.image = UIImage(named: "SoundOn") } else { soundImage.image = UIImage(named: "SoundOff") } } } var isVibraOn: Bool { didSet { if isVibraOn { vibraImage.image = UIImage(named: "VibraOn") } else { vibraImage.image = UIImage(named: "VibraOff") } } } // MARK: life cycle override init(frame: CGRect) { self.isSoundOn = true self.isVibraOn = true super.init(frame: frame) self.backgroundColor = UIColor.white setupView() } required init?(coder aDecoder: NSCoder) { self.isSoundOn = true self.isVibraOn = true super.init(coder: aDecoder) } fileprivate func setupView() { // subview addSubview(titleLabel) addSubview(reader) addSubview(resultLabel) addSubview(resultText) addSubview(clearButton) addSubview(copyButton) addSubview(soundImage) addSubview(vibraImage) // action clearButton.addTarget(self, action: #selector(BarCodeView.clearResult), for: .touchUpInside) copyButton.addTarget(self, action: #selector(BarCodeView.copyResult), for: .touchUpInside) let soundTap = UITapGestureRecognizer(target: self, action: #selector(BarCodeView.changeSound)) soundImage.addGestureRecognizer(soundTap) let vibraTap = UITapGestureRecognizer(target: self, action: #selector(BarCodeView.changeVibra)) vibraImage.addGestureRecognizer(vibraTap) let gesture = UITapGestureRecognizer(target: self, action: #selector(BarCodeView.tapReader)) reader.addGestureRecognizer(gesture) } override func layoutSubviews() { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-84-[v0(40)]-20-[v1(334)]-[v2(30)]-[v3(54)]-[v4(25)]-20-[v5(36)]-69-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": titleLabel, "v1": reader, "v2": resultLabel, "v3": resultText, "v4": clearButton, "v5": soundImage])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-586-[v0(25)]-20-[v1(36)]-69-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": copyButton, "v1": vibraImage])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": titleLabel])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-40-[v0(334)]-40-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": reader])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": resultLabel])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": resultText])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-150-[v0(53)]-[v1(53)]-150-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": clearButton, "v1": copyButton])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0(36)]-20-[v1(36)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": soundImage, "v1": vibraImage])) } // MARK: event response @objc func clearResult() { resultText.text = LanguageManager.getToolString(forKey: "barcode.resulttext.text") } @objc func copyResult() { delegate?.copyButtonAction(resultText.text) } @objc func changeSound() { isSoundOn = !isSoundOn delegate?.tapSoundImage() } @objc func changeVibra() { isVibraOn = !isVibraOn delegate?.tapVibraImage() } @objc func tapReader() { delegate?.tapReader() } func hasResult(_ result: String) { if result.isEmpty { resultText.text = LanguageManager.getToolString(forKey: "barcode.resulttext.text") } else { resultText.text = result } } // MARK: getters and setters fileprivate var titleLabel: UILabel = { var label = UILabel() label.text = LanguageManager.getToolString(forKey: "barcode.titlelabel.text") label.font = UIFont.boldSystemFont(ofSize: 36) label.textAlignment = .center label.translatesAutoresizingMaskIntoConstraints = false return label }() var reader: UIView = { var view = UIView() view.translatesAutoresizingMaskIntoConstraints = false let label = UILabel() label.text = LanguageManager.getToolString(forKey: "barcode.reader.label.text") label.textAlignment = .center label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) let width = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 300) let height = NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20) let centerX = NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0) let centerY = NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0) NSLayoutConstraint.activate([width, height, centerX, centerY]) return view }() fileprivate var resultLabel: UILabel = { var label = UILabel() label.text = LanguageManager.getToolString(forKey: "barcode.resultlabel.text") label.font = UIFont.boldSystemFont(ofSize: 20) label.textAlignment = .center label.translatesAutoresizingMaskIntoConstraints = false return label }() fileprivate var resultText: UITextView = { var textView = UITextView() textView.text = LanguageManager.getToolString(forKey: "barcode.resulttext.text") textView.textAlignment = .center textView.font = UIFont.systemFont(ofSize: 20) textView.isUserInteractionEnabled = false textView.translatesAutoresizingMaskIntoConstraints = false return textView }() fileprivate var clearButton: UIButton = { var button = UIButton(type: .system) button.setTitle(LanguageManager.getPublicString(forKey: "clear"), for: UIControlState()) button.isExclusiveTouch = true button.translatesAutoresizingMaskIntoConstraints = false return button }() fileprivate var copyButton: UIButton = { var button = UIButton(type: .system) button.setTitle(LanguageManager.getPublicString(forKey: "copy"), for: UIControlState()) button.isExclusiveTouch = true button.translatesAutoresizingMaskIntoConstraints = false return button }() fileprivate var soundImage: UIImageView = { var imageView = UIImageView() imageView.image = UIImage(named: "SoundOn") imageView.isUserInteractionEnabled = true imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() fileprivate var vibraImage: UIImageView = { var imageView = UIImageView() imageView.image = UIImage(named: "VibraOn") imageView.isUserInteractionEnabled = true imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() }
mit
a2849be503c206a754b8c5d371755dc3
38.913043
311
0.648148
4.696987
false
false
false
false
speee/jsonschema2swift
jsonschema2swift/SwiftyJSONSchema/Entity/JsonSchemaEntity.swift
1
9522
// // JsonSchemaEntity.swift // jsonschema2swift // // Created by hayato.iida on 2016/08/30. // Copyright © 2016年 Speee, Inc. All rights reserved. // import Foundation protocol JsonSchema { var json: JSON { get set } var rootJSON: JSON { get set } init() } protocol Referenceable: JsonSchema { var ref: String? { get set } } extension Referenceable { init?(json: JSON, rootJSON: JSON) { guard !json.isEmpty else { return nil } self.init() self.rootJSON = rootJSON if let ref = json["$ref"].string { // schemaが参照形式の場合 self.json = json.extract(ref, rootJSON: rootJSON) self.ref = ref } else { self.json = json } } init?(byRootJSON: JSON) { self.init(json: byRootJSON, rootJSON: byRootJSON) } init?(byRef: String, rootJSON: JSON) { self.init(json: rootJSON.extract(byRef, rootJSON: rootJSON), rootJSON: rootJSON) self.ref = byRef } } protocol RootSchemaProtocol: JsonSchema { var links: [LinkSchema]? { get } var properties: [String: PropertySchema]? { get } var required: [String] { get } var title: String? { get } var description: String? { get } } extension RootSchemaProtocol { var title: String? { get { return json["title"].string } } var description: String? { get { return json["description"].string } } var links: [LinkSchema]? { get { return json["links"].array?.map { LinkSchema(json: $0, rootJSON: rootJSON) } } } var properties: [String: PropertySchema]? { get { return json["properties"].dictionaryValue.mapPairs { ($0, PropertySchema(json: $1, rootJSON: self.rootJSON)!) } } } var required: [String] { get { return json["required"].arrayValue.map { $0.stringValue } } } } /// type /// typeは必ず配列形式で記載し、2個以内とする /// 2個指定する場合は、片方を"null"にする /// ["String", "Integer"]と記載すると、型を定義できないため enum ConcreteType: String { case null = "null" case array = "array" case object = "object" case boolean = "boolean" case integer = "integer" case number = "number" case string = "string" } protocol TypeSchema: JsonSchema { var items: DefinitionSchema? { get } var type: [ConcreteType]? { get } var format: String? { get } var oneOf: [PropertySchema]? { get } var ref: String? { get set } var enumValues: [String]? { get } /// 独自定義 var enumDescription: [EnumDescription]? { get } var media: MediaSchema? { get } var title: String? { get } var description: String? { get } } extension TypeSchema { var title: String? { get { return json["title"].string } } var description: String? { get { return json["description"].string } } var enumValues: [String]? { get { return json["enum"].array?.map { $0.stringValue } } } var type: [ConcreteType]? { get { return json["type"].array?.map { ConcreteType(rawValue: $0.stringValue)! } } } var format: String? { get { return json["format"].string } } var items: DefinitionSchema? { get { return DefinitionSchema(json: json["items"], rootJSON: rootJSON) } } var media: MediaSchema? { get { return MediaSchema(json: json["media"]) } } /// 独自定義 var enumDescription: [EnumDescription]? { get { return json["enumDescription"].array?.map { EnumDescription(json: $0, rootJSON: rootJSON) } } } var oneOf: [PropertySchema]? { get { return json["oneOf"].array?.map { PropertySchema(json: $0, rootJSON: rootJSON)! } } } } struct Schema: Referenceable, TypeSchema, RootSchemaProtocol { var json: JSON var rootJSON: JSON var ref: String? init() { self.json = [:] self.rootJSON = [:] } var schema: String? { get { return json["$schema"].string } } var type: [String]? { get { return json["type"].array?.map { $0.stringValue } } } var definitions: [String: DefinitionSchema]? { get { return json["definitions"].dictionaryValue.mapPairs { ($0, DefinitionSchema(json: $1, rootJSON: self.rootJSON)!) } } } var id: String? { get { return json["id"].string } } var title: String? { get { return json["title"].string } } var description: String? { get { return json["description"].string } } } struct DefinitionSchema: Referenceable, TypeSchema, RootSchemaProtocol { var json: JSON var rootJSON: JSON var ref: String? init() { self.json = [:] self.rootJSON = [:] } var definitions: [String: PropertySchema]? { get { return json["definitions"].dictionaryValue.mapPairs { ($0, PropertySchema(json: $1, rootJSON: self.rootJSON)!) } } } var title: String? { get { return json["title"].string } } var description: String? { get { return json["description"].string } } } struct TargetSchema: Referenceable, TypeSchema, RootSchemaProtocol { var json: JSON var rootJSON: JSON var ref: String? init() { self.json = [:] self.rootJSON = [:] } var title: String? { get { return json["title"].string } } var description: String? { get { return json["description"].string } } } struct PropertySchema: Referenceable, TypeSchema { var json: JSON var rootJSON: JSON var ref: String? init() { self.json = [:] self.rootJSON = [:] } var maximum: String? { get { return json["maximum"].string } } var multipleOf: String? { get { return json["multipleOf"].string } } var exclusiveMaximum: String? { get { return json["exclusiveMaximum"].string } } var minimum: String? { get { return json["minimum"].string } } var exclusiveMinimum: String? { get { return json["exclusiveMinimum"].string } } var maxLength: String? { get { return json["maxLength"].string } } var minLength: String? { get { return json["minLength"].string } } var pattern: String? { get { return json["pattern"].string } } var additionalItems: String? { get { return json["additionalItems"].string } } var maxItems: String? { get { return json["maxItems"].string } } var minItems: String? { get { return json["minItems"].string } } var uniqueItems: String? { get { return json["uniqueItems"].string } } var maxProperties: String? { get { return json["maxProperties"].string } } var minProperties: String? { get { return json["minProperties"].string } } var additionalProperties: String? { get { return json["additionalProperties"].string } } var definitions: String? { get { return json["definitions"].string } } var properties: [String: PropertySchema]? { get { return json["properties"].dictionaryValue.mapPairs { ($0, PropertySchema(json: $1, rootJSON: self.rootJSON)!) } } } var patternProperties: String? { get { return json["patternProperties"].string } } var dependencies: String? { get { return json["dependencies"].string } } var allOf: [PropertySchema]? { get { return json["allOf"].array?.map { PropertySchema(json: $0, rootJSON: rootJSON)! } } } var anyOf: [PropertySchema]? { get { return json["anyOf"].array?.map { PropertySchema(json: $0, rootJSON: rootJSON)! } } } var not: PropertySchema? { get { return PropertySchema(json: json["not"], rootJSON: rootJSON) } } } struct LinkSchema { var json: JSON var rootJSON: JSON var href: String var rel: String var encType: String? var description: String? var method: String? var title: String? var mediaType: String? var schema: Schema? var targetSchema: TargetSchema? init(json: JSON, rootJSON: JSON) { self.href = json["href"].stringValue self.rel = json["rel"].stringValue self.encType = json["encType"].stringValue self.description = json["description"].stringValue self.method = json["method"].stringValue self.title = json["title"].stringValue self.mediaType = json["mediaType"].stringValue self.schema = Schema(json: json["schema"], rootJSON: rootJSON) self.targetSchema = TargetSchema(json: json["targetSchema"], rootJSON: rootJSON) self.json = json self.rootJSON = rootJSON } } struct MediaSchema { var binaryEncoding: String var type: String init?(json: JSON) { guard !json.isEmpty else { return nil } self.binaryEncoding = json["binaryEncoding"].stringValue self.type = json["type"].stringValue } } /// 独自定義 /// enumプロパティの解説用に、独自に定義したプロパティ /// モデルクラスを自動生成する際に、各要素の名称を付けるために使う struct EnumDescription { var json: JSON var rootJSON: JSON var key: String var value: String init(json: JSON, rootJSON: JSON) { self.key = json["key"].stringValue self.value = json["value"].stringValue self.json = json self.rootJSON = rootJSON } }
mit
3db6a5fe8b6ef5dd677f08a21962db9b
18.395397
84
0.599072
3.624316
false
false
false
false
MukeshKumarS/Swift
test/SILGen/generic_closures.swift
1
5667
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s import Swift var zero: Int // CHECK-LABEL: sil hidden @_TF16generic_closures28generic_nondependent_context{{.*}} func generic_nondependent_context<T>(x: T, y: Int) -> Int { var y = y func foo() -> Int { return y } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures28generic_nondependent_context{{.*}} : $@convention(thin) (@owned @box Int) -> Int // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] return foo() } // CHECK-LABEL: sil hidden @_TF16generic_closures15generic_capture{{.*}} func generic_capture<T>(x: T) -> Any.Type { func foo() -> Any.Type { return T.self } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures15generic_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick protocol<>.Type // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] return foo() } // CHECK-LABEL: sil hidden @_TF16generic_closures20generic_capture_cast{{.*}} func generic_capture_cast<T>(x: T, y: Any) -> Bool { func foo(a: Any) -> Bool { return a is T } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures20generic_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in protocol<>) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] return foo(y) } protocol Concept { var sensical: Bool { get } } // CHECK-LABEL: sil hidden @_TF16generic_closures29generic_nocapture_existential{{.*}} func generic_nocapture_existential<T>(x: T, y: Concept) -> Bool { func foo(a: Concept) -> Bool { return a.sensical } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures29generic_nocapture_existential{{.*}} : $@convention(thin) (@in Concept) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] return foo(y) } // CHECK-LABEL: sil hidden @_TF16generic_closures25generic_dependent_context{{.*}} func generic_dependent_context<T>(x: T, y: Int) -> T { func foo() -> T { return x } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures25generic_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@out τ_0_0, @owned @box τ_0_0) -> () // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T> return foo() } enum Optionable<T> { case Some(T) case None } class NestedGeneric<U> { class func generic_nondependent_context<T>(x: T, y: Int, z: U) -> Int { func foo() -> Int { return y } return foo() } class func generic_dependent_inner_context<T>(x: T, y: Int, z: U) -> T { func foo() -> T { return x } return foo() } class func generic_dependent_outer_context<T>(x: T, y: Int, z: U) -> U { func foo() -> U { return z } return foo() } class func generic_dependent_both_contexts<T>(x: T, y: Int, z: U) -> (T, U) { func foo() -> (T, U) { return (x, z) } return foo() } // CHECK-LABEL: sil hidden @_TFC16generic_closures13NestedGeneric20nested_reabstraction{{.*}} // CHECK: [[REABSTRACT:%.*]] = function_ref @_TTRG__rXFo__dT__XFo_iT__iT__ // CHECK: partial_apply [[REABSTRACT]]<U, T> func nested_reabstraction<T>(x: T) -> Optionable<() -> ()> { return .Some({}) } } // CHECK-LABEL: sil hidden @_TF16generic_closures24generic_curried_function{{.*}} : $@convention(thin) <T, U> (@in U, @in T) -> () { // CHECK-LABEL: sil shared @_TF16generic_closures24generic_curried_function{{.*}} func generic_curried_function<T, U>(x: T)(y: U) { } var f: (Int) -> () = generic_curried_function(zero) // <rdar://problem/15417773> // Ensure that nested closures capture the generic parameters of their nested // context. // CHECK: sil hidden @_TF16generic_closures25nested_closure_in_generic{{.*}} : $@convention(thin) <T> (@out T, @in T) -> () // CHECK: function_ref [[OUTER_CLOSURE:@_TFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_]] // CHECK: sil shared [[OUTER_CLOSURE]] : $@convention(thin) <T> (@out T, @inout_aliasable T) -> () // CHECK: function_ref [[INNER_CLOSURE:@_TFFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_U_FT_Q_]] // CHECK: sil shared [[INNER_CLOSURE]] : $@convention(thin) <T> (@out T, @inout_aliasable T) -> () { func nested_closure_in_generic<T>(x:T) -> T { return { { x }() }() } // CHECK-LABEL: sil hidden @_TF16generic_closures16local_properties func local_properties<T>(inout t: T) { // CHECK: [[TBOX:%[0-9]+]] = alloc_box $T var prop: T { get { return t } set { t = newValue } } // CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@out τ_0_0, @owned @box τ_0_0) -> () // CHECK: apply [[GETTER_REF]] t = prop // CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned @box τ_0_0) -> () // CHECK: apply [[SETTER_REF]] prop = t var prop2: T { get { return t } set { // doesn't capture anything } } // CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@out τ_0_0, @owned @box τ_0_0) -> () // CHECK: apply [[GETTER2_REF]] t = prop2 // CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> () // CHECK: apply [[SETTER2_REF]] prop2 = t } protocol Fooable { static func foo() -> Bool } // <rdar://problem/16399018> func shmassert(@autoclosure f: () -> Bool) {} // CHECK-LABEL: sil hidden @_TF16generic_closures21capture_generic_param func capture_generic_param<A: Fooable>(x: A) { shmassert(A.foo()) }
apache-2.0
9d98605d76749f3ce243327d9cdfd391
35.934641
181
0.615997
3.108361
false
false
false
false
naoyashiga/CatsForInstagram
Nekobu/TopCollectionViewController+UIViewControllerTransitioningDelegate.swift
1
1362
// // TopCollectionViewController+UIViewControllerTransitioningDelegate.swift // Nekobu // // Created by naoyashiga on 2015/08/23. // Copyright (c) 2015年 naoyashiga. All rights reserved. // import Foundation extension TopCollectionViewController: UIViewControllerTransitioningDelegate { func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { return BlurredBackgroundPresentationController(presentedViewController: presented, presentingViewController: self) } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { let animator = TransitionPresentationAnimator() animator.sourceVC = self animator.destinationVC = presented return animator } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { let animator = TransitionDismissAnimator() animator.sourceVC = dismissed animator.destinationVC = self return animator } }
mit
e5735512774e0205913e2e6d3d8878c8
37.885714
219
0.761765
7.351351
false
false
false
false
IvanVorobei/Sparrow
sparrow/animation/SPAnimation.swift
1
2516
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class SPAnimation { static func animate(_ duration: TimeInterval, animations: (() -> Void)!, delay: TimeInterval = 0, options: UIViewAnimationOptions = [], withComplection completion: (() -> Void)! = {}) { UIView.animate( withDuration: duration, delay: delay, options: options, animations: { animations() }, completion: { finished in completion() }) } static func animateWithRepeatition(_ duration: TimeInterval, animations: (() -> Void)!, delay: TimeInterval = 0, options: UIViewAnimationOptions = [], withComplection completion: (() -> Void)! = {}) { var optionsWithRepeatition = options optionsWithRepeatition.insert([.autoreverse, .repeat]) self.animate( duration, animations: { animations() }, delay: delay, options: optionsWithRepeatition, withComplection: { completion() }) } }
mit
179855f8acc6d4b3280d358f7625278e
37.692308
88
0.585686
5.576497
false
false
false
false
ooftv/ooftv-tvos
ooftv/AppDelegate.swift
1
6473
// // AppDelegate.swift // ooftv // // Created by Loren Risker on 12/2/15. // Copyright © 2015 OutOfFocusTV. All rights reserved. // github test // github return test import UIKit import TVMLKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate { var window: UIWindow? var appController: TVApplicationController? // tvBaseURL points to a server on your local machine. To create a local server for testing purposes, use the following command inside your project folder from the Terminal app: ruby -run -ehttpd . -p9001. See NSAppTransportSecurity for information on using a non-secure server. //Switch this on for local http server //static let TVBaseURL = "http://localhost:9001/" //Switch this on for testing remote server (make sure to update sublime sftp upload location by right clicking on the folder and editing the remote upload location) //static let TVBaseURL = "http://www.discolemonade.com/tvos/ooftv/v2/test/2.0/app/" //switch this on for testing the release version static let TVBaseURL = "http://www.discolemonade.com/tvos/ooftv/v2/release/app/" //probably leave this next line alone static let TVBootURL = "\(AppDelegate.TVBaseURL)js/application.js" // MARK: Javascript Execution Helper func executeRemoteMethod(_ methodName: String, completion: @escaping (Bool) -> Void) { appController?.evaluate(inJavaScriptContext: { (context: JSContext) in let appObject : JSValue = context.objectForKeyedSubscript("App") if appObject.hasProperty(methodName) { appObject.invokeMethod(methodName, withArguments: []) } }, completion: completion) } // MARK: UIApplicationDelegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) // Create the TVApplicationControllerContext for this application and set the properties that will be passed to the `App.onLaunch` function in JavaScript. let appControllerContext = TVApplicationControllerContext() // The JavaScript URL is used to create the JavaScript context for your TVMLKit application. Although it is possible to separate your JavaScript into separate files, to help reduce the launch time of your application we recommend creating minified and compressed version of this resource. This will allow for the resource to be retrieved and UI presented to the user quickly. if let javaScriptURL = URL(string: AppDelegate.TVBootURL) { appControllerContext.javaScriptApplicationURL = javaScriptURL } appControllerContext.launchOptions["BASEURL"] = AppDelegate.TVBaseURL as NSString if let launchOptions = launchOptions { for (kind, value) in launchOptions { appControllerContext.launchOptions[kind.rawValue] = value } } appController = TVApplicationController(context: appControllerContext, window: window, 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 stop playback executeRemoteMethod("onWillResignActive", completion: { (success: Bool) in // ... }) } 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. executeRemoteMethod("onDidEnterBackground", completion: { (success: Bool) in // ... }) } 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. executeRemoteMethod("onWillEnterForeground", completion: { (success: Bool) in // ... }) } 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. executeRemoteMethod("onDidBecomeActive", completion: { (success: Bool) in // ... }) } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. executeRemoteMethod("onWillTerminate", completion: { (success: Bool) in // ... }) } // MARK: TVApplicationControllerDelegate func appController(_ appController: TVApplicationController, didFinishLaunching options: [String: Any]?) { print("\(#function) invoked with options: \(options ?? [:])") } func appController(_ appController: TVApplicationController, didFail error: Error) { print("\(#function) invoked with error: \(error)") let title = "Error Launching Application" let message = error.localizedDescription let alertController = UIAlertController(title: title, message: message, preferredStyle:.alert ) self.appController?.navigationController.present(alertController, animated: true, completion: { // ... }) } func appController(_ appController: TVApplicationController, didStop options: [String: Any]?) { print("\(#function) invoked with options: \(options ?? [:])") } }
gpl-3.0
9fcac6bbcb75b13de04ea7439b18801f
46.940741
383
0.691286
5.452401
false
false
false
false
tarun-talentica/TalNet
Source/Response/QueryResponseSerialization.swift
2
6138
// // ResponseSerialization.swift // Pod-In-Playground // // Created by Tarun Sharma on 13/05/16. // Copyright © 2016 Tarun Sharma. All rights reserved. // import Foundation import ObjectMapper public protocol ResultSerializableType { associatedtype SerializedType func serialize(from request:CancellableRequest,completionHandler: QueryResponse<SerializedType, NSError> -> Void) } public protocol StringSerializable: ResultSerializableType { associatedtype SerializedType = String var encoding: NSStringEncoding? {get set} } public extension StringSerializable { func serialize(from request:CancellableRequest,completionHandler: QueryResponse<String, NSError> -> Void) { request.innerCancellable?.vendorRequest?.response { (request:NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in func sendResponse(results: QueryResult<String,NSError>) { let queryResponse = QueryResponse(request:request, response: response, statusCode: response?.statusCode, result: results) completionHandler(queryResponse) } guard error == nil else { sendResponse(QueryResult.Failure(error!)) return } if let urlResponse = response where urlResponse.statusCode == 204 { sendResponse(QueryResult.Success("")) return } guard let validData = data else { let error = Error.StringSerializationFailed.nsError sendResponse(QueryResult.Failure(error)) return } var convertedEncoding = self.encoding if let encodingName = response?.textEncodingName where convertedEncoding == nil { convertedEncoding = CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName) ) } let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding guard let string = String(data: validData, encoding: actualEncoding) else { let error = Error.StringSerializationFailed.nsError sendResponse(QueryResult.Failure(error)) return } sendResponse(QueryResult.Success(string)) } } } public protocol JsonSerializable: ResultSerializableType { associatedtype SerializedType = AnyObject var jsonOptions: NSJSONReadingOptions {get} } public extension JsonSerializable { func serialize(from request:CancellableRequest,completionHandler: QueryResponse<AnyObject, NSError> -> Void) { request.innerCancellable?.vendorRequest?.response { (request:NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in func sendResponse(results: QueryResult<AnyObject,NSError>) { let queryResponse = QueryResponse(request:request, response: response, statusCode: response?.statusCode, result: results) completionHandler(queryResponse) } guard error == nil else { sendResponse(QueryResult.Failure(error!)) return } guard let validData = data where validData.length > 0 else { let error = Error.JSONSerializationFailed.nsError sendResponse(QueryResult.Failure(error)) return } if let urlResponse = response where urlResponse.statusCode == 204 { sendResponse(QueryResult.Success(NSNull())) return } do { let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: self.jsonOptions) sendResponse(QueryResult.Success(JSON)) } catch { sendResponse(QueryResult.Failure(error as NSError)) } } } } public protocol ObjectSerializable: ResultSerializableType { associatedtype ObjectType: ObjectMappable associatedtype SerializedType = ObjectType } public protocol ObjectArraySerializable: ResultSerializableType { associatedtype ObjectType: ObjectMappable associatedtype SerializedType = [ObjectType] var keyPath: String? { get } } public extension CancellableRequest { public func checkForVendorRegistration<T>(completionHandler:QueryResponse<T,NSError> -> Void) -> Bool { /// Check if any vendor exists. If not then return an error. guard let _ = self.innerCancellable?.vendorRequest else { let error = Error.NoVendorRegistered.nsError let errorResponse = QueryResponse<T,NSError>(result: QueryResult.Failure(error)) completionHandler(errorResponse) return false } return true } } public extension CancellableRequest { func response<T:ResultSerializableType>( destinationQueue queue: dispatch_queue_t? = nil,type:T, completionHandler: QueryResponse<T.SerializedType, NSError> -> Void) -> CancellableRequest { self.innerCancellable?.queue.addOperationWithBlock { if self.refreshTokenFailed { let error = Error.InvalidAccessToken.nsError let queryResponse = QueryResponse<T.SerializedType,NSError>( result: .Failure(error)) dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(queryResponse) } } else{ type.serialize(from: self) { response in dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) } } } } return self } }
mit
9fcdf7bf2d926e7377d4876cb9c283c3
35.313609
137
0.604856
5.969844
false
false
false
false
johnpatrickmorgan/FireRoutes
Example/Tests/Tests.swift
1
4205
// https://github.com/Quick/Quick import Quick import Nimble import FireRoutes import Alamofire class TableOfContentsSpec: QuickSpec { override func spec() { let manager = SessionManager.default describe("A string route") { let route = StringRoute() context("with delayed stubbed data") { let data = dataForFile("StringRouteSample", type:"txt")! let stub = (RequestResult.success(data), 0.1) it("should succeed") { waitUntil { done in manager.stub(route, stub: stub) { (response) -> Void in expect(response.result.value).toNot(beNil()) expect(response.result.error).to(beNil()) expect(response.result.value).to(equal("Hello world!")) done() } } } } } describe("A JSON route") { let route = JSONRoute() context("with delayed stubbed data") { let data = dataForFile("JSONRouteSample", type:"json")! let stub = (RequestResult.success(data), 0.1) it("should succeed") { waitUntil { done in manager.stub(route, stub: stub) { (response) -> Void in expect(response.result.value).toNot(beNil()) expect(response.result.error).to(beNil()) let representation = response.result.value as? NSDictionary expect(representation).toNot(beNil()) let greeting = representation!["greeting"] as? String expect(greeting).to(equal("Hello world!")) done() } } } } } describe("An image route") { let route = ImageRoute(userId:"jmorgan") context("with delayed stubbed data") { let data = dataForFile("ImageRouteSample", type:"png")! let stub = (RequestResult.success(data), 0.1) it("should succeed") { waitUntil { done in manager.stub(route, stub: stub) { (response) -> Void in expect(response.result.value).toNot(beNil()) expect(response.result.error).to(beNil()) expect(response.result.value!.size.width).to(equal(640.0)) done() } } } } } describe("A mapped model route") { let route = MappedModelRoute() context("with delayed stubbed data") { let data = dataForFile("MappedModelRouteSample", type:"json")! let stub = (RequestResult.success(data), 0.1) it("should succeed") { waitUntil { done in manager.stub(route, stub: stub) { (response) -> Void in expect(response.result.value).toNot(beNil()) expect(response.result.error).to(beNil()) let mappedModel = response.result.value expect(mappedModel!.exampleURL).toNot(beNil()) expect(mappedModel!.exampleInt).to(equal(42)) expect(mappedModel!.exampleString).to(equal("Hello world!")) done() } } } } } } } func dataForFile(_ filename: String, type: String?) -> Data? { let bundle = Bundle(for: StringRoute.self) if let url = bundle.url(forResource: filename, withExtension: type) { return try! Data(contentsOf: url) } return nil }
mit
72d3fa539c80e2927c10572934531993
37.227273
88
0.443282
5.599201
false
false
false
false
tbointeractive/bytes
Example/bytesTests/Specs/DiscardTouchViewSpec.swift
1
2801
// // DiscardTouchViewSpec.swift // bytes // // Created by Cornelius Horstmann on 01.11.16. // Copyright © 2016 TBO INTERACTIVE GmbH & Co. KG. All rights reserved. // import bytes import Quick import Nimble class DiscardTouchViewSpec: QuickSpec { override func spec() { describe("discardTouches") { it("should be true per default") { let discardTouchView = DiscardTouchView() expect(discardTouchView.discardsTouches) == true } } describe("hitTest") { context("with no subviews and discardTouches to true") { let discardTouchView = DiscardTouchView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) it("should always return nil") { expect(discardTouchView.hitTest(CGPoint(x: 0, y: 0), with: nil)).to(beNil()) } } context("with no subviews and discardTouches to false") { let discardTouchView = DiscardTouchView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) discardTouchView.discardsTouches = false it("should always return itself") { expect(discardTouchView.hitTest(CGPoint(x: 0, y: 0), with: nil)) == discardTouchView } } context("with a subview and discardTouches to true") { let discardTouchView = DiscardTouchView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) discardTouchView.addSubview(UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 5))) it("should always return nil if the hit test doesn't hit the subview") { expect(discardTouchView.hitTest(CGPoint(x: 1, y: 6), with: nil)).to(beNil()) } it("should return the subview that has been hit") { expect(discardTouchView.hitTest(CGPoint(x: 1, y: 1), with: nil)) == discardTouchView.subviews.first } } context("with a subview and discardTouches to false") { let discardTouchView = DiscardTouchView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) discardTouchView.addSubview(UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 5))) discardTouchView.discardsTouches = false it("should always return itself if the hit test doesn't hit the subview") { expect(discardTouchView.hitTest(CGPoint(x: 1, y: 6), with: nil)) == discardTouchView } it("should return the subview that has been hit") { expect(discardTouchView.hitTest(CGPoint(x: 1, y: 1), with: nil)) == discardTouchView.subviews.first } } } } }
mit
bf0288bfb08634fc52459d5c85ae789b
46.457627
119
0.567143
4.444444
false
true
false
false
zhuhuihuihui/LeetCode-Scott
SwiftSolutions/Solution.playground/Contents.swift
1
1466
//: Playground - noun: a place where people can play import UIKit class Solution { /** * 125. Valid Palindrome * String, Easy * https://leetcode.com/problems/valid-palindrome/ * */ func isPalindrome(s: String) -> Bool { let alphanumericCharSet = NSCharacterSet.alphanumericCharacterSet() if !s.isEmpty { var lefCursor = s.startIndex, rightCursor = s.endIndex.predecessor() while lefCursor < rightCursor { let leftChar = s[lefCursor], rightChar = s[rightCursor] print("leftChar = \(leftChar), rightChar = \(rightChar)") if alphanumericCharSet.characterIsMember(leftChar as! unichar) && alphanumericCharSet.characterIsMember(rightChar) { if leftChar != rightChar { return false } } if !alphanumericCharSet.characterIsMember(leftChar) { lefCursor = lefCursor.successor() } if !alphanumericCharSet.characterIsMember(rightChar) { rightCursor = rightCursor.predecessor() } } return true } return false } func description(string: String) { print(string) } } let solution = Solution() let result = solution.isPalindrome("A man, a plan, a canal: Panama")
mit
46ddf6d5defd07768b214c889433d7f3
31.577778
132
0.543656
5.180212
false
false
false
false
vknabel/Rock
Sources/rock/Arguments.swift
1
1032
import Commandant import PathKit import RockLib import Result extension Path: ArgumentProtocol { public static var name = "path" public static func from(string: String) -> Path? { return Path.current + string } } extension Dependency: ArgumentProtocol { public static var name = "rocket[@version]" } let projectOption = Option( key: "project", defaultValue: Path.current, usage: "The target project. It should contain the Rockfile" ) let rocketArguments = Argument<[Dependency.Name]>(usage: "A list of rockets") let dependencyArguments = Argument<[Dependency]>(usage: "A list of rockets, optionally including a version") extension RockProject { static func fromOptions(_ m: CommandMode) -> Result<RockProject, CommandantError<RockError>> { let path: Result<Path, CommandantError<RockError>> = m <| projectOption return path.flatMap({ path in Rockfile.fromPath(path).mapError(CommandantError.commandError) .map { RockProject(rockfile: $0, rockPath: path) } }) } }
mit
eaef869e2d9664ed46efdcdf813c82af
27.666667
108
0.718023
4.111554
false
false
false
false
LoopKit/LoopKit
LoopKit/KeychainManager.swift
1
10391
// // KeychainManager.swift // Loop // // Created by Nate Racklyeft on 6/26/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import Security public enum KeychainManagerError: Error { case add(OSStatus) case copy(OSStatus) case delete(OSStatus) case unknownResult } /** Influenced by https://github.com/marketplacer/keychain-swift */ public struct KeychainManager { typealias Query = [String: NSObject] public init() { } var accessibility: CFString = kSecAttrAccessibleAfterFirstUnlock var accessGroup: String? public struct InternetCredentials: Equatable { public let username: String public let password: String public let url: URL public init(username: String, password: String, url: URL) { self.username = username self.password = password self.url = url } } // MARK: - Convenience methods private func query(by class: CFString) -> Query { var query: Query = [kSecClass as String: `class`] if let accessGroup = accessGroup { query[kSecAttrAccessGroup as String] = accessGroup as NSObject? } return query } private func queryForGenericPassword(by service: String) -> Query { var query = self.query(by: kSecClassGenericPassword) query[kSecAttrService as String] = service as NSObject? return query } private func queryForInternetPassword(account: String? = nil, url: URL? = nil, label: String? = nil) -> Query { var query = self.query(by: kSecClassInternetPassword) if let account = account { query[kSecAttrAccount as String] = account as NSObject? } if let url = url, let components = URLComponents(url: url, resolvingAgainstBaseURL: true) { for (key, value) in components.keychainAttributes { query[key] = value } } if let label = label { query[kSecAttrLabel as String] = label as NSObject? } return query } private func updatedQuery(_ query: Query, withPassword password: Data) throws -> Query { var query = query query[kSecValueData as String] = password as NSObject? query[kSecAttrAccessible as String] = accessibility return query } private func updatedQuery(_ query: Query, withPassword password: String) throws -> Query { guard let value = password.data(using: String.Encoding.utf8) else { throw KeychainManagerError.add(errSecDecode) } return try updatedQuery(query, withPassword: value) } func delete(_ query: Query) throws { let statusCode = SecItemDelete(query as CFDictionary) guard statusCode == errSecSuccess || statusCode == errSecItemNotFound else { throw KeychainManagerError.delete(statusCode) } } // MARK: – Generic Passwords public func deleteGenericPassword(forService service: String) throws { try delete(queryForGenericPassword(by: service)) } public func replaceGenericPassword(_ password: String?, forService service: String) throws { var query = queryForGenericPassword(by: service) try delete(query) guard let password = password else { return } query = try updatedQuery(query, withPassword: password) let statusCode = SecItemAdd(query as CFDictionary, nil) guard statusCode == errSecSuccess else { throw KeychainManagerError.add(statusCode) } } public func replaceGenericPassword(_ password: Data?, forService service: String) throws { var query = queryForGenericPassword(by: service) try delete(query) guard let password = password else { return } query = try updatedQuery(query, withPassword: password) let statusCode = SecItemAdd(query as CFDictionary, nil) guard statusCode == errSecSuccess else { throw KeychainManagerError.add(statusCode) } } public func getGenericPasswordForServiceAsData(_ service: String) throws -> Data { var query = queryForGenericPassword(by: service) query[kSecReturnData as String] = kCFBooleanTrue query[kSecMatchLimit as String] = kSecMatchLimitOne var result: AnyObject? let statusCode = SecItemCopyMatching(query as CFDictionary, &result) guard statusCode == errSecSuccess else { throw KeychainManagerError.copy(statusCode) } guard let passwordData = result as? Data else { throw KeychainManagerError.unknownResult } return passwordData } public func getGenericPasswordForService(_ service: String) throws -> String { let passwordData = try getGenericPasswordForServiceAsData(service) guard let password = String(data: passwordData, encoding: String.Encoding.utf8) else { throw KeychainManagerError.unknownResult } return password } // MARK – Internet Passwords public func setInternetPassword(_ password: String, account: String, atURL url: URL, label: String? = nil) throws { var query = try updatedQuery(queryForInternetPassword(account: account, url: url, label: label), withPassword: password) query[kSecAttrAccount as String] = account as NSObject? if let components = URLComponents(url: url, resolvingAgainstBaseURL: true) { for (key, value) in components.keychainAttributes { query[key] = value } } if let label = label { query[kSecAttrLabel as String] = label as NSObject? } let statusCode = SecItemAdd(query as CFDictionary, nil) guard statusCode == errSecSuccess else { throw KeychainManagerError.add(statusCode) } } public func replaceInternetCredentials(_ credentials: InternetCredentials?, forAccount account: String) throws { let query = queryForInternetPassword(account: account) try delete(query) if let credentials = credentials { try setInternetPassword(credentials.password, account: credentials.username, atURL: credentials.url) } } public func replaceInternetCredentials(_ credentials: InternetCredentials?, forLabel label: String) throws { let query = queryForInternetPassword(label: label) try delete(query) if let credentials = credentials { try setInternetPassword(credentials.password, account: credentials.username, atURL: credentials.url, label: label) } } public func replaceInternetCredentials(_ credentials: InternetCredentials?, forURL url: URL) throws { let query = queryForInternetPassword(url: url) try delete(query) if let credentials = credentials { try setInternetPassword(credentials.password, account: credentials.username, atURL: credentials.url) } } public func getInternetCredentials(account: String? = nil, url: URL? = nil, label: String? = nil) throws -> InternetCredentials { var query = queryForInternetPassword(account: account, url: url, label: label) query[kSecReturnData as String] = kCFBooleanTrue query[kSecReturnAttributes as String] = kCFBooleanTrue query[kSecMatchLimit as String] = kSecMatchLimitOne var result: AnyObject? let statusCode: OSStatus = SecItemCopyMatching(query as CFDictionary, &result) guard statusCode == errSecSuccess else { throw KeychainManagerError.copy(statusCode) } if let result = result as? [AnyHashable: Any], let passwordData = result[kSecValueData as String] as? Data, let password = String(data: passwordData, encoding: String.Encoding.utf8), let url = URLComponents(keychainAttributes: result)?.url, let username = result[kSecAttrAccount as String] as? String { return InternetCredentials(username: username, password: password, url: url) } throw KeychainManagerError.unknownResult } } private enum SecurityProtocol { case http case https init?(scheme: String?) { switch scheme?.lowercased() { case "http"?: self = .http case "https"?: self = .https default: return nil } } init?(secAttrProtocol: CFString) { if secAttrProtocol == kSecAttrProtocolHTTP { self = .http } else if secAttrProtocol == kSecAttrProtocolHTTPS { self = .https } else { return nil } } var scheme: String { switch self { case .http: return "http" case .https: return "https" } } var secAttrProtocol: CFString { switch self { case .http: return kSecAttrProtocolHTTP case .https: return kSecAttrProtocolHTTPS } } } private extension URLComponents { init?(keychainAttributes: [AnyHashable: Any]) { self.init() if let secAttProtocol = keychainAttributes[kSecAttrProtocol as String] { scheme = SecurityProtocol(secAttrProtocol: secAttProtocol as! CFString)?.scheme } host = keychainAttributes[kSecAttrServer as String] as? String if let port = keychainAttributes[kSecAttrPort as String] as? Int, port > 0 { self.port = port } if let path = keychainAttributes[kSecAttrPath as String] as? String { self.path = path } } var keychainAttributes: [String: NSObject] { var query: [String: NSObject] = [:] if let `protocol` = SecurityProtocol(scheme: scheme) { query[kSecAttrProtocol as String] = `protocol`.secAttrProtocol } if let host = host { query[kSecAttrServer as String] = host as NSObject } if let port = port { query[kSecAttrPort as String] = port as NSObject } if !path.isEmpty { query[kSecAttrPath as String] = path as NSObject } return query } }
mit
75b9fae76a8e0c2e1844e1cbf61a443c
28.502841
133
0.633028
5.215972
false
false
false
false
Joachimdj/JobResume
Apps/Kort sagt/KortSagt-master/KortSagt/HomeViewController.swift
1
7105
// // HomeViewController.swift // KortSagt // // Created by Joachim on 20/03/15. // Copyright (c) 2015 Joachim Dittman. All rights reserved. // import UIKit import Alamofire import SwiftyJSON var nextPageToken = ""; var prevPageToken = ""; var isPresented = false class HomeViewController: UIViewController { @IBOutlet weak var date: UILabel! @IBOutlet weak var place: UILabel! override func viewDidLoad() { super.viewDidLoad() videos.removeAll(keepCapacity: true) loadNewVideo() let parameters : [ String : String] = [ "access_token": "535078339963418|0cad57a5c0680b105fdb6a3bb6f71a72", "fields": "cover,start_time,name,place" ] let url = "https://graph.facebook.com/v2.3/kortsagt.nu/events" Alamofire.request(.GET, url,encoding: .URLEncodedInURL,parameters:parameters).responseJSON { response in switch response.result { case .Success(let data): let json = JSON(data) let imageString = json["data"][0]["cover"]["source"].string let place = json["data"][0]["place"]["name"].string let date1 = json["data"][0]["start_time"].string if(date1 != nil){ let df = NSDateFormatter() //Wed Dec 01 17:08:03 +0000 2010 df.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ" let date = df.dateFromString(date1!) df.dateFormat = "dd-MM-yyyy HH:mm" let dateStr = df.stringFromDate(date!) let dateNext = "Næste event" let dateString1 = "\(dateNext) \(dateStr)" let dateNow = NSDate() print(dateNow) print(date) print(date!.compare(dateNow).rawValue) if(date!.compare(dateNow).rawValue == 1){ // Fade out to set the text UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.place.alpha = 0.0 self.date.alpha = 0.0 }, completion: { (finished: Bool) -> Void in //Once the label is completely invisible, set the text and fade it back in self.place.text = place self.date.text = dateString1 // Fade in UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.place.alpha = 1.0 self.date.alpha = 1.0 }, completion: nil) }) } // self.place.text = place } let imageView1 = UIImageView() if(imageString != nil){ ImageLoader.sharedLoader.imageForUrl(imageString!, completionHandler:{(image: UIImage?, url: String) in imageView1.image = Toucan(image: image!).resize(CGSize(width: 640, height: 360), fitMode: Toucan.Resize.FitMode.Crop).image // Do any additional setup after loading the view. }) } case .Failure(let error): print("Request failed with error: \(error)") } } } // headerTalkimage.addSubview(imageView1) func loadNewVideo(){ let url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCBBSZunZagb4bDBi3PSqd7Q&order=date&key=AIzaSyA0T0fCHDyQzKCH0z0xs-i8Vh6DeSMcUuQ&maxResults=50&part=snippet,contentDetails&pageToken=\(nextPageToken)" Alamofire.request(.GET, url,encoding: .URLEncodedInURL,parameters:nil).responseJSON { response in switch response.result { case .Success(let data): let json = JSON(data) _ = json["items"] let count = json["items"].count; for var i = 0; i <= count; i++ { if(json["items"][i]["id"]["videoId"] != nil){ videos.append(Video(id:json["items"][i]["id"]["videoId"].string! , name:json["items"][i]["snippet"]["title"].string!, desc:json["items"][i]["snippet"]["description"].string!)) } print(" \(i) = \(count)") } if(json["prevPageToken"] != nil){prevPageToken = json["prevPageToken"].string! } if(json["nextPageToken"] != nil){ nextPageToken = json["nextPageToken"].string! } if(json["nextPageToken"].string != nil) { self.loadNewVideo() } case .Failure(let error): print("Request failed with error: \(error)") } } } func SupriceMe(sender: AnyObject) { is_searching = false if(videos.count>0){ let random = randomInt(0,max: videos.count) selectedVideo = random let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let modalVC: ItemViewController = storyboard.instantiateViewControllerWithIdentifier("item") as! ItemViewController let navController = UINavigationController(rootViewController: modalVC) self.presentViewController(navController, animated: true, completion: nil) } } func randomInt(min: Int, max:Int) -> Int { return min + Int(arc4random_uniform(UInt32(max - min + 1))) } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ override func prefersStatusBarHidden() -> Bool { return true } func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int { return Int(UIInterfaceOrientationMask.Portrait.rawValue); } }
mit
466a8418aeb44c87a3dd965b33f3abb1
38.910112
236
0.508446
5.114471
false
false
false
false
asm-products/voicesrepo
Voices/Voices/Extensions/NSObject+Basics.swift
1
774
// // NSObject+Basics.swift // LocalPrayApp-ios // // Created by Mazyad Alabduljaleel on 11/9/14. // Copyright (c) 2014 ArabianDevs. All rights reserved. // import Foundation extension NSObject { class var className: String { var classString = NSStringFromClass(self) let range = classString.rangeOfString(".", options: .CaseInsensitiveSearch, range: Range<String.Index>(start:classString.startIndex, end: classString.endIndex), locale: nil) var identifier = "" if let dotRange = range { identifier = classString.substringFromIndex(dotRange.endIndex) } else { assertionFailure("Couldn't resolve class: \(classString)") } return identifier } }
agpl-3.0
8567a1590767db6542b2426d7641007f
25.689655
181
0.635659
4.607143
false
false
false
false
vojto/NiceKit
NiceKit/CALayer+Additions.swift
1
1106
// // CALayer+Additions.swift // Pomodoro X // // Created by Vojtech Rinik on 28/12/15. // Copyright © 2015 Vojtech Rinik. All rights reserved. // import Foundation import QuartzCore public extension CALayer { public func animate(_ property: String, to: CGFloat, duration: Double) { let currentValue = value(forKey: property) let animation = CABasicAnimation() animation.fromValue = currentValue animation.toValue = to animation.duration = duration add(animation, forKey: property) setValue(to, forKey: property) } public var scale: (CGFloat, CGFloat) { get { return (transform.m11, transform.m22) } set { let (x, y) = newValue transform = CATransform3DMakeScale(x, y, 1) } } } public extension CAShapeLayer { public static func circleLayer(_ frame: CGRect) -> CAShapeLayer { let layer = CAShapeLayer() layer.frame = frame let path = XBezierPath(ovalIn: frame) layer.path = path.CGPath return layer } }
mit
41369d76e0be4fa660ecab048d1de926
22.020833
76
0.611765
4.367589
false
false
false
false
taewan0530/TWKit
TWKit/StyleGenerator.swift
1
1134
// // StyleGenerator.swift // EasyKit // // Created by kimtaewan on 2016. 4. 26.. // Copyright © 2016년 taewan. All rights reserved. // import Foundation import UIKit //example EasyStyle class StyleGenerator { static private var generated = false class func generator() { if generated { return } generated = true let manger = EasyStyleManager.sharedInstance manger.registerStyle(key: "sample") { view in if let label = view as? UILabel { label.backgroundColor = UIColor.blue } } manger.registerStyle(key: "test") { view in if let label = view as? UILabel { label.textColor = UIColor.cyan } } } } @IBDesignable class IBLabel: UILabel { override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() StyleGenerator.generator() } } @IBDesignable class IBButton: UIButton { override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() StyleGenerator.generator() } }
mit
a489ccc485b54497e7711459000018f0
20.75
53
0.605659
4.7125
false
false
false
false
Jens-G/thrift
test/swift/CrossTests/Sources/TestServer/main.swift
3
2127
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import Foundation import Thrift import Common class TestServer { var server: Any? func run() throws { let parameters = try TestServerParameters(arguments: CommandLine.arguments) if parameters.showHelp { parameters.printHelp() return } let service = ThriftTestImpl() let processor = ThriftTestProcessor(service: service) switch (parameters.proto, parameters.transport) { case (.binary, .buffered): let proto = TBinaryProtocol.self server = try TSocketServer(port: parameters.port!, inProtocol: proto, outProtocol: proto, processor: processor) case (.binary, .framed): let proto = TBinaryProtocol.self server = try TFramedSocketServer(port: parameters.port!, inProtocol: proto, outProtocol: proto, processor: processor) case (.compact, .buffered): let proto = TCompactProtocol.self server = try TSocketServer(port: parameters.port!, inProtocol: proto, outProtocol: proto, processor: processor) case (.compact, .framed): let proto = TCompactProtocol.self server = try TFramedSocketServer(port: parameters.port!, inProtocol: proto, outProtocol: proto, processor: processor) default: throw ParserError.unsupportedOption } } } let server = TestServer() try server.run() RunLoop.main.run()
apache-2.0
670a8cba2d82c8496f9fb24a470d2893
35.050847
123
0.723554
4.440501
false
true
false
false
tadija/AEViewModel
Sources/AEViewModel/CollectionViewController.swift
1
4405
/** * https://github.com/tadija/AEViewModel * Copyright © 2017-2020 Marko Tadić * Licensed under the MIT license */ import UIKit open class CollectionViewController: UICollectionViewController, CellDelegate { // MARK: Properties open var isAutomaticReloadEnabled = true open var dataSource: DataSource = BasicDataSource() { didSet { if isAutomaticReloadEnabled { reload() } } } // MARK: Init public convenience init() { self.init(dataSource: BasicDataSource()) } public convenience init(dataSource: DataSource, layout: UICollectionViewLayout = UICollectionViewFlowLayout()) { self.init(collectionViewLayout: layout) self.dataSource = dataSource } // MARK: Lifecycle open override func viewDidLoad() { super.viewDidLoad() reload() } // MARK: API open func cellType(forIdentifier identifier: String) -> CollectionCellType { return .basic } open func update(_ cell: CollectionCell, at indexPath: IndexPath) { let item = dataSource.item(at: indexPath) cell.update(with: item) cell.delegate = self } open func action(for cell: CollectionCell, at indexPath: IndexPath, sender: Any) {} // MARK: CellDelegate public func callback(from cell: Cell, sender: Any) { if let cell = cell as? CollectionCell, let indexPath = collectionView?.indexPath(for: cell) { action(for: cell, at: indexPath, sender: sender) } } // MARK: Helpers private func reload() { if Thread.isMainThread { performReload() } else { DispatchQueue.main.async { [weak self] in self?.performReload() } } } private func performReload() { if let title = dataSource.title { self.title = title } collectionView?.reloadData() } } // MARK: - UICollectionViewControllerDataSource extension CollectionViewController { open override func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource.sections.count } open override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.sections[section].items.count } open override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let id = dataSource.identifier(at: indexPath) registerCell(with: id) let cell = collectionView.dequeueReusableCell(withReuseIdentifier: id, for: indexPath) if let cell = cell as? CollectionCell { update(cell, at: indexPath) } return cell } // MARK: Helpers private func registerCell(with identifier: String) { switch cellType(forIdentifier: identifier) { case .basic: collectionView?.register( CollectionCellBasic.self, forCellWithReuseIdentifier: identifier ) case .button: collectionView?.register( CollectionCellButton.self, forCellWithReuseIdentifier: identifier ) case .spinner: collectionView?.register( CollectionCellSpinner.self, forCellWithReuseIdentifier: identifier ) case .customClass(let cellClass): collectionView?.register( cellClass, forCellWithReuseIdentifier: identifier ) case .customNib(let cellClass): collectionView?.register( cellClass.nib, forCellWithReuseIdentifier: identifier ) } } } // MARK: - UICollectionViewControllerDelegate extension CollectionViewController { open override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? CollectionCell else { return } action(for: cell, at: indexPath, sender: self) } }
mit
3181a3fd0d168bb5bca811d38ebb789b
27.044586
99
0.597093
5.659383
false
false
false
false
JoeHolt/BetterReminders
BetterReminders/AppDelegate.swift
1
8004
// // AppDelegate.swift // BetterReminders // // Created by Joe Holt on 2/28/17. // Copyright © 2017 Joe Holt. All rights reserved. // import UIKit import UserNotifications enum NotificationArgs: String { case Class = "class" case Name = "name" case DueDate = "dueDate" case TimeToComplete = "timeToComplete" } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { let center = UNUserNotificationCenter.current() let notificationArgs: [String] = [] var window: UIWindow? var tasksToAdd: [[String: JHTask]] = [] var args: [String: String] = ["class" : "","name": "","dueDate": "","timeToComplete": ""] func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { center.delegate = self center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in } return true } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { //If notificatoin was a homework notification with text box if response.actionIdentifier.contains("classFinshedAction") { let response = response as! UNTextInputNotificationResponse let (task, clas) = createTaskFromArgs(args: parseNotificationString(string: response.userText)) tasksToAdd.append([clas: task]) } completionHandler() } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { //After a notification is displayed, request it agaion after the next week day if notification.request.identifier.contains("classFinishedRequest") { let nextTrigger: Double! let oneMinute = 60.0 //Seconds let oneDay = 1440.0 //Minutes let weekDay = Calendar.current.component(.weekday, from: Date()) var daysTillNextNotification: Double = 1.0 switch weekDay { case 6: //Friday daysTillNextNotification = 3.0 //Trigger in 3 days - monday case 7: //Saturday daysTillNextNotification = 2.0 //Trigger in 2 days - monday default: daysTillNextNotification = 1.0 } nextTrigger = oneMinute * oneDay * daysTillNextNotification let trigger = UNTimeIntervalNotificationTrigger(timeInterval: nextTrigger, repeats: false) let content = createNotificationContent(title: "Enter assigned homework", body: "class=\"Class\" \nname=\"Name\" \ndueDate=\"04/15/17\" \ntimeToComplete=\"01:15\"", badge: 0) content.categoryIdentifier = "classFinishedCatagory" let request = UNNotificationRequest(identifier: "classFinishedRequest", content: content, trigger: trigger) center.add(request) } } /** Parses a notification string - parameter string: String to be parsed - returns: A dictionsary with keys as args and values as arg body */ func parseNotificationString(string: String) -> [String: String]{ //notification is in the format of: arg0="content" arg1="Content" arg2="content" etc var body: String = "" var argActive = false //Sets if argument is been parsed var firstQuote = true //Shows if first quote in block has passed var argStr = "" for char in Array(string.characters) { if argActive == false { if char != "=" { argStr = argStr + String(char) } else { argActive = true } } else { if char == "\"" { if firstQuote { firstQuote = false } else { firstQuote = true argActive = false args[argStr.trimmingCharacters(in: .whitespaces)] = body body = "" argStr = "" } } else { body += String(char) } } } return args } /** Creates a JHTask from given args - parameter args: Dictionary containing args as keys and bodies as values - returns: The JHTask created and the name of the class it belonds to */ func createTaskFromArgs(args: [String: String]) -> (JHTask, String) { var name: String = "Untitled" var dueDate: Date = Date() let components = DateComponents(hour: 1, minute: 15) var timeToFinish: Date = Calendar.current.date(from: components)! var clas: String = "AP Calculus" for key in args.keys { switch key { case NotificationArgs.Class.rawValue: if args[key] != "" { clas = args[key]! } case NotificationArgs.Name.rawValue: if args[key] != "" { name = args[key]! } case NotificationArgs.DueDate.rawValue: if args[key] != "" { let formatter = DateFormatter() formatter.dateFormat = "MM/dd/yyyy" if let dueDatex = formatter.date(from: args[key]!) { dueDate = dueDatex } } case NotificationArgs.TimeToComplete.rawValue: if args[key] != "" { let formatter = DateFormatter() formatter.dateFormat = "hh:mm" if let TTF = formatter.date(from: args[key]!) { timeToFinish = TTF } } default: break } } return (JHTask(name: name, completed: false, dueDate: dueDate, estimatedTimeToComplete: timeToFinish), clas) } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
a3e3f390ac510072469b0fad2d84b68a
43.21547
285
0.603274
5.282508
false
false
false
false
JGiola/swift
stdlib/public/core/SetAlgebra.swift
5
25092
//===--- SetAlgebra.swift - Protocols for set operations ------------------===// // // 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 // //===----------------------------------------------------------------------===// // // // //===----------------------------------------------------------------------===// /// A type that provides mathematical set operations. /// /// You use types that conform to the `SetAlgebra` protocol when you need /// efficient membership tests or mathematical set operations such as /// intersection, union, and subtraction. In the standard library, you can /// use the `Set` type with elements of any hashable type, or you can easily /// create bit masks with `SetAlgebra` conformance using the `OptionSet` /// protocol. See those types for more information. /// /// - Note: Unlike ordinary set types, the `Element` type of an `OptionSet` is /// identical to the `OptionSet` type itself. The `SetAlgebra` protocol is /// specifically designed to accommodate both kinds of set. /// /// Conforming to the SetAlgebra Protocol /// ===================================== /// /// When implementing a custom type that conforms to the `SetAlgebra` protocol, /// you must implement the required initializers and methods. For the /// inherited methods to work properly, conforming types must meet the /// following axioms. Assume that `S` is a custom type that conforms to the /// `SetAlgebra` protocol, `x` and `y` are instances of `S`, and `e` is of /// type `S.Element`---the type that the set holds. /// /// - `S() == []` /// - `x.intersection(x) == x` /// - `x.intersection([]) == []` /// - `x.union(x) == x` /// - `x.union([]) == x` /// - `x.contains(e)` implies `x.union(y).contains(e)` /// - `x.union(y).contains(e)` implies `x.contains(e) || y.contains(e)` /// - `x.contains(e) && y.contains(e)` if and only if /// `x.intersection(y).contains(e)` /// - `x.isSubset(of: y)` implies `x.union(y) == y` /// - `x.isSuperset(of: y)` implies `x.union(y) == x` /// - `x.isSubset(of: y)` if and only if `y.isSuperset(of: x)` /// - `x.isStrictSuperset(of: y)` if and only if /// `x.isSuperset(of: y) && x != y` /// - `x.isStrictSubset(of: y)` if and only if `x.isSubset(of: y) && x != y` public protocol SetAlgebra<Element>: Equatable, ExpressibleByArrayLiteral { /// A type for which the conforming type provides a containment test. associatedtype Element /// Creates an empty set. /// /// This initializer is equivalent to initializing with an empty array /// literal. For example, you create an empty `Set` instance with either /// this initializer or with an empty array literal. /// /// var emptySet = Set<Int>() /// print(emptySet.isEmpty) /// // Prints "true" /// /// emptySet = [] /// print(emptySet.isEmpty) /// // Prints "true" init() /// Returns a Boolean value that indicates whether the given element exists /// in the set. /// /// This example uses the `contains(_:)` method to test whether an integer is /// a member of a set of prime numbers. /// /// let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] /// let x = 5 /// if primes.contains(x) { /// print("\(x) is prime!") /// } else { /// print("\(x). Not prime.") /// } /// // Prints "5 is prime!" /// /// - Parameter member: An element to look for in the set. /// - Returns: `true` if `member` exists in the set; otherwise, `false`. func contains(_ member: Element) -> Bool /// Returns a new set with the elements of both this and the given set. /// /// In the following example, the `attendeesAndVisitors` set is made up /// of the elements of the `attendees` and `visitors` sets: /// /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// let visitors = ["Marcia", "Nathaniel"] /// let attendeesAndVisitors = attendees.union(visitors) /// print(attendeesAndVisitors) /// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]" /// /// If the set already contains one or more elements that are also in /// `other`, the existing members are kept. /// /// let initialIndices = Set(0..<5) /// let expandedIndices = initialIndices.union([2, 3, 6, 7]) /// print(expandedIndices) /// // Prints "[2, 4, 6, 7, 0, 1, 3]" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: A new set with the unique elements of this set and `other`. /// /// - Note: if this set and `other` contain elements that are equal but /// distinguishable (e.g. via `===`), which of these elements is present /// in the result is unspecified. __consuming func union(_ other: __owned Self) -> Self /// Returns a new set with the elements that are common to both this set and /// the given set. /// /// In the following example, the `bothNeighborsAndEmployees` set is made up /// of the elements that are in *both* the `employees` and `neighbors` sets. /// Elements that are in only one or the other are left out of the result of /// the intersection. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] /// let bothNeighborsAndEmployees = employees.intersection(neighbors) /// print(bothNeighborsAndEmployees) /// // Prints "["Bethany", "Eric"]" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: A new set. /// /// - Note: if this set and `other` contain elements that are equal but /// distinguishable (e.g. via `===`), which of these elements is present /// in the result is unspecified. __consuming func intersection(_ other: Self) -> Self /// Returns a new set with the elements that are either in this set or in the /// given set, but not in both. /// /// In the following example, the `eitherNeighborsOrEmployees` set is made up /// of the elements of the `employees` and `neighbors` sets that are not in /// both `employees` *and* `neighbors`. In particular, the names `"Bethany"` /// and `"Eric"` do not appear in `eitherNeighborsOrEmployees`. /// /// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani"] /// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors) /// print(eitherNeighborsOrEmployees) /// // Prints "["Diana", "Forlani", "Alicia"]" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: A new set. __consuming func symmetricDifference(_ other: __owned Self) -> Self // FIXME(move-only types): SetAlgebra.insert is not implementable by a // set with move-only Element type, since it would be necessary to copy // the argument in order to both store it inside the set and return it as // the `memberAfterInsert`. /// Inserts the given element in the set if it is not already present. /// /// If an element equal to `newMember` is already contained in the set, this /// method has no effect. In this example, a new element is inserted into /// `classDays`, a set of days of the week. When an existing element is /// inserted, the `classDays` set does not change. /// /// enum DayOfTheWeek: Int { /// case sunday, monday, tuesday, wednesday, thursday, /// friday, saturday /// } /// /// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday] /// print(classDays.insert(.monday)) /// // Prints "(true, .monday)" /// print(classDays) /// // Prints "[.friday, .wednesday, .monday]" /// /// print(classDays.insert(.friday)) /// // Prints "(false, .friday)" /// print(classDays) /// // Prints "[.friday, .wednesday, .monday]" /// /// - Parameter newMember: An element to insert into the set. /// - Returns: `(true, newMember)` if `newMember` was not contained in the /// set. If an element equal to `newMember` was already contained in the /// set, the method returns `(false, oldMember)`, where `oldMember` is the /// element that was equal to `newMember`. In some cases, `oldMember` may /// be distinguishable from `newMember` by identity comparison or some /// other means. @discardableResult mutating func insert( _ newMember: __owned Element ) -> (inserted: Bool, memberAfterInsert: Element) /// Removes the given element and any elements subsumed by the given element. /// /// - Parameter member: The element of the set to remove. /// - Returns: For ordinary sets, an element equal to `member` if `member` is /// contained in the set; otherwise, `nil`. In some cases, a returned /// element may be distinguishable from `member` by identity comparison /// or some other means. /// /// For sets where the set type and element type are the same, like /// `OptionSet` types, this method returns any intersection between the set /// and `[member]`, or `nil` if the intersection is empty. @discardableResult mutating func remove(_ member: Element) -> Element? /// Inserts the given element into the set unconditionally. /// /// If an element equal to `newMember` is already contained in the set, /// `newMember` replaces the existing element. In this example, an existing /// element is inserted into `classDays`, a set of days of the week. /// /// enum DayOfTheWeek: Int { /// case sunday, monday, tuesday, wednesday, thursday, /// friday, saturday /// } /// /// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday] /// print(classDays.update(with: .monday)) /// // Prints "Optional(.monday)" /// /// - Parameter newMember: An element to insert into the set. /// - Returns: For ordinary sets, an element equal to `newMember` if the set /// already contained such a member; otherwise, `nil`. In some cases, the /// returned element may be distinguishable from `newMember` by identity /// comparison or some other means. /// /// For sets where the set type and element type are the same, like /// `OptionSet` types, this method returns any intersection between the /// set and `[newMember]`, or `nil` if the intersection is empty. @discardableResult mutating func update(with newMember: __owned Element) -> Element? /// Adds the elements of the given set to the set. /// /// In the following example, the elements of the `visitors` set are added to /// the `attendees` set: /// /// var attendees: Set = ["Alicia", "Bethany", "Diana"] /// let visitors: Set = ["Diana", "Marcia", "Nathaniel"] /// attendees.formUnion(visitors) /// print(attendees) /// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]" /// /// If the set already contains one or more elements that are also in /// `other`, the existing members are kept. /// /// var initialIndices = Set(0..<5) /// initialIndices.formUnion([2, 3, 6, 7]) /// print(initialIndices) /// // Prints "[2, 4, 6, 7, 0, 1, 3]" /// /// - Parameter other: A set of the same type as the current set. mutating func formUnion(_ other: __owned Self) /// Removes the elements of this set that aren't also in the given set. /// /// In the following example, the elements of the `employees` set that are /// not also members of the `neighbors` set are removed. In particular, the /// names `"Alicia"`, `"Chris"`, and `"Diana"` are removed. /// /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] /// employees.formIntersection(neighbors) /// print(employees) /// // Prints "["Bethany", "Eric"]" /// /// - Parameter other: A set of the same type as the current set. mutating func formIntersection(_ other: Self) /// Removes the elements of the set that are also in the given set and adds /// the members of the given set that are not already in the set. /// /// In the following example, the elements of the `employees` set that are /// also members of `neighbors` are removed from `employees`, while the /// elements of `neighbors` that are not members of `employees` are added to /// `employees`. In particular, the names `"Bethany"` and `"Eric"` are /// removed from `employees` while the name `"Forlani"` is added. /// /// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani"] /// employees.formSymmetricDifference(neighbors) /// print(employees) /// // Prints "["Diana", "Forlani", "Alicia"]" /// /// - Parameter other: A set of the same type. mutating func formSymmetricDifference(_ other: __owned Self) //===--- Requirements with default implementations ----------------------===// /// Returns a new set containing the elements of this set that do not occur /// in the given set. /// /// In the following example, the `nonNeighbors` set is made up of the /// elements of the `employees` set that are not elements of `neighbors`: /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] /// let nonNeighbors = employees.subtracting(neighbors) /// print(nonNeighbors) /// // Prints "["Diana", "Chris", "Alicia"]" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: A new set. __consuming func subtracting(_ other: Self) -> Self /// Returns a Boolean value that indicates whether the set is a subset of /// another set. /// /// Set *A* is a subset of another set *B* if every member of *A* is also a /// member of *B*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(attendees.isSubset(of: employees)) /// // Prints "true" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. func isSubset(of other: Self) -> Bool /// Returns a Boolean value that indicates whether the set has no members in /// common with the given set. /// /// In the following example, the `employees` set is disjoint with the /// `visitors` set because no name appears in both sets. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"] /// print(employees.isDisjoint(with: visitors)) /// // Prints "true" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: `true` if the set has no elements in common with `other`; /// otherwise, `false`. func isDisjoint(with other: Self) -> Bool /// Returns a Boolean value that indicates whether the set is a superset of /// the given set. /// /// Set *A* is a superset of another set *B* if every member of *B* is also a /// member of *A*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(employees.isSuperset(of: attendees)) /// // Prints "true" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: `true` if the set is a superset of `possibleSubset`; /// otherwise, `false`. func isSuperset(of other: Self) -> Bool /// A Boolean value that indicates whether the set has no elements. var isEmpty: Bool { get } /// Creates a new set from a finite sequence of items. /// /// Use this initializer to create a new set from an existing sequence, like /// an array or a range: /// /// let validIndices = Set(0..<7).subtracting([2, 4, 5]) /// print(validIndices) /// // Prints "[6, 0, 1, 3]" /// /// - Parameter sequence: The elements to use as members of the new set. init<S: Sequence>(_ sequence: __owned S) where S.Element == Element /// Removes the elements of the given set from this set. /// /// In the following example, the elements of the `employees` set that are /// also members of the `neighbors` set are removed. In particular, the /// names `"Bethany"` and `"Eric"` are removed from `employees`. /// /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] /// employees.subtract(neighbors) /// print(employees) /// // Prints "["Diana", "Chris", "Alicia"]" /// /// - Parameter other: A set of the same type as the current set. mutating func subtract(_ other: Self) } /// `SetAlgebra` requirements for which default implementations /// are supplied. /// /// - Note: A type conforming to `SetAlgebra` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension SetAlgebra { /// Creates a new set from a finite sequence of items. /// /// Use this initializer to create a new set from an existing sequence, like /// an array or a range: /// /// let validIndices = Set(0..<7).subtracting([2, 4, 5]) /// print(validIndices) /// // Prints "[6, 0, 1, 3]" /// /// - Parameter sequence: The elements to use as members of the new set. @inlinable // protocol-only public init<S: Sequence>(_ sequence: __owned S) where S.Element == Element { self.init() // Needed to fully optimize OptionSet literals. _onFastPath() for e in sequence { insert(e) } } /// Removes the elements of the given set from this set. /// /// In the following example, the elements of the `employees` set that are /// also members of the `neighbors` set are removed. In particular, the /// names `"Bethany"` and `"Eric"` are removed from `employees`. /// /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] /// employees.subtract(neighbors) /// print(employees) /// // Prints "["Diana", "Chris", "Alicia"]" /// /// - Parameter other: A set of the same type as the current set. @inlinable // protocol-only public mutating func subtract(_ other: Self) { self.formIntersection(self.symmetricDifference(other)) } /// Returns a Boolean value that indicates whether the set is a subset of /// another set. /// /// Set *A* is a subset of another set *B* if every member of *A* is also a /// member of *B*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(attendees.isSubset(of: employees)) /// // Prints "true" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. @inlinable // protocol-only public func isSubset(of other: Self) -> Bool { return self.intersection(other) == self } /// Returns a Boolean value that indicates whether the set is a superset of /// the given set. /// /// Set *A* is a superset of another set *B* if every member of *B* is also a /// member of *A*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(employees.isSuperset(of: attendees)) /// // Prints "true" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: `true` if the set is a superset of `other`; otherwise, /// `false`. @inlinable // protocol-only public func isSuperset(of other: Self) -> Bool { return other.isSubset(of: self) } /// Returns a Boolean value that indicates whether the set has no members in /// common with the given set. /// /// In the following example, the `employees` set is disjoint with the /// `visitors` set because no name appears in both sets. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"] /// print(employees.isDisjoint(with: visitors)) /// // Prints "true" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: `true` if the set has no elements in common with `other`; /// otherwise, `false`. @inlinable // protocol-only public func isDisjoint(with other: Self) -> Bool { return self.intersection(other).isEmpty } /// Returns a new set containing the elements of this set that do not occur /// in the given set. /// /// In the following example, the `nonNeighbors` set is made up of the /// elements of the `employees` set that are not elements of `neighbors`: /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] /// let nonNeighbors = employees.subtracting(neighbors) /// print(nonNeighbors) /// // Prints "["Diana", "Chris", "Alicia"]" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: A new set. @inlinable // protocol-only public func subtracting(_ other: Self) -> Self { return self.intersection(self.symmetricDifference(other)) } /// A Boolean value that indicates whether the set has no elements. @inlinable // protocol-only public var isEmpty: Bool { return self == Self() } /// Returns a Boolean value that indicates whether this set is a strict /// superset of the given set. /// /// Set *A* is a strict superset of another set *B* if every member of *B* is /// also a member of *A* and *A* contains at least one element that is *not* /// a member of *B*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(employees.isStrictSuperset(of: attendees)) /// // Prints "true" /// /// // A set is never a strict superset of itself: /// print(employees.isStrictSuperset(of: employees)) /// // Prints "false" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: `true` if the set is a strict superset of `other`; otherwise, /// `false`. @inlinable // protocol-only public func isStrictSuperset(of other: Self) -> Bool { return self.isSuperset(of: other) && self != other } /// Returns a Boolean value that indicates whether this set is a strict /// subset of the given set. /// /// Set *A* is a strict subset of another set *B* if every member of *A* is /// also a member of *B* and *B* contains at least one element that is not a /// member of *A*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(attendees.isStrictSubset(of: employees)) /// // Prints "true" /// /// // A set is never a strict subset of itself: /// print(attendees.isStrictSubset(of: attendees)) /// // Prints "false" /// /// - Parameter other: A set of the same type as the current set. /// - Returns: `true` if the set is a strict subset of `other`; otherwise, /// `false`. @inlinable // protocol-only public func isStrictSubset(of other: Self) -> Bool { return other.isStrictSuperset(of: self) } } extension SetAlgebra where Element == ArrayLiteralElement { /// Creates a set containing the elements of the given array literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you use an array literal. Instead, create a new set using an array /// literal as its value by enclosing a comma-separated list of values in /// square brackets. You can use an array literal anywhere a set is expected /// by the type context. /// /// Here, a set of strings is created from an array literal holding only /// strings: /// /// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"] /// if ingredients.isSuperset(of: ["sugar", "salt"]) { /// print("Whatever it is, it's bound to be delicious!") /// } /// // Prints "Whatever it is, it's bound to be delicious!" /// /// - Parameter arrayLiteral: A list of elements of the new set. @inlinable // protocol-only public init(arrayLiteral: Element...) { self.init(arrayLiteral) } }
apache-2.0
50ec6ca7a3f9017adf01c836ec6d4f0c
41.673469
83
0.621353
3.981593
false
false
false
false
dreamsxin/swift
stdlib/public/core/StringIndexConversions.swift
2
7781
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension String.Index { /// Creates an index in the given string that corresponds exactly to the /// specified `UnicodeScalarView` position. /// /// The following example converts the position of the Unicode scalar `"e"` /// into its corresponding position in the string's character view. The /// character at that position is the composed `"é"` character. /// /// let cafe = "Cafe\u{0301}" /// print(cafe) /// // Prints "Café" /// /// let scalarsIndex = cafe.unicodeScalars.index(of: "e")! /// let charactersIndex = String.Index(scalarsIndex, within: cafe)! /// /// print(String(cafe.characters.prefix(through: charactersIndex))) /// // Prints "Café" /// /// If the position passed in `unicodeScalarIndex` doesn't have an exact /// corresponding position in `other.characters`, the result of the /// initializer is `nil`. For example, an attempt to convert the position of /// the combining acute accent (`"\u{0301}"`) fails. Combining Unicode /// scalars do not have their own position in a character view. /// /// let nextIndex = String.Index(cafe.unicodeScalars.index(after: scalarsIndex), /// within: cafe) /// print(nextIndex) /// // Prints "nil" /// /// - Parameters: /// - unicodeScalarIndex: A position in the `unicodeScalars` view of the /// `other` parameter. /// - other: The string referenced by both `unicodeScalarIndex` and the /// resulting index. public init?( _ unicodeScalarIndex: String.UnicodeScalarIndex, within other: String ) { if !unicodeScalarIndex._isOnGraphemeClusterBoundary { return nil } self.init(_base: unicodeScalarIndex) } /// Creates an index in the given string that corresponds exactly to the /// specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the the string's /// `characters` view. The value `32` is the UTF-16 encoded value of a space /// character. /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.index(of: 32)! /// let charactersIndex = String.Index(utf16Index, within: cafe)! /// /// print(String(cafe.characters.prefix(upTo: charactersIndex))) /// // Prints "Café" /// /// If the position passed in `utf16Index` doesn't have an exact /// corresponding position in `other.characters`, the result of the /// initializer is `nil`. For example, an attempt to convert the position of /// the trailing surrogate of a UTF-16 surrogate pair fails. /// /// The next example attempts to convert the indices of the two UTF-16 code /// points that represent the teacup emoji (`"🍵"`). The index of the lead /// surrogate is successfully converted to a position in `other.characters`, /// but the index of the trailing surrogate is not. /// /// let emojiHigh = cafe.utf16.index(after: utf16Index) /// print(String.Index(emojiHigh, within: cafe)) /// // Prints "Optional(String.Index(...))" /// /// let emojiLow = cafe.utf16.index(after: emojiHigh) /// print(String.Index(emojiLow, within: cafe)) /// // Prints "nil" /// /// - Parameters: /// - utf16Index: A position in the `utf16` view of the `other` parameter. /// - other: The string referenced by both `utf16Index` and the resulting /// index. public init?( _ utf16Index: String.UTF16Index, within other: String ) { if let me = utf16Index.samePosition( in: other.unicodeScalars )?.samePosition(in: other) { self = me } else { return nil } } /// Creates an index in the given string that corresponds exactly to the /// specified `UTF8View` position. /// /// If the position passed in `utf8Index` doesn't have an exact corresponding /// position in `other.characters`, the result of the initializer is `nil`. /// For example, an attempt to convert the position of a UTF-8 continuation /// byte returns `nil`. /// /// - Parameters: /// - utf8Index: A position in the `utf8` view of the `other` parameter. /// - other: The string referenced by both `utf8Index` and the resulting /// index. public init?( _ utf8Index: String.UTF8Index, within other: String ) { if let me = utf8Index.samePosition( in: other.unicodeScalars )?.samePosition(in: other) { self = me } else { return nil } } /// Returns the position in the given UTF-8 view that corresponds exactly to /// this index. /// /// The index must be a valid index of `String(utf8).characters`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `utf8` view. /// /// let cafe = "Café" /// if let i = cafe.characters.index(of: "é") { /// let j = i.samePosition(in: cafe.utf8) /// print(Array(cafe.utf8.suffix(from: j))) /// } /// // Prints "[195, 169]" /// /// - Parameter utf8: The view to use for the index conversion. /// - Returns: The position in `utf8` that corresponds exactly to this index. public func samePosition( in utf8: String.UTF8View ) -> String.UTF8View.Index { return String.UTF8View.Index(self, within: utf8) } /// Returns the position in the given UTF-16 view that corresponds exactly to /// this index. /// /// The index must be a valid index of `String(utf16).characters`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `utf16` view. /// /// let cafe = "Café" /// if let i = cafe.characters.index(of: "é") { /// let j = i.samePosition(in: cafe.utf16) /// print(cafe.utf16[j]) /// } /// // Prints "233" /// /// - Parameter utf16: The view to use for the index conversion. /// - Returns: The position in `utf16` that corresponds exactly to this index. public func samePosition( in utf16: String.UTF16View ) -> String.UTF16View.Index { return String.UTF16View.Index(self, within: utf16) } /// Returns the position in the given view of Unicode scalars that /// corresponds exactly to this index. /// /// The index must be a valid index of `String(unicodeScalars).characters`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `unicodeScalars` /// view. /// /// let cafe = "Café" /// if let i = cafe.characters.index(of: "é") { /// let j = i.samePosition(in: cafe.unicodeScalars) /// print(cafe.unicodeScalars[j]) /// } /// // Prints "é" /// /// - Parameter unicodeScalars: The view to use for the index conversion. /// - Returns: The position in `unicodeScalars` that corresponds exactly to /// this index. public func samePosition( in unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarView.Index { return String.UnicodeScalarView.Index(self, within: unicodeScalars) } }
apache-2.0
83d33896758c6408791d8dc5b6b3b1d5
36.669903
86
0.627191
4.077772
false
false
false
false
kosicki123/eidolon
Kiosk/App/Models/SystemTime.swift
1
1251
import Foundation import ISO8601DateFormatter public class SystemTime { public var systemTimeInterval: NSTimeInterval? = nil public init () {} public func syncSignal() -> RACSignal { let endpoint: ArtsyAPI = ArtsyAPI.SystemTime return XAppRequest(endpoint).filterSuccessfulStatusCodes().mapJSON() .doNext { [weak self] (response) -> Void in if let dictionary = response as? NSDictionary { let formatter = ISO8601DateFormatter() let artsyDate = formatter.dateFromString(dictionary["iso8601"] as String?) self?.systemTimeInterval = NSDate().timeIntervalSinceDate(artsyDate) } }.doError { (error) -> Void in println("Error: \(error.localizedDescription)") } } public func inSync() -> Bool { return systemTimeInterval != nil } public func date() -> NSDate { let now = NSDate() if let systemTimeInterval = systemTimeInterval { return now.dateByAddingTimeInterval(-systemTimeInterval) } else { return now } } public func reset() { systemTimeInterval = nil } }
mit
ab32e4f52c346e9a7e43f75c11d5dba3
28.785714
94
0.585132
5.818605
false
false
false
false
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/View Collection/QRoomList/QRoomList.swift
1
10358
// // QRoomList.swift // Example // // Created by Ahmad Athaullah on 9/15/17. // Copyright © 2017 Ahmad Athaullah. All rights reserved. // import UIKit @objc public protocol QRoomListDelegate { /** Click Cell and redirect to chat view */ @objc optional func didSelect(room: QRoom) @objc optional func didDeselect(room:QRoom) @objc optional func didSelect(comment: QComment) @objc optional func didDeselect(comment:QComment) @objc optional func didScrollBottom() @objc optional func willLoad(rooms: [QRoom]) -> [QRoom]? /** Return your custom table view cell as QRoomListCell */ @objc optional func tableviewCell(for room: QRoom) -> QRoomListCell? } open class QRoomList: UITableView{ public var listDelegate: QRoomListDelegate? public var rooms = [QRoom]() private var clearingData:Bool = false public var filteredRooms: [QRoom] { get{ let text = searchText.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if text == "" { return self.rooms }else{ return self.rooms.filter({ (room) in return room.name.lowercased().contains(text) }) } } } public var comments = [QComment](){ didSet{ let indexSet = IndexSet(integer: 1) self.reloadSections(indexSet, with: UITableViewRowAnimation.fade) } } public var searchText:String = "" { didSet{ let indexSet = IndexSet(integer: 0) self.reloadSections(indexSet, with: .none) } } public var searchComment : Bool = true override open func draw(_ rect: CGRect) { // Drawing code self.delegate = self self.dataSource = self self.estimatedRowHeight = 60 self.rowHeight = UITableViewAutomaticDimension self.tableFooterView = UIView() NotificationCenter.default.addObserver(self, selector: #selector(QRoomList.roomListChange(_:)), name: QiscusNotification.ROOM_ORDER_MAY_CHANGE, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(QRoomList.roomListChange(_:)), name: QiscusNotification.ROOM_DELETED, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(QRoomList.dataCleared(_:)), name: QiscusNotification.FINISHED_CLEAR_MESSAGES, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(QRoomList.newRoom(_:)), name: QiscusNotification.GOT_NEW_ROOM, object: nil) registerCell() } open func registerCell(){ self.register(UINib(nibName: "QRoomListDefaultCell", bundle: Qiscus.bundle), forCellReuseIdentifier: "roomDefaultCell") self.register(UINib(nibName: "QSearchListDefaultCell", bundle: Qiscus.bundle), forCellReuseIdentifier: "searchDefaultCell") } internal func didSelectRoom(room: QRoom){ self.listDelegate?.didSelect?(room: room) } internal func didSelectComment(comment: QComment){ self.listDelegate?.didSelect?(comment: comment) } internal func didScrollBottom(){ self.listDelegate?.didScrollBottom?() } open func roomCell(at row: Int) -> QRoomListCell { let indexPath = IndexPath(row: row, section: 0) let cell = self.dequeueReusableCell(withIdentifier: "roomDefaultCell", for: indexPath) as! QRoomListDefaultCell return cell } open func commentCell(at row: Int) -> QSearchListCell{ let indexPath = IndexPath(row: row, section: 1) let cell = self.dequeueReusableCell(withIdentifier: "searchDefaultCell", for: indexPath) as! QSearchListDefaultCell return cell } public func reload(){ if !self.clearingData { let roomsData = QRoom.all() if let extRooms = self.listDelegate?.willLoad?(rooms: roomsData) { self.rooms = extRooms } else { self.rooms = roomsData } let indexSet = IndexSet(integer: 0) self.reloadSections(indexSet, with: .none) } } public func search(text:String, searchLocal: Bool = false, searchComment: Bool = true){ self.searchText = text self.searchComment = searchComment if searchComment { if !searchLocal { QChatService.searchComment(withQuery: text, onSuccess: { (comments) in if text == self.searchText { self.comments = comments } }) { (error) in Qiscus.printLog(text: "test") } } else { self.comments = Qiscus.searchComment(searchQuery: text) } } } @objc private func dataCleared(_ notification: Notification){ dataCleared() self.clearingData = true } @objc private func newRoom(_ notification: Notification){ if let userInfo = notification.userInfo { if let room = userInfo["room"] as? QRoom { if room.isInvalidated { self.reload() }else{ self.gotNewRoom(room: room) } } } } @objc private func roomListChange(_ notification: Notification){ self.reload() } open func dataCleared(){ self.reload() } open func gotNewRoom(room:QRoom){ self.reload() } open func roomListChange(){ self.rooms = QRoom.all() let indexSet = IndexSet(integer: 0) self.reloadSections(indexSet, with: .none) } open func roomSectionHeight()->CGFloat{ if self.searchText != ""{ return 25.0 } else { return 0 } } open func commentSectionHeight()->CGFloat{ if self.searchText != ""{ return 25.0 } else { return 0 } } open func roomHeader()->UIView? { if self.searchText != "" { let screenWidth: CGFloat = QiscusHelper.screenWidth() let container = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 25)) let title = UILabel(frame: CGRect(x: 8, y: 0, width: screenWidth - 16, height: 25)) title.textAlignment = NSTextAlignment.left title.textColor = UIColor.black title.font = UIFont.boldSystemFont(ofSize: 12) title.text = "Conversations" container.backgroundColor = UIColor.lightGray container.addSubview(title) return container } else { return nil } } open func commentHeader()->UIView?{ if self.searchText != "" && searchComment{ let screenWidth: CGFloat = QiscusHelper.screenWidth() let container = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 25)) let title = UILabel(frame: CGRect(x: 8, y: 0, width: screenWidth - 16, height: 25)) title.textAlignment = NSTextAlignment.left title.textColor = UIColor.black title.font = UIFont.boldSystemFont(ofSize: 12) title.text = "Messages" container.backgroundColor = UIColor.lightGray container.addSubview(title) return container } else { return nil } } } extension QRoomList: UITableViewDelegate,UITableViewDataSource { open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return self.filteredRooms.count case 1: return self.comments.count default: return 0 } } open func numberOfSections(in tableView: UITableView) -> Int { return 2 } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // When filter or search active, top section is room result then comment result if indexPath.section == 0 { let room = self.filteredRooms[indexPath.row] // New approach Custom Cell if var cell = self.listDelegate?.tableviewCell?(for: room) { cell = self.dequeueReusableCell(withIdentifier: cell.reuseIdentifier!, for: indexPath) as! QRoomListCell cell.room = room cell.searchText = searchText return cell } if(rooms.count - 1 == indexPath.row ){ self.didScrollBottom() } let cell = self.roomCell(at: indexPath.row) cell.room = room cell.searchText = searchText return cell }else{ let cell = self.commentCell(at: indexPath.row) cell.comment = self.comments[indexPath.row] cell.searchText = self.searchText return cell } } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0 { didSelectRoom(room: self.filteredRooms[indexPath.row]) }else{ didSelectComment(comment: self.comments[indexPath.row]) } } open func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if indexPath.section == 0 { self.listDelegate?.didDeselect?(room: self.filteredRooms[indexPath.row]) }else{ self.listDelegate?.didDeselect?(comment: self.comments[indexPath.row]) } } open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return self.roomSectionHeight() }else{ return self.commentSectionHeight() } } open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { return roomHeader() }else{ return commentHeader() } } }
mit
6b24e330559be5d24dd1c2ce51687718
34.591065
164
0.582794
4.908531
false
false
false
false
mcxiaoke/learning-ios
ios_programming_4th/TouchTracker-ch13-excercises/TouchTracker/DrawView.swift
1
9097
// // DrawView.swift // TouchTracker // // Created by Xiaoke Zhang on 2017/8/17. // Copyright © 2017年 Xiaoke Zhang. All rights reserved. // import UIKit class DrawView: UIView { var currentWidth:CGFloat = 10 var currentLines:[NSValue:Line] = [:] var finishedLines:[Line] = [] weak var selectedLine:Line? var moveRecongnizer: UIPanGestureRecognizer? override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { self.isMultipleTouchEnabled = true self.backgroundColor = UIColor.white // load() let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTap(gs:))) doubleTap.numberOfTapsRequired = 2 doubleTap.delaysTouchesBegan = true self.addGestureRecognizer(doubleTap) let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTap(gs:))) singleTap.numberOfTapsRequired = 1 singleTap.require(toFail: doubleTap) singleTap.delaysTouchesBegan = true self.addGestureRecognizer(singleTap) let longPress = UILongPressGestureRecognizer.init(target: self, action: #selector(longPress(gs:))) self.addGestureRecognizer(longPress) let move = UIPanGestureRecognizer(target: self, action: #selector(move(gs:))) move.delegate = self move.cancelsTouchesInView = false self.moveRecongnizer = move self.addGestureRecognizer(move) let threeSwipe = UISwipeGestureRecognizer.init(target: self, action: #selector(threeSwipe(gs:))) threeSwipe.numberOfTouchesRequired = 3 threeSwipe.cancelsTouchesInView = true threeSwipe.direction = .up self.addGestureRecognizer(threeSwipe) } func threeSwipe(gs:UIGestureRecognizer) { print("threeSwipe") } func longPress(gs:UIGestureRecognizer) { switch gs.state { case .began: print("longPress began") let point = gs.location(in: self) self.selectedLine = lineAt(point: point) if let _ = self.selectedLine { self.currentLines.removeAll() } case .ended: print("longPress end") self.selectedLine = nil default: break } setNeedsDisplay() } func singleTap(gs: UIGestureRecognizer) { print("singleTap \(gs.location(in: self))") let point = gs.location(in: self) self.selectedLine = lineAt(point: point) setNeedsDisplay() if let _ = self.selectedLine { self.becomeFirstResponder() let menu = UIMenuController.shared let deleteItem = UIMenuItem.init(title: "Delete", action: #selector(deleteLine(_:))) menu.menuItems = [deleteItem] menu.setTargetRect(CGRect(x: point.x, y:point.y, width: 2, height: 2), in: self) menu.isMenuVisible = true } else { UIMenuController.shared.isMenuVisible = false } } func doubleTap(gs: UIGestureRecognizer) { print("doubleTap \(gs.location(in: self))") self.currentLines.removeAll() self.finishedLines.removeAll() setNeedsDisplay() } func updateSpeed(gs: UIPanGestureRecognizer) { let velocity = gs.velocity(in: self) // min=0 20px max=6000 5px let speed = min(sqrt(velocity.x*velocity.x + velocity.y*velocity.y), 6000) self.currentWidth = max(20 - speed/6000 * 20, 2) // print("updateSpeed speed=\(speed) currentWidth=\(currentWidth)") } func move(gs: UIPanGestureRecognizer) { updateSpeed(gs: gs) guard !UIMenuController.shared.isMenuVisible else { return } guard let line = self.selectedLine else { return } switch gs.state { case .changed: let translation = gs.translation(in: self) line.begin.x += translation.x line.begin.y += translation.y line.end.x += translation.x line.end.y += translation.y gs.setTranslation(CGPoint.zero, in: self) setNeedsDisplay() default: break } } func deleteLine(_ id: Any?) { if let line = self.selectedLine { self.finishedLines.remove(object: line) setNeedsDisplay() } } func lineAt(point: CGPoint) -> Line? { for line in self.finishedLines { let start = line.begin let end = line.end var t = CGFloat(0.0) while t <= 1.0 { let x = start.x + t * (end.x - start.x) let y = start.y + t * (end.y - start.y) if hypot(x - point.x, y - point.y) < 20.0 { print("found line: \(line)") return line } t += 0.05 } } return nil } func getLinesStoreFile() -> String { let fileDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) return fileDir.appendingPathComponent("finishedLines.dat").path } func getColorsStoreFile() -> String { let fileDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) return fileDir.appendingPathComponent("finishedLineColors.dat").path } func save() { let ret = NSKeyedArchiver.archiveRootObject(self.finishedLines, toFile: getLinesStoreFile()) print("save result=\(ret)") } func load() { if let lines = NSKeyedUnarchiver.unarchiveObject(withFile: getLinesStoreFile()) as? [Line] { self.finishedLines = lines } setNeedsDisplay() } override var canBecomeFirstResponder: Bool { return true } override func draw(_ rect: CGRect) { for line in finishedLines { line.color.set() strokeLine(line) } if let line = self.selectedLine { UIColor.yellow.set() strokeLine(line) } UIColor.red.set() for line in currentLines.values { strokeLine(line, width: currentWidth) } } func strokeLine(_ line: Line, width: CGFloat? = nil) { let bp = UIBezierPath() bp.lineWidth = width ?? line.width bp.lineCapStyle = .round bp.move(to: line.begin) bp.addLine(to: line.end) bp.stroke() } // MARK: TouchEvent override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("\(#function) \(currentWidth)") for t in touches { let p = t.location(in: self) let line = Line(begin: p, end: p) // using memory address let key = NSValue(nonretainedObject: t) self.currentLines[key] = line } setNeedsDisplay() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { // print("\(#function) \(touches.map({$0.location(in: self)}))") for t in touches { let key = NSValue(nonretainedObject: t) if let line = self.currentLines[key] { line.end = t.location(in: self) self.currentLines[key] = line } } setNeedsDisplay() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { print("\(#function) \(currentWidth)") for t in touches { let key = NSValue(nonretainedObject: t) if let line = self.currentLines[key] { line.width = currentWidth self.finishedLines.append(line) self.currentLines[key] = nil } } setNeedsDisplay() // save() } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { print("\(#function) \(touches.map({$0.location(in: self)}))") for t in touches { let key = NSValue(nonretainedObject: t) self.currentLines[key] = nil } setNeedsDisplay() // save() } } extension DrawView: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return gestureRecognizer == self.moveRecongnizer } }
apache-2.0
99b1d2f964fe50ac828e21396ef385f5
32.311355
115
0.555641
4.806554
false
false
false
false
thierrybucco/Eureka
Source/Core/Core.swift
5
42520
// Core.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit // MARK: Row internal class RowDefaults { static var cellUpdate = [String: (BaseCell, BaseRow) -> Void]() static var cellSetup = [String: (BaseCell, BaseRow) -> Void]() static var onCellHighlightChanged = [String: (BaseCell, BaseRow) -> Void]() static var rowInitialization = [String: (BaseRow) -> Void]() static var onRowValidationChanged = [String: (BaseCell, BaseRow) -> Void]() static var rawCellUpdate = [String: Any]() static var rawCellSetup = [String: Any]() static var rawOnCellHighlightChanged = [String: Any]() static var rawRowInitialization = [String: Any]() static var rawOnRowValidationChanged = [String: Any]() } // MARK: FormCells public struct CellProvider<Cell: BaseCell> where Cell: CellType { /// Nibname of the cell that will be created. public private (set) var nibName: String? /// Bundle from which to get the nib file. public private (set) var bundle: Bundle! public init() {} public init(nibName: String, bundle: Bundle? = nil) { self.nibName = nibName self.bundle = bundle ?? Bundle(for: Cell.self) } /** Creates the cell with the specified style. - parameter cellStyle: The style with which the cell will be created. - returns: the cell */ func makeCell(style: UITableViewCellStyle) -> Cell { if let nibName = self.nibName { return bundle.loadNibNamed(nibName, owner: nil, options: nil)!.first as! Cell } return Cell.init(style: style, reuseIdentifier: nil) } } /** Enumeration that defines how a controller should be created. - Callback->VCType: Creates the controller inside the specified block - NibFile: Loads a controller from a nib file in some bundle - StoryBoard: Loads the controller from a Storyboard by its storyboard id */ public enum ControllerProvider<VCType: UIViewController> { /** * Creates the controller inside the specified block */ case callback(builder: (() -> VCType)) /** * Loads a controller from a nib file in some bundle */ case nibFile(name: String, bundle: Bundle?) /** * Loads the controller from a Storyboard by its storyboard id */ case storyBoard(storyboardId: String, storyboardName: String, bundle: Bundle?) func makeController() -> VCType { switch self { case .callback(let builder): return builder() case .nibFile(let nibName, let bundle): return VCType.init(nibName: nibName, bundle:bundle ?? Bundle(for: VCType.self)) case .storyBoard(let storyboardId, let storyboardName, let bundle): let sb = UIStoryboard(name: storyboardName, bundle: bundle ?? Bundle(for: VCType.self)) return sb.instantiateViewController(withIdentifier: storyboardId) as! VCType } } } /** * Responsible for the options passed to a selector view controller */ public struct DataProvider<T: Equatable> { public let arrayData: [T]? public init(arrayData: [T]) { self.arrayData = arrayData } } /** Defines how a controller should be presented. - Show?: Shows the controller with `showViewController(...)`. - PresentModally?: Presents the controller modally. - SegueName?: Performs the segue with the specified identifier (name). - SegueClass?: Performs a segue from a segue class. */ public enum PresentationMode<VCType: UIViewController> { /** * Shows the controller, created by the specified provider, with `showViewController(...)`. */ case show(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?) /** * Presents the controller, created by the specified provider, modally. */ case presentModally(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?) /** * Performs the segue with the specified identifier (name). */ case segueName(segueName: String, onDismiss: ((UIViewController) -> Void)?) /** * Performs a segue from a segue class. */ case segueClass(segueClass: UIStoryboardSegue.Type, onDismiss: ((UIViewController) -> Void)?) case popover(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?) public var onDismissCallback: ((UIViewController) -> Void)? { switch self { case .show(_, let completion): return completion case .presentModally(_, let completion): return completion case .segueName(_, let completion): return completion case .segueClass(_, let completion): return completion case .popover(_, let completion): return completion } } /** Present the view controller provided by PresentationMode. Should only be used from custom row implementation. - parameter viewController: viewController to present if it makes sense (normally provided by makeController method) - parameter row: associated row - parameter presentingViewController: form view controller */ public func present(_ viewController: VCType!, row: BaseRow, presentingController: FormViewController) { switch self { case .show(_, _): presentingController.show(viewController, sender: row) case .presentModally(_, _): presentingController.present(viewController, animated: true) case .segueName(let segueName, _): presentingController.performSegue(withIdentifier: segueName, sender: row) case .segueClass(let segueClass, _): let segue = segueClass.init(identifier: row.tag, source: presentingController, destination: viewController) presentingController.prepare(for: segue, sender: row) segue.perform() case .popover(_, _): guard let porpoverController = viewController.popoverPresentationController else { fatalError() } porpoverController.sourceView = porpoverController.sourceView ?? presentingController.tableView presentingController.present(viewController, animated: true) } } /** Creates the view controller specified by presentation mode. Should only be used from custom row implementation. - returns: the created view controller or nil depending on the PresentationMode type. */ public func makeController() -> VCType? { switch self { case .show(let controllerProvider, let completionCallback): let controller = controllerProvider.makeController() let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.onDismissCallback = callback } return controller case .presentModally(let controllerProvider, let completionCallback): let controller = controllerProvider.makeController() let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.onDismissCallback = callback } return controller case .popover(let controllerProvider, let completionCallback): let controller = controllerProvider.makeController() controller.modalPresentationStyle = .popover let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.onDismissCallback = callback } return controller default: return nil } } } /** * Protocol to be implemented by custom formatters. */ public protocol FormatterProtocol { func getNewPosition(forPosition: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition } // MARK: Predicate Machine enum ConditionType { case hidden, disabled } /** Enumeration that are used to specify the disbaled and hidden conditions of rows - Function: A function that calculates the result - Predicate: A predicate that returns the result */ public enum Condition { /** * Calculate the condition inside a block * * @param Array of tags of the rows this function depends on * @param Form->Bool The block that calculates the result * * @return If the condition is true or false */ case function([String], (Form)->Bool) /** * Calculate the condition using a NSPredicate * * @param NSPredicate The predicate that will be evaluated * * @return If the condition is true or false */ case predicate(NSPredicate) } extension Condition : ExpressibleByBooleanLiteral { /** Initialize a condition to return afixed boolean value always */ public init(booleanLiteral value: Bool) { self = Condition.function([]) { _ in return value } } } extension Condition : ExpressibleByStringLiteral { /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(stringLiteral value: String) { self = .predicate(NSPredicate(format: value)) } /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(unicodeScalarLiteral value: String) { self = .predicate(NSPredicate(format: value)) } /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(extendedGraphemeClusterLiteral value: String) { self = .predicate(NSPredicate(format: value)) } } // MARK: Errors /** Errors thrown by Eureka - DuplicatedTag: When a section or row is inserted whose tag dows already exist */ public enum EurekaError: Error { case duplicatedTag(tag: String) } //Mark: FormViewController /** * A protocol implemented by FormViewController */ public protocol FormViewControllerProtocol { var tableView: UITableView! { get } func beginEditing<T: Equatable>(of: Cell<T>) func endEditing<T: Equatable>(of: Cell<T>) func insertAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation func deleteAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation func reloadAnimation(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation func insertAnimation(forSections sections: [Section]) -> UITableViewRowAnimation func deleteAnimation(forSections sections: [Section]) -> UITableViewRowAnimation func reloadAnimation(oldSections: [Section], newSections: [Section]) -> UITableViewRowAnimation } /** * Navigation options for a form view controller. */ public struct RowNavigationOptions: OptionSet { private enum NavigationOptions: Int { case disabled = 0, enabled = 1, stopDisabledRow = 2, skipCanNotBecomeFirstResponderRow = 4 } public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue} private init(_ options: NavigationOptions ) { self.rawValue = options.rawValue } /// No navigation. public static let Disabled = RowNavigationOptions(.disabled) /// Full navigation. public static let Enabled = RowNavigationOptions(.enabled) /// Break navigation when next row is disabled. public static let StopDisabledRow = RowNavigationOptions(.stopDisabledRow) /// Break navigation when next row cannot become first responder. public static let SkipCanNotBecomeFirstResponderRow = RowNavigationOptions(.skipCanNotBecomeFirstResponderRow) } /** * Defines the configuration for the keyboardType of FieldRows. */ public struct KeyboardReturnTypeConfiguration { /// Used when the next row is available. public var nextKeyboardType = UIReturnKeyType.next /// Used if next row is not available. public var defaultKeyboardType = UIReturnKeyType.default public init() {} public init(nextKeyboardType: UIReturnKeyType, defaultKeyboardType: UIReturnKeyType) { self.nextKeyboardType = nextKeyboardType self.defaultKeyboardType = defaultKeyboardType } } /** * Options that define when an inline row should collapse. */ public struct InlineRowHideOptions: OptionSet { private enum _InlineRowHideOptions: Int { case never = 0, anotherInlineRowIsShown = 1, firstResponderChanges = 2 } public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue} private init(_ options: _InlineRowHideOptions ) { self.rawValue = options.rawValue } /// Never collapse automatically. Only when user taps inline row. public static let Never = InlineRowHideOptions(.never) /// Collapse qhen another inline row expands. Just one inline row will be expanded at a time. public static let AnotherInlineRowIsShown = InlineRowHideOptions(.anotherInlineRowIsShown) /// Collapse when first responder changes. public static let FirstResponderChanges = InlineRowHideOptions(.firstResponderChanges) } /// View controller that shows a form. open class FormViewController: UIViewController, FormViewControllerProtocol { @IBOutlet public var tableView: UITableView! private lazy var _form: Form = { [weak self] in let form = Form() form.delegate = self return form }() public var form: Form { get { return _form } set { guard form !== newValue else { return } _form.delegate = nil tableView?.endEditing(false) _form = newValue _form.delegate = self if isViewLoaded { tableView?.reloadData() } } } /// Extra space to leave between between the row in focus and the keyboard open var rowKeyboardSpacing: CGFloat = 0 /// Enables animated scrolling on row navigation open var animateScroll = false /// Accessory view that is responsible for the navigation between rows open var navigationAccessoryView: NavigationAccessoryView! /// Defines the behaviour of the navigation between rows public var navigationOptions: RowNavigationOptions? private var tableViewStyle: UITableViewStyle = .grouped public init(style: UITableViewStyle) { super.init(nibName: nil, bundle: nil) tableViewStyle = style } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func viewDidLoad() { super.viewDidLoad() navigationAccessoryView = NavigationAccessoryView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 44.0)) navigationAccessoryView.autoresizingMask = .flexibleWidth if tableView == nil { tableView = UITableView(frame: view.bounds, style: tableViewStyle) tableView.autoresizingMask = UIViewAutoresizing.flexibleWidth.union(.flexibleHeight) if #available(iOS 9.0, *) { tableView.cellLayoutMarginsFollowReadableWidth = false } } if tableView.superview == nil { view.addSubview(tableView) } if tableView.delegate == nil { tableView.delegate = self } if tableView.dataSource == nil { tableView.dataSource = self } tableView.estimatedRowHeight = BaseRow.estimatedRowHeight tableView.setEditing(true, animated: false) tableView.allowsSelectionDuringEditing = true } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) animateTableView = true let selectedIndexPaths = tableView.indexPathsForSelectedRows ?? [] if !selectedIndexPaths.isEmpty { tableView.reloadRows(at: selectedIndexPaths, with: .none) } selectedIndexPaths.forEach { tableView.selectRow(at: $0, animated: false, scrollPosition: .none) } let deselectionAnimation = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in selectedIndexPaths.forEach { self?.tableView.deselectRow(at: $0, animated: context.isAnimated) } } let reselection = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in if context.isCancelled { selectedIndexPaths.forEach { self?.tableView.selectRow(at: $0, animated: false, scrollPosition: .none) } } } if let coordinator = transitionCoordinator { coordinator.animate(alongsideTransition: deselectionAnimation, completion: reselection) } else { selectedIndexPaths.forEach { tableView.deselectRow(at: $0, animated: false) } } NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillHide(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil) } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil) } open override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) let baseRow = sender as? BaseRow baseRow?.prepare(for: segue) } /** Returns the navigation accessory view if it is enabled. Returns nil otherwise. */ open func inputAccessoryView(for row: BaseRow) -> UIView? { let options = navigationOptions ?? Form.defaultNavigationOptions guard options.contains(.Enabled) else { return nil } guard row.baseCell.cellCanBecomeFirstResponder() else { return nil} navigationAccessoryView.previousButton.isEnabled = nextRow(for: row, withDirection: .up) != nil navigationAccessoryView.doneButton.target = self navigationAccessoryView.doneButton.action = #selector(FormViewController.navigationDone(_:)) navigationAccessoryView.previousButton.target = self navigationAccessoryView.previousButton.action = #selector(FormViewController.navigationAction(_:)) navigationAccessoryView.nextButton.target = self navigationAccessoryView.nextButton.action = #selector(FormViewController.navigationAction(_:)) navigationAccessoryView.nextButton.isEnabled = nextRow(for: row, withDirection: .down) != nil return navigationAccessoryView } // MARK: FormViewControllerProtocol /** Called when a cell becomes first responder */ public final func beginEditing<T: Equatable>(of cell: Cell<T>) { cell.row.isHighlighted = true cell.row.updateCell() RowDefaults.onCellHighlightChanged["\(type(of: cell.row!))"]?(cell, cell.row) cell.row.callbackOnCellHighlightChanged?() guard let _ = tableView, (form.inlineRowHideOptions ?? Form.defaultInlineRowHideOptions).contains(.FirstResponderChanges) else { return } let row = cell.baseRow let inlineRow = row?._inlineRow for row in form.allRows.filter({ $0 !== row && $0 !== inlineRow && $0._inlineRow != nil }) { if let inlineRow = row as? BaseInlineRowType { inlineRow.collapseInlineRow() } } } /** Called when a cell resigns first responder */ public final func endEditing<T: Equatable>(of cell: Cell<T>) { cell.row.isHighlighted = false cell.row.wasBlurred = true RowDefaults.onCellHighlightChanged["\(type(of: self))"]?(cell, cell.row) cell.row.callbackOnCellHighlightChanged?() if cell.row.validationOptions.contains(.validatesOnBlur) || (cell.row.wasChanged && cell.row.validationOptions.contains(.validatesOnChangeAfterBlurred)) { cell.row.validate() } cell.row.updateCell() } /** Returns the animation for the insertion of the given rows. */ open func insertAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation { return .fade } /** Returns the animation for the deletion of the given rows. */ open func deleteAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation { return .fade } /** Returns the animation for the reloading of the given rows. */ open func reloadAnimation(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation { return .automatic } /** Returns the animation for the insertion of the given sections. */ open func insertAnimation(forSections sections: [Section]) -> UITableViewRowAnimation { return .automatic } /** Returns the animation for the deletion of the given sections. */ open func deleteAnimation(forSections sections: [Section]) -> UITableViewRowAnimation { return .automatic } /** Returns the animation for the reloading of the given sections. */ open func reloadAnimation(oldSections: [Section], newSections: [Section]) -> UITableViewRowAnimation { return .automatic } // MARK: TextField and TextView Delegate open func textInputShouldBeginEditing<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { return true } open func textInputDidBeginEditing<T>(_ textInput: UITextInput, cell: Cell<T>) { if let row = cell.row as? KeyboardReturnHandler { let next = nextRow(for: cell.row, withDirection: .down) if let textField = textInput as? UITextField { textField.returnKeyType = next != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType)) } else if let textView = textInput as? UITextView { textView.returnKeyType = next != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType)) } } } open func textInputShouldEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { return true } open func textInputDidEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) { } open func textInput<T>(_ textInput: UITextInput, shouldChangeCharactersInRange range: NSRange, replacementString string: String, cell: Cell<T>) -> Bool { return true } open func textInputShouldClear<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { return true } open func textInputShouldReturn<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { if let nextRow = nextRow(for: cell.row, withDirection: .down) { if nextRow.baseCell.cellCanBecomeFirstResponder() { nextRow.baseCell.cellBecomeFirstResponder() return true } } tableView?.endEditing(true) return true } // MARK: FormDelegate open func valueHasBeenChanged(for: BaseRow, oldValue: Any?, newValue: Any?) {} // MARK: UITableViewDelegate @objc open func tableView(_ tableView: UITableView, willBeginReorderingRowAtIndexPath indexPath: IndexPath) { // end editing if inline cell is first responder let row = form[indexPath] if let inlineRow = row as? BaseInlineRowType, row._inlineRow != nil { inlineRow.collapseInlineRow() } } // MARK: Private var oldBottomInset: CGFloat? var animateTableView = false } extension FormViewController : UITableViewDelegate { // MARK: UITableViewDelegate open func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return indexPath } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard tableView == self.tableView else { return } let row = form[indexPath] // row.baseCell.cellBecomeFirstResponder() may be cause InlineRow collapsed then section count will be changed. Use orignal indexPath will out of section's bounds. if !row.baseCell.cellCanBecomeFirstResponder() || !row.baseCell.cellBecomeFirstResponder() { self.tableView?.endEditing(true) } row.didSelect() } open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard tableView == self.tableView else { return tableView.rowHeight } let row = form[indexPath.section][indexPath.row] return row.baseCell.height?() ?? tableView.rowHeight } open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { guard tableView == self.tableView else { return tableView.rowHeight } let row = form[indexPath.section][indexPath.row] return row.baseCell.height?() ?? tableView.estimatedRowHeight } open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return form[section].header?.viewForSection(form[section], type: .header) } open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return form[section].footer?.viewForSection(form[section], type:.footer) } open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let height = form[section].header?.height { return height() } guard let view = form[section].header?.viewForSection(form[section], type: .header) else { return UITableViewAutomaticDimension } guard view.bounds.height != 0 else { return UITableViewAutomaticDimension } return view.bounds.height } open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if let height = form[section].footer?.height { return height() } guard let view = form[section].footer?.viewForSection(form[section], type: .footer) else { return UITableViewAutomaticDimension } guard view.bounds.height != 0 else { return UITableViewAutomaticDimension } return view.bounds.height } open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { guard let section = form[indexPath.section] as? MultivaluedSection else { return false } let row = form[indexPath] guard !row.isDisabled else { return false } guard !(indexPath.row == section.count - 1 && section.multivaluedOptions.contains(.Insert) && section.showInsertIconInAddButton) else { return true } if indexPath.row > 0 && section[indexPath.row - 1] is BaseInlineRowType && section[indexPath.row - 1]._inlineRow != nil { return false } return true } public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let row = form[indexPath] var section = row.section! if let _ = row.baseCell.findFirstResponder() { tableView.endEditing(true) } section.remove(at: indexPath.row) DispatchQueue.main.async { tableView.isEditing = !tableView.isEditing tableView.isEditing = !tableView.isEditing } } else if editingStyle == .insert { guard var section = form[indexPath.section] as? MultivaluedSection else { return } guard let multivaluedRowToInsertAt = section.multivaluedRowToInsertAt else { fatalError("Multivalued section multivaluedRowToInsertAt property must be set up") } let newRow = multivaluedRowToInsertAt(max(0, section.count - 1)) section.insert(newRow, at: section.count - 1) DispatchQueue.main.async { tableView.isEditing = !tableView.isEditing tableView.isEditing = !tableView.isEditing } tableView.scrollToRow(at: IndexPath(row: section.count - 1, section: indexPath.section), at: .bottom, animated: true) if newRow.baseCell.cellCanBecomeFirstResponder() { newRow.baseCell.cellBecomeFirstResponder() } else if let inlineRow = newRow as? BaseInlineRowType { inlineRow.expandInlineRow() } } } public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { guard let section = form[indexPath.section] as? MultivaluedSection, section.multivaluedOptions.contains(.Reorder) && section.count > 1 else { return false } if section.multivaluedOptions.contains(.Insert) && (section.count <= 2 || indexPath.row == (section.count - 1)) { return false } if indexPath.row > 0 && section[indexPath.row - 1] is BaseInlineRowType && section[indexPath.row - 1]._inlineRow != nil { return false } return true } public func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath { guard let section = form[sourceIndexPath.section] as? MultivaluedSection else { return sourceIndexPath } guard sourceIndexPath.section == proposedDestinationIndexPath.section else { return sourceIndexPath } let destRow = form[proposedDestinationIndexPath] if destRow is BaseInlineRowType && destRow._inlineRow != nil { return IndexPath(row: proposedDestinationIndexPath.row + (sourceIndexPath.row < proposedDestinationIndexPath.row ? 1 : -1), section:sourceIndexPath.section) } if proposedDestinationIndexPath.row > 0 { let previousRow = form[IndexPath(row: proposedDestinationIndexPath.row - 1, section: proposedDestinationIndexPath.section)] if previousRow is BaseInlineRowType && previousRow._inlineRow != nil { return IndexPath(row: proposedDestinationIndexPath.row + (sourceIndexPath.row < proposedDestinationIndexPath.row ? 1 : -1), section:sourceIndexPath.section) } } if section.multivaluedOptions.contains(.Insert) && proposedDestinationIndexPath.row == section.count - 1 { return IndexPath(row: section.count - 2, section: sourceIndexPath.section) } return proposedDestinationIndexPath } public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { guard var section = form[sourceIndexPath.section] as? MultivaluedSection else { return } if sourceIndexPath.row < section.count && destinationIndexPath.row < section.count && sourceIndexPath.row != destinationIndexPath.row { let sourceRow = form[sourceIndexPath] animateTableView = false section.remove(at: sourceIndexPath.row) section.insert(sourceRow, at: destinationIndexPath.row) animateTableView = true // update the accessory view let _ = inputAccessoryView(for: sourceRow) } } public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { guard let section = form[indexPath.section] as? MultivaluedSection else { return .none } if section.multivaluedOptions.contains(.Insert) && indexPath.row == section.count - 1 { return .insert } if section.multivaluedOptions.contains(.Delete) { return .delete } return .none } public func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return self.tableView(tableView, editingStyleForRowAt: indexPath) != .none } } extension FormViewController : UITableViewDataSource { // MARK: UITableViewDataSource open func numberOfSections(in tableView: UITableView) -> Int { return form.count } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return form[section].count } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { form[indexPath].updateCell() return form[indexPath].baseCell } open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return form[section].header?.title } open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return form[section].footer?.title } } extension FormViewController: FormDelegate { // MARK: FormDelegate open func sectionsHaveBeenAdded(_ sections: [Section], at indexes: IndexSet) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.insertSections(indexes, with: insertAnimation(forSections: sections)) tableView?.endUpdates() } open func sectionsHaveBeenRemoved(_ sections: [Section], at indexes: IndexSet) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.deleteSections(indexes, with: deleteAnimation(forSections: sections)) tableView?.endUpdates() } open func sectionsHaveBeenReplaced(oldSections: [Section], newSections: [Section], at indexes: IndexSet) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.reloadSections(indexes, with: reloadAnimation(oldSections: oldSections, newSections: newSections)) tableView?.endUpdates() } open func rowsHaveBeenAdded(_ rows: [BaseRow], at indexes: [IndexPath]) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.insertRows(at: indexes, with: insertAnimation(forRows: rows)) tableView?.endUpdates() } open func rowsHaveBeenRemoved(_ rows: [BaseRow], at indexes: [IndexPath]) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.deleteRows(at: indexes, with: deleteAnimation(forRows: rows)) tableView?.endUpdates() } open func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at indexes: [IndexPath]) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.reloadRows(at: indexes, with: reloadAnimation(oldRows: oldRows, newRows: newRows)) tableView?.endUpdates() } } extension FormViewController : UIScrollViewDelegate { // MARK: UIScrollViewDelegate open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { guard let tableView = tableView, scrollView === tableView else { return } tableView.endEditing(true) } } extension FormViewController { // MARK: KeyBoard Notifications /** Called when the keyboard will appear. Adjusts insets of the tableView and scrolls it if necessary. */ open func keyboardWillShow(_ notification: Notification) { guard let table = tableView, let cell = table.findFirstResponder()?.formCell() else { return } let keyBoardInfo = notification.userInfo! let endFrame = keyBoardInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue let keyBoardFrame = table.window!.convert(endFrame.cgRectValue, to: table.superview) let newBottomInset = table.frame.origin.y + table.frame.size.height - keyBoardFrame.origin.y + rowKeyboardSpacing var tableInsets = table.contentInset var scrollIndicatorInsets = table.scrollIndicatorInsets oldBottomInset = oldBottomInset ?? tableInsets.bottom if newBottomInset > oldBottomInset! { tableInsets.bottom = newBottomInset scrollIndicatorInsets.bottom = tableInsets.bottom UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration((keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double)) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: (keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey] as! Int))!) table.contentInset = tableInsets table.scrollIndicatorInsets = scrollIndicatorInsets if let selectedRow = table.indexPath(for: cell) { table.scrollToRow(at: selectedRow, at: .none, animated: animateScroll) } UIView.commitAnimations() } } /** Called when the keyboard will disappear. Adjusts insets of the tableView. */ open func keyboardWillHide(_ notification: Notification) { guard let table = tableView, let oldBottom = oldBottomInset else { return } let keyBoardInfo = notification.userInfo! var tableInsets = table.contentInset var scrollIndicatorInsets = table.scrollIndicatorInsets tableInsets.bottom = oldBottom scrollIndicatorInsets.bottom = tableInsets.bottom oldBottomInset = nil UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration((keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double)) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: (keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey] as! Int))!) table.contentInset = tableInsets table.scrollIndicatorInsets = scrollIndicatorInsets UIView.commitAnimations() } } public enum Direction { case up, down } extension FormViewController { // MARK: Navigation Methods func navigationDone(_ sender: UIBarButtonItem) { tableView?.endEditing(true) } func navigationAction(_ sender: UIBarButtonItem) { navigateTo(direction: sender == navigationAccessoryView.previousButton ? .up : .down) } public func navigateTo(direction: Direction) { guard let currentCell = tableView?.findFirstResponder()?.formCell() else { return } guard let currentIndexPath = tableView?.indexPath(for: currentCell) else { assertionFailure(); return } guard let nextRow = nextRow(for: form[currentIndexPath], withDirection: direction) else { return } if nextRow.baseCell.cellCanBecomeFirstResponder() { tableView?.scrollToRow(at: nextRow.indexPath!, at: .none, animated: animateScroll) nextRow.baseCell.cellBecomeFirstResponder(withDirection: direction) } } func nextRow(for currentRow: BaseRow, withDirection direction: Direction) -> BaseRow? { let options = navigationOptions ?? Form.defaultNavigationOptions guard options.contains(.Enabled) else { return nil } guard let next = direction == .down ? form.nextRow(for: currentRow) : form.previousRow(for: currentRow) else { return nil } if next.isDisabled && options.contains(.StopDisabledRow) { return nil } if !next.baseCell.cellCanBecomeFirstResponder() && !next.isDisabled && !options.contains(.SkipCanNotBecomeFirstResponderRow) { return nil } if !next.isDisabled && next.baseCell.cellCanBecomeFirstResponder() { return next } return nextRow(for: next, withDirection:direction) } } extension FormViewControllerProtocol { // MARK: Helpers func makeRowVisible(_ row: BaseRow) { guard let cell = row.baseCell, let indexPath = row.indexPath, let tableView = tableView else { return } if cell.window == nil || (tableView.contentOffset.y + tableView.frame.size.height <= cell.frame.origin.y + cell.frame.size.height) { tableView.scrollToRow(at: indexPath, at: .bottom, animated: true) } } }
mit
2057453a55823298178b367866abc8f5
39.189036
187
0.670414
5.244203
false
false
false
false
invoy/CoreDataQueryInterface
CoreDataQueryInterface/Miscellanea.swift
1
1525
// // Subquery.swift // CoreDataQueryInterface // // Created by Gregory Higley on 9/25/16. // Copyright © 2016 Prosumma LLC. All rights reserved. // import CoreData import Foundation public func alias(_ expression: ExpressionConvertible, name: String, type: NSAttributeType) -> PropertyConvertible { let property = NSExpressionDescription() property.expression = expression.cdqiExpression property.name = name property.expressionResultType = type return property } public func alias(_ expression: ExpressionConvertible, name: String) -> PropertyConvertible { var type: NSAttributeType = .undefinedAttributeType if let typed = expression as? Typed { type = typed.cdqiType } return alias(expression, name: name, type: type) } public func alias(_ expression: KeyPathExpressionConvertible, type: NSAttributeType) -> PropertyConvertible { return alias(expression, name: expression.cdqiName, type: type) } public func subquery<E: EntityAttribute>(_ items: E, _ query: (E) -> NSPredicate) -> ExpressionConvertible { let uuid = NSUUID().uuidString let index = uuid.index(uuid.startIndex, offsetBy: 6) let randomString = uuid[..<index] let variable = "v\(randomString)" return NSExpression(forSubquery: items.cdqiExpression, usingIteratorVariable: variable, predicate: query(E(variable: variable))) } public func subqueryCount<E: EntityAttribute>(_ items: E, _ query: (E) -> NSPredicate) -> FunctionExpression { return count(subquery(items, query)) }
mit
e449b083ec66910eb0ddb29b36996f77
35.285714
132
0.731627
4.37931
false
false
false
false
tuannme/Up
Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationOrbit.swift
2
7828
// // NVActivityIndicatorAnimationOrbit.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class NVActivityIndicatorAnimationOrbit: NVActivityIndicatorAnimationDelegate { let duration: CFTimeInterval = 1.9 let satelliteCoreRatio: CGFloat = 0.25 let distanceRatio:CGFloat = 1.5 // distance / core size var coreSize: CGFloat = 0 var satelliteSize: CGFloat = 0 func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { coreSize = size.width / (1 + satelliteCoreRatio + distanceRatio) satelliteSize = coreSize * satelliteCoreRatio ring1InLayer(layer, size: size, color: color) ring2InLayer(layer, size: size, color: color) coreInLayer(layer, size: size, color: color) satelliteInLayer(layer, size: size, color: color) } func ring1InLayer(_ layer: CALayer, size: CGSize, color: UIColor) { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.45, 0.45, 1] scaleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) scaleAnimation.values = [0, 0, 1.3, 2] scaleAnimation.duration = duration // Opacity animation let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") let timingFunction = CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1) opacityAnimation.keyTimes = [0, 0.45, 1] scaleAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear), timingFunction] opacityAnimation.values = [0.8, 0.8, 0] opacityAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: coreSize, height: coreSize), color: color) let frame = CGRect(x: (layer.bounds.size.width - coreSize) / 2, y: (layer.bounds.size.height - coreSize) / 2, width: coreSize, height: coreSize) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } func ring2InLayer(_ layer: CALayer, size: CGSize, color: UIColor) { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.55, 0.55, 1] scaleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) scaleAnimation.values = [0, 0, 1.3, 2.1] scaleAnimation.duration = duration // Opacity animation let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") let timingFunction = CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1) opacityAnimation.keyTimes = [0, 0.55, 0.65, 1] scaleAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear), timingFunction] opacityAnimation.values = [0.7, 0.7, 0, 0] opacityAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: coreSize, height: coreSize), color: color) let frame = CGRect(x: (layer.bounds.size.width - coreSize) / 2, y: (layer.bounds.size.height - coreSize) / 2, width: coreSize, height: coreSize) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } func coreInLayer(_ layer: CALayer, size: CGSize, color: UIColor) { let inTimingFunction = CAMediaTimingFunction(controlPoints: 0.7, 0, 1, 0.5) let outTimingFunction = CAMediaTimingFunction(controlPoints: 0, 0.7, 0.5, 1) let standByTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.45, 0.55, 1] scaleAnimation.timingFunctions = [inTimingFunction, standByTimingFunction, outTimingFunction]; scaleAnimation.values = [1, 1.3, 1.3, 1] scaleAnimation.duration = duration scaleAnimation.repeatCount = HUGE scaleAnimation.isRemovedOnCompletion = false // Draw circle let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: coreSize, height: coreSize), color: color) let frame = CGRect(x: (layer.bounds.size.width - coreSize) / 2, y: (layer.bounds.size.height - coreSize) / 2, width: coreSize, height: coreSize) circle.frame = frame circle.add(scaleAnimation, forKey: "animation") layer.addSublayer(circle) } func satelliteInLayer(_ layer: CALayer, size: CGSize, color: UIColor) { // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath: "position") rotateAnimation.path = UIBezierPath(arcCenter: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY), radius: (size.width - satelliteSize) / 2, startAngle: CGFloat(M_PI) * 1.5, endAngle: CGFloat(M_PI) * 1.5 + 4 * CGFloat(M_PI), clockwise: true).cgPath rotateAnimation.duration = duration * 2 rotateAnimation.repeatCount = HUGE rotateAnimation.isRemovedOnCompletion = false // Draw circle let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: satelliteSize, height: satelliteSize), color: color) let frame = CGRect(x: 0, y: 0, width: satelliteSize, height: satelliteSize) circle.frame = frame circle.add(rotateAnimation, forKey: "animation") layer.addSublayer(circle) } }
mit
706214d3bb078b5bfb4de8af15e45126
44.511628
135
0.64231
4.970159
false
false
false
false
CosmicMind/Material
Sources/iOS/Button/IconButton.swift
3
1945
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit public enum IconButtonThemingStyle { /// Theming when background content is in background color. case onBackground /// Theming when background content is in primary color. case onPrimary } open class IconButton: Button { /// A reference to IconButtonThemingStyle. open var themingStyle = IconButtonThemingStyle.onBackground open override func prepare() { super.prepare() pulseAnimation = .center } open override func apply(theme: Theme) { super.apply(theme: theme) switch themingStyle { case .onBackground: tintColor = theme.secondary pulseColor = theme.secondary case .onPrimary: tintColor = theme.onPrimary pulseColor = theme.onPrimary } } }
mit
322f21325ac6869fe02574fdc1b092ea
33.122807
80
0.732648
4.512761
false
false
false
false
CAHjbao/JContainerViewController
Pods/ImagePicker/Source/BottomView/ImageStack.swift
3
1072
import UIKit import Photos open class ImageStack { public struct Notifications { public static let imageDidPush = "imageDidPush" public static let imageDidDrop = "imageDidDrop" public static let stackDidReload = "stackDidReload" } open var assets = [PHAsset]() fileprivate let imageKey = "image" open func pushAsset(_ asset: PHAsset) { assets.append(asset) NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.imageDidPush), object: self, userInfo: [imageKey: asset]) } open func dropAsset(_ asset: PHAsset) { assets = assets.filter() {$0 != asset} NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.imageDidDrop), object: self, userInfo: [imageKey: asset]) } open func resetAssets(_ assetsArray: [PHAsset]) { assets = assetsArray NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.stackDidReload), object: self, userInfo: nil) } open func containsAsset(_ asset: PHAsset) -> Bool { return assets.contains(asset) } }
mit
70e748082f5498e32c55e9cf5e677177
31.484848
141
0.728545
4.1875
false
false
false
false
momotofu/UI-Color-Picker---Swift
ColorPicker/Shape.swift
1
4380
// // Nib.swift // ColorPicker // // Created by Christopher REECE on 2/4/15. // Copyright (c) 2015 Christopher Reece. All rights reserved. // import UIKit // Equatable protocol func ==(lhs: Shape, rhs: Shape) -> Bool { return lhs == rhs } class Shape: UIView, Equatable { private var _rotation: CGFloat = 0.0 private var _multiplier: CGFloat = 1 private var _state: HSBA = .hue var shapeState: HSBA { get { return _state } set { _state = newValue } } var rotation: CGFloat { get { return _rotation } set { _rotation = newValue + (2 * CGFloat(M_PI) * 0.248) } } var nibCenter: CGPoint = CGPointMake(0, 0) var color: UIColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 0.9) private var _shape: Shapes = Shapes.circle override func drawRect(rect: CGRect) { let context: CGContext = UIGraphicsGetCurrentContext() let width = min(bounds.size.width, bounds.size.height) * 0.6 switch _shape { case .circle: let nib = UIBezierPath(arcCenter: nibCenter, radius: CGFloat(min(bounds.width, bounds.height) * _multiplier) / 2, startAngle: 0.0, endAngle: CGFloat(M_PI) * 2, clockwise: false) color.setFill() nib.fill() case .triangle: CGContextTranslateCTM(context, bounds.midX, bounds.midY) ; println("width: \(width)") CGContextRotateCTM(context, rotation) CGContextMoveToPoint(context, 0, (width / 2) * -1) CGContextAddLineToPoint(context, width / 2, width / 2) CGContextAddLineToPoint(context, (width / 2) * -1, width / 2) CGContextClosePath(context) CGContextSetFillColorWithColor(context, color.CGColor) CGContextDrawPath(context, kCGPathFill) case .square: let nib = UIBezierPath(arcCenter: nibCenter, radius: CGFloat(min(bounds.width, bounds.height)) / 2, startAngle: 0.0, endAngle: CGFloat(M_PI) * 2, clockwise: false) color.setFill() nib.fill() case .pentagon: let nib = UIBezierPath(arcCenter: nibCenter, radius: CGFloat(min(bounds.width, bounds.height)) / 2, startAngle: 0.0, endAngle: CGFloat(M_PI) * 2, clockwise: false) color.setFill() nib.fill() case .hexagon: let nib = UIBezierPath(arcCenter: nibCenter, radius: CGFloat(min(bounds.width, bounds.height)) / 2, startAngle: 0.0, endAngle: CGFloat(M_PI) * 2, clockwise: false) color.setFill() nib.fill() default: let nib = UIBezierPath(arcCenter: nibCenter, radius: CGFloat(min(bounds.width, bounds.height)) / 2, startAngle: 0.0, endAngle: CGFloat(M_PI) * 2, clockwise: false) color.setFill() nib.fill() } } init(frame: CGRect, setColor: UIColor?, shape: Shapes) { super.init(frame: frame) _shape = shape if setColor != nil { color = setColor! } self.backgroundColor = UIColor.clearColor() nibCenter = CGPointMake(bounds.midX, bounds.midY) } init(frame: CGRect, setColor: UIColor?, shape: Shapes, multiplier: CGFloat) { super.init(frame: frame) _multiplier = multiplier _shape = shape if setColor != nil { color = setColor! } self.backgroundColor = UIColor.clearColor() nibCenter = CGPointMake(bounds.midX, bounds.midY) } init(frame: CGRect, setColor: UIColor?, shape: Shapes, multiplier: CGFloat, state: HSBA) { super.init(frame: frame) _state = state _multiplier = multiplier _shape = shape if setColor != nil { color = setColor! } self.backgroundColor = UIColor.clearColor() nibCenter = CGPointMake(bounds.midX, bounds.midY) } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() nibCenter = CGPointMake(bounds.midX, bounds.midY) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
cc0-1.0
08b40081d0a40eb31a29b4386812e1b7
31.205882
189
0.575342
4.281525
false
false
false
false
qualaroo/QualarooSDKiOS
Qualaroo/Extensions/Bundle.swift
1
1330
// // Bundle.swift // Qualaroo // // 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 extension Bundle { /// Convenience way to get Qualaroo bundle. /// /// - Returns: Bundle used internally by Qualaroo Framework. static func qualaroo() -> Bundle? { let bundle = Bundle(for: Qualaroo.self) if (containsQualarooResources(bundle)) { Qualaroo.log("Using Qualaroo.self bundle") return bundle } guard let url = bundle.resourceURL else { Qualaroo.log("Qualaroo.self bundle resourceUrl is nil.") return nil } let qualarooBundleUrl = url.appendingPathComponent("Qualaroo.bundle") let qualarooBundle = Bundle(url: qualarooBundleUrl) if (!containsQualarooResources(qualarooBundle)) { Qualaroo.log("Qualaroo.bundle does not exist or does not contain Qualaroo resources. Main path: \(url)") } return qualarooBundle } private static func containsQualarooResources(_ bundle: Bundle?) -> Bool { guard let bundle = bundle else { return false } let path = bundle.path(forResource: "AnswerBinaryView", ofType: "nib") return path != nil } }
mit
f7fc0fdea385bf39543f241a70b5e7ac
30.666667
112
0.674436
3.958333
false
false
false
false
ihomway/RayWenderlichCourses
Advanced Swift 3/Advanced Swift 3.playground/Pages/Protocols and Generics.xcplaygroundpage/Contents.swift
1
2350
//: [Previous](@previous) import Foundation import CoreGraphics var str = "Hello, playground" protocol Stackable: class { associatedtype Element: Comparable func push(_ element: Element) func pop() -> Element? } class Stack<Element: Comparable>: Stackable { private var storage: [Element] = [] func push(_ element: Element) { storage.append(element) } func pop() -> Element? { return storage.popLast() } } func pushToAll<S: Stackable>(stacks: [S], value: S.Element) { stacks.forEach{ $0.push(value)} } var stack1 = Stack<Int>() stack1.push(13) stack1.push(3) stack1.pop() var stack2 = Stack<Int>() dump(stack1) dump(stack2) //MARK: protocol Shape { func isEqual(to other: Shape) -> Bool } extension Shape where Self: Equatable { func isEqual(to other: Shape) -> Bool { if let other = other as? Self { return self == other } return false } } struct Circle: Shape, Equatable { let center: CGPoint let radius: CGFloat static func ==(lhs: Circle, rhs: Circle) -> Bool { return lhs.center == rhs.center && lhs.radius == rhs.radius } } struct Square: Shape, Equatable { let origin: CGPoint let size: CGFloat static func ==(lhs: Square, rhs: Square) -> Bool { return lhs.origin == rhs.origin && lhs.size == rhs.size } } struct Diagram: Equatable { var shapes: [Shape] static func ==(lhs: Diagram, rhs: Diagram) -> Bool { return lhs.shapes.count == rhs.shapes.count && !zip(lhs.shapes, rhs.shapes).contains{ let (shape1, shape2) = $0 // if return `true`, the `contains` function will be terminated immediately and return ture, // so we don't chech if two elements is equal, instead we check if they are unequal // if two elements is unequal, we should terminate the function, and it will return a `true`, // so there is a `!` outside // if two elements is equal, we continue to compare next pair of elements until // there is no more elements, and it will return a `false`, with the `!` outside, it will be a `ture` return !shape1.isEqual(to: shape2) } } } let diagram1 = Diagram(shapes: [Circle(center: .zero, radius: 10), Square(origin: .zero, size: 10)]) let diagram2 = Diagram(shapes: [Circle(center: .zero, radius: 10), Square(origin: .zero, size: 10)]) diagram1 == diagram2 diagram2 == diagram1 diagram1 != diagram2 //: [Next](@next)
mit
721a17b631d8c73a769fc6f0af23c585
20.171171
104
0.67234
3.245856
false
false
false
false
evgenyneu/Auk
AukTests/AukTests.swift
1
11471
import XCTest import moa @testable import Auk class AukTests: XCTestCase { var scrollView: UIScrollView! var auk: Auk! var fakeAnimator: iiFakeAnimator! override func setUp() { super.setUp() scrollView = UIScrollView() // Set scroll view size let size = CGSize(width: 120, height: 90) scrollView.bounds = CGRect(origin: CGPoint(), size: size) auk = Auk(scrollView: scrollView) // Use fake animator fakeAnimator = iiFakeAnimator() iiAnimator.currentAnimator = fakeAnimator } override func tearDown() { super.tearDown() iiAnimator.currentAnimator = nil // Remove the fake animator } // MARK: - Setup func testSetup_style() { auk = Auk(scrollView: scrollView) auk.setup() XCTAssertFalse(scrollView.showsHorizontalScrollIndicator) XCTAssert(scrollView.isPagingEnabled) } // MARK: Page indicator func testSetup_createPageIndicator() { // Layout scroll view // --------------- let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) scrollView.translatesAutoresizingMaskIntoConstraints = false superview.addSubview(scrollView) iiAutolayoutConstraints.height(scrollView, value: 100) iiAutolayoutConstraints.width(scrollView, value: 100) iiAutolayoutConstraints.alignSameAttributes(scrollView, toItem: superview, constraintContainer: superview, attribute: NSLayoutConstraint.Attribute.left, margin: 0) iiAutolayoutConstraints.alignSameAttributes(scrollView, toItem: superview, constraintContainer: superview, attribute: NSLayoutConstraint.Attribute.top, margin: 0) auk = Auk(scrollView: scrollView) // Setup the auk which will create the page view // --------------- auk.settings.pageControl.marginToScrollViewBottom = 11 auk.setup() superview.layoutIfNeeded() // Check the page indicator layout // ----------- XCTAssertEqual(89, auk.pageIndicatorContainer!.frame.maxY) } func testSetup_doNotCreatePageIndicator() { // Layout scroll view // --------------- let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) scrollView.translatesAutoresizingMaskIntoConstraints = false superview.addSubview(scrollView) iiAutolayoutConstraints.height(scrollView, value: 100) iiAutolayoutConstraints.width(scrollView, value: 100) iiAutolayoutConstraints.alignSameAttributes(scrollView, toItem: superview, constraintContainer: superview, attribute: NSLayoutConstraint.Attribute.left, margin: 0) iiAutolayoutConstraints.alignSameAttributes(scrollView, toItem: superview, constraintContainer: superview, attribute: NSLayoutConstraint.Attribute.top, margin: 0) auk = Auk(scrollView: scrollView) // Setup the auk which will create the page view // --------------- auk.settings.pageControl.visible = false auk.setup() superview.layoutIfNeeded() // Check the page indicator layout // ----------- XCTAssert(auk.pageIndicatorContainer == nil) } func testSetup_createSinglePageIndicator() { // Layout scroll view // --------------- let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) auk = Auk(scrollView: scrollView) // Call setup multiple times // --------------- auk.setup() auk.setup() auk.setup() // Verify that only one page indicator container has been created // --------------- let indicators = superview.subviews.filter { $0 as? AukPageIndicatorContainer != nil } XCTAssertEqual(1, indicators.count) } // MARK: - Update page indicator func testPageIndicator_updateCurrentPage_updateNumberOfPages() { // Layout scroll view // --------------- let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) // Show 3 images // ------------- let image = createImage96px() auk.show(image: image) auk.show(image: image) auk.show(image: image) // Verify page indicator is showing three pages // ------------- XCTAssertEqual(3, auk.pageIndicatorContainer!.pageControl!.numberOfPages) } func testPageIndicator_updateCurrentPage() { // Layout scroll view // --------------- let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) // Show 3 images // ------------- let image = createImage96px() auk.show(image: image) auk.show(image: image) auk.show(image: image) // Scroll to the first page // ------------ scrollView.contentOffset.x = 0 scrollView.delegate?.scrollViewDidScroll?(scrollView) XCTAssertEqual(0, auk.pageIndicatorContainer!.pageControl!.currentPage) // Scroll to the second page // ------------- scrollView.contentOffset.x = 120 scrollView.delegate?.scrollViewDidScroll?(scrollView) XCTAssertEqual(1, auk.pageIndicatorContainer!.pageControl!.currentPage) } // MARK: - Show / hide page indicator func testPageIndicator_showForTwoPages() { // Layout scroll view // --------------- let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) let image = createImage96px() auk.show(image: image) auk.show(image: image) XCTAssertFalse(auk.pageIndicatorContainer!.isHidden) } func testPageIndicator_hideWhenPagesRemoved() { // Layout scroll view // --------------- let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) let image = createImage96px() auk.show(image: image) auk.show(image: image) auk.removeAll() XCTAssert(auk.pageIndicatorContainer!.isHidden) } func testPageIndicator_scrollWhenPageIndicatorIsTapped() { let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) let image = createImage96px() auk.show(image: image) auk.show(image: image) auk.pageIndicatorContainer!.pageControl!.currentPage = 1 auk.pageIndicatorContainer?.didTapPageControl(auk.pageIndicatorContainer!.pageControl!) XCTAssertEqual(120, scrollView.contentOffset.x) } // MARK: - updatePageIndicator func testUpdateTestIndicator() { let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) let aukView1 = AukPage() let aukView2 = AukPage() scrollView.addSubview(aukView1) scrollView.addSubview(aukView2) // Create page indicator // --------------- let pageIndicator = AukPageIndicatorContainer() auk.pageIndicatorContainer = pageIndicator superview.addSubview(pageIndicator) pageIndicator.setup(auk.settings, scrollView: scrollView) superview.layoutIfNeeded() // Update page indicator // ------------- XCTAssertEqual(0, auk.pageIndicatorContainer!.pageControl!.numberOfPages) XCTAssertEqual(-1, auk.pageIndicatorContainer!.pageControl!.currentPage) auk.updatePageIndicator() XCTAssertEqual(2, auk.pageIndicatorContainer!.pageControl!.numberOfPages) XCTAssertEqual(0, auk.pageIndicatorContainer!.pageControl!.currentPage) scrollView.contentOffset = CGPoint(x: 200, y: 0) XCTAssertEqual(1, auk.pageIndicatorContainer!.pageControl!.currentPage) auk.updatePageIndicator() } // MARK: - removePage func testRemovePage() { let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) let aukView1 = AukPage() let aukView2 = AukPage() scrollView.addSubview(aukView1) scrollView.addSubview(aukView2) auk.createPageIndicator() superview.layoutIfNeeded() scrollView.contentOffset = CGPoint(x: 200, y: 0) auk.updatePageIndicator() XCTAssertEqual(2, auk.pageIndicatorContainer!.pageControl!.numberOfPages) XCTAssertEqual(1, auk.pageIndicatorContainer!.pageControl!.currentPage) // Remove page // ------------- auk.removePage(page: aukView2, animated: false) // Page is removed XCTAssertNil(aukView2.superview) // Page indicator is updated XCTAssertEqual(1, auk.pageIndicatorContainer!.pageControl!.numberOfPages) XCTAssertEqual(0, auk.pageIndicatorContainer!.pageControl!.currentPage) } func testRemovePage_callCompletion() { let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) let aukView1 = AukPage() let aukView2 = AukPage() scrollView.addSubview(aukView1) scrollView.addSubview(aukView2) superview.layoutIfNeeded() // Remove page // ------------- var didCallCompletion = false auk.removePage(page: aukView2, animated: false, completion: { didCallCompletion = true }) XCTAssert(didCallCompletion) } func testRemovePage_notifyPagesAboutTheirVisibitliy() { let simulate = MoaSimulator.simulate("site.com") let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) auk.show(url: "http://site.com/one.jpg") auk.show(url: "http://site.com/two.jpg") // Dowload the first page initially XCTAssertEqual(1, simulate.downloaders.count) XCTAssertEqual("http://site.com/one.jpg", simulate.downloaders[0].url) // Remove first page // ------------- let page = aukPage(scrollView, pageIndex: 0)! auk.removePage(page: page, animated: false) // Dowload the second page XCTAssertEqual(2, simulate.downloaders.count) XCTAssertEqual("http://site.com/two.jpg", simulate.downloaders[1].url) } func testRemovePage_animated() { let superview = UIView(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 300))) superview.addSubview(scrollView) let aukView1 = AukPage() let aukView2 = AukPage() scrollView.addSubview(aukView1) scrollView.addSubview(aukView2) auk.createPageIndicator() superview.layoutIfNeeded() scrollView.contentOffset = CGPoint(x: 200, y: 0) auk.updatePageIndicator() XCTAssertEqual(2, auk.pageIndicatorContainer!.pageControl!.numberOfPages) XCTAssertEqual(1, auk.pageIndicatorContainer!.pageControl!.currentPage) // Remove page // ------------- auk.removePage(page: aukView2, animated: true) // Check the animation XCTAssertEqual(1, fakeAnimator.testParameters.count) XCTAssertEqual(0.3, fakeAnimator.testParameters[0].duration) // Default layout animation duration } }
mit
c7a9bde48921bf92d5d55365d32897fb
29.107612
136
0.655479
4.617955
false
true
false
false
zhangchn/swelly
swelly/EffectView.swift
1
2397
// // EffectView.swift // swelly // // Created by ZhangChen on 16/02/2017. // // import Cocoa import QuartzCore.CoreAnimation public var DEFAULT_POPUP_BOX_FONT: String { return "Helvetica" } public var DEFAULT_POPUP_MENU_FONT: String { return "Lucida Grande" } class WLEffectView : NSView { @IBOutlet var mainView: TermView! lazy var mainLayer: CALayer = { let layer = CALayer() // Make the background color to be a dark gray with a 50% alpha similar to // the real Dashbaord. let bgColor = NSColor.black.cgColor layer.backgroundColor = bgColor return layer }() var ipAddrLayer: CALayer! var clickEntryLayer: CALayer! var popUpLayer: CALayer! var buttonLayer: CALayer! var urlLineLayer: CALayer! var urlIndicatorImage: CGImage! var selectedItemIndex: Int! var popUpLayerTextColor: CGColor! var popUpLayerTextFont: CGFont! /* */ required init?(coder: NSCoder) { super.init(coder: coder) wantsLayer = true } init(view: NSView) { super.init(frame: view.frame) wantsLayer = true } deinit { buttonLayer.removeFromSuperlayer() } override func awakeFromNib() { setupLayer() } // for ip seeker func drawIPAddrBox(_ rect: NSRect) { } func clearIPAddrBox() { } // for post view func drawClickEntry(_ rect: NSRect) { } func clearClickEntry() { } // for button func drawButton(_ rect: NSRect, withMessage message: String!) { } func clearButton() { } // for URL func showIndicator(at point: NSPoint) { } func removeIndicator() { } // To show pop up message by core animation // This method might be changed in future // by gtCarrera @ 9# func drawPopUpMessage(_ message: String!) { } func removePopUpMessage() { } func resize() { setFrameSize(mainView.frame.size) setFrameOrigin(.zero) } func clear() { clearIPAddrBox() clearClickEntry() clearButton() } func setupLayer() { frame = mainView.frame mainLayer.frame = frame } }
gpl-2.0
af98197f1548d474f6328fc23225488a
18.330645
82
0.560284
4.505639
false
false
false
false
johnno1962b/swift-corelibs-foundation
Foundation/NSRegularExpression.swift
5
21580
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /* NSRegularExpression is a class used to represent and apply regular expressions. An instance of this class is an immutable representation of a compiled regular expression pattern and various option flags. */ import CoreFoundation extension NSRegularExpression { public struct Options : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let caseInsensitive = Options(rawValue: 1 << 0) /* Match letters in the pattern independent of case. */ public static let allowCommentsAndWhitespace = Options(rawValue: 1 << 1) /* Ignore whitespace and #-prefixed comments in the pattern. */ public static let ignoreMetacharacters = Options(rawValue: 1 << 2) /* Treat the entire pattern as a literal string. */ public static let dotMatchesLineSeparators = Options(rawValue: 1 << 3) /* Allow . to match any character, including line separators. */ public static let anchorsMatchLines = Options(rawValue: 1 << 4) /* Allow ^ and $ to match the start and end of lines. */ public static let useUnixLineSeparators = Options(rawValue: 1 << 5) /* Treat only \n as a line separator (otherwise, all standard line separators are used). */ public static let useUnicodeWordBoundaries = Options(rawValue: 1 << 6) /* Use Unicode TR#29 to specify word boundaries (otherwise, traditional regular expression word boundaries are used). */ } } open class NSRegularExpression: NSObject, NSCopying, NSCoding { internal var _internal: _CFRegularExpression open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.pattern._nsObject, forKey: "NSPattern") aCoder.encode(self.options.rawValue._bridgeToObjectiveC(), forKey: "NSOptions") } public required convenience init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let pattern = aDecoder.decodeObject(forKey: "NSPattern") as? NSString, let options = aDecoder.decodeObject(forKey: "NSOptions") as? NSNumber else { return nil } do { try self.init(pattern: pattern._swiftObject, options: Options(rawValue: options.uintValue)) } catch { return nil } } open override func isEqual(_ object: Any?) -> Bool { guard let other = object as? NSRegularExpression else { return false } return self === other || (self.pattern == other.pattern && self.options == other.options) } /* An instance of NSRegularExpression is created from a regular expression pattern and a set of options. If the pattern is invalid, nil will be returned and an NSError will be returned by reference. The pattern syntax currently supported is that specified by ICU. */ public init(pattern: String, options: Options = []) throws { var error: Unmanaged<CFError>? #if os(OSX) || os(iOS) let opt = _CFRegularExpressionOptions(rawValue: options.rawValue) #else let opt = _CFRegularExpressionOptions(options.rawValue) #endif if let regex = _CFRegularExpressionCreate(kCFAllocatorSystemDefault, pattern._cfObject, opt, &error) { _internal = regex } else { throw error!.takeRetainedValue() } } open var pattern: String { return _CFRegularExpressionGetPattern(_internal)._swiftObject } open var options: Options { #if os(OSX) || os(iOS) let opt = _CFRegularExpressionGetOptions(_internal).rawValue #else let opt = _CFRegularExpressionGetOptions(_internal) #endif return Options(rawValue: opt) } open var numberOfCaptureGroups: Int { return _CFRegularExpressionGetNumberOfCaptureGroups(_internal) } /* This class method will produce a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as pattern metacharacters. */ open class func escapedPattern(for string: String) -> String { return _CFRegularExpressionCreateEscapedPattern(string._cfObject)._swiftObject } } extension NSRegularExpression { public struct MatchingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let reportProgress = MatchingOptions(rawValue: 1 << 0) /* Call the block periodically during long-running match operations. */ public static let reportCompletion = MatchingOptions(rawValue: 1 << 1) /* Call the block once after the completion of any matching. */ public static let anchored = MatchingOptions(rawValue: 1 << 2) /* Limit matches to those at the start of the search range. */ public static let withTransparentBounds = MatchingOptions(rawValue: 1 << 3) /* Allow matching to look beyond the bounds of the search range. */ public static let withoutAnchoringBounds = MatchingOptions(rawValue: 1 << 4) /* Prevent ^ and $ from automatically matching the beginning and end of the search range. */ internal static let OmitResult = MatchingOptions(rawValue: 1 << 13) } public struct MatchingFlags : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let progress = MatchingFlags(rawValue: 1 << 0) /* Set when the block is called to report progress during a long-running match operation. */ public static let completed = MatchingFlags(rawValue: 1 << 1) /* Set when the block is called after completion of any matching. */ public static let hitEnd = MatchingFlags(rawValue: 1 << 2) /* Set when the current match operation reached the end of the search range. */ public static let requiredEnd = MatchingFlags(rawValue: 1 << 3) /* Set when the current match depended on the location of the end of the search range. */ public static let internalError = MatchingFlags(rawValue: 1 << 4) /* Set when matching failed due to an internal error. */ } } internal class _NSRegularExpressionMatcher { var regex: NSRegularExpression var block: (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void init(regex: NSRegularExpression, block: @escaping (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void) { self.regex = regex self.block = block } } internal func _NSRegularExpressionMatch(_ context: UnsafeMutableRawPointer?, ranges: UnsafeMutablePointer<CFRange>?, count: CFIndex, options: _CFRegularExpressionMatchingOptions, stop: UnsafeMutablePointer<_DarwinCompatibleBoolean>) -> Void { let matcher = unsafeBitCast(context, to: _NSRegularExpressionMatcher.self) if ranges == nil { #if os(OSX) || os(iOS) let opts = options.rawValue #else let opts = options #endif stop.withMemoryRebound(to: ObjCBool.self, capacity: 1, { matcher.block(nil, NSRegularExpression.MatchingFlags(rawValue: opts), $0) }) } else { let result = ranges!.withMemoryRebound(to: NSRange.self, capacity: count) { rangePtr in NSTextCheckingResult.regularExpressionCheckingResultWithRanges(rangePtr, count: count, regularExpression: matcher.regex) } #if os(OSX) || os(iOS) let flags = NSRegularExpression.MatchingFlags(rawValue: options.rawValue) #else let flags = NSRegularExpression.MatchingFlags(rawValue: options) #endif stop.withMemoryRebound(to: ObjCBool.self, capacity: 1, { matcher.block(result, flags, $0) }) } } extension NSRegularExpression { /* The fundamental matching method on NSRegularExpression is a block iterator. There are several additional convenience methods, for returning all matches at once, the number of matches, the first match, or the range of the first match. Each match is specified by an instance of NSTextCheckingResult (of type NSTextCheckingTypeRegularExpression) in which the overall match range is given by the range property (equivalent to range at:0) and any capture group ranges are given by range at: for indexes from 1 to numberOfCaptureGroups. {NSNotFound, 0} is used if a particular capture group does not participate in the match. */ public func enumerateMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange, using block: @escaping (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { let matcher = _NSRegularExpressionMatcher(regex: self, block: block) withExtendedLifetime(matcher) { (m: _NSRegularExpressionMatcher) -> Void in #if os(OSX) || os(iOS) let opts = _CFRegularExpressionMatchingOptions(rawValue: options.rawValue) #else let opts = _CFRegularExpressionMatchingOptions(options.rawValue) #endif _CFRegularExpressionEnumerateMatchesInString(_internal, string._cfObject, opts, CFRange(range), unsafeBitCast(matcher, to: UnsafeMutableRawPointer.self), _NSRegularExpressionMatch) } } public func matches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> [NSTextCheckingResult] { var matches = [NSTextCheckingResult]() enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in if let match = result { matches.append(match) } } return matches } public func numberOfMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> Int { var count = 0 enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion).union(.OmitResult), range: range) {_,_,_ in count += 1 } return count } public func firstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> NSTextCheckingResult? { var first: NSTextCheckingResult? enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in first = result stop.pointee = true } return first } public func rangeOfFirstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> NSRange { var firstRange = NSMakeRange(NSNotFound, 0) enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in if let match = result { firstRange = match.range } else { firstRange = NSMakeRange(0, 0) } stop.pointee = true } return firstRange } } /* By default, the block iterator method calls the block precisely once for each match, with a non-nil result and appropriate flags. The client may then stop the operation by setting the contents of stop to YES. If the NSMatchingReportProgress option is specified, the block will also be called periodically during long-running match operations, with nil result and NSMatchingProgress set in the flags, at which point the client may again stop the operation by setting the contents of stop to YES. If the NSMatchingReportCompletion option is specified, the block will be called once after matching is complete, with nil result and NSMatchingCompleted set in the flags, plus any additional relevant flags from among NSMatchingHitEnd, NSMatchingRequiredEnd, or NSMatchingInternalError. NSMatchingReportProgress and NSMatchingReportCompletion have no effect for methods other than the block iterator. NSMatchingHitEnd is set in the flags passed to the block if the current match operation reached the end of the search range. NSMatchingRequiredEnd is set in the flags passed to the block if the current match depended on the location of the end of the search range. NSMatchingInternalError is set in the flags passed to the block if matching failed due to an internal error (such as an expression requiring exponential memory allocations) without examining the entire search range. NSMatchingAnchored, NSMatchingWithTransparentBounds, and NSMatchingWithoutAnchoringBounds can apply to any match or replace method. If NSMatchingAnchored is specified, matches are limited to those at the start of the search range. If NSMatchingWithTransparentBounds is specified, matching may examine parts of the string beyond the bounds of the search range, for purposes such as word boundary detection, lookahead, etc. If NSMatchingWithoutAnchoringBounds is specified, ^ and $ will not automatically match the beginning and end of the search range (but will still match the beginning and end of the entire string). NSMatchingWithTransparentBounds and NSMatchingWithoutAnchoringBounds have no effect if the search range covers the entire string. NSRegularExpression is designed to be immutable and threadsafe, so that a single instance can be used in matching operations on multiple threads at once. However, the string on which it is operating should not be mutated during the course of a matching operation (whether from another thread or from within the block used in the iteration). */ extension NSRegularExpression { /* NSRegularExpression also provides find-and-replace methods for both immutable and mutable strings. The replacement is treated as a template, with $0 being replaced by the contents of the matched range, $1 by the contents of the first capture group, and so on. Additional digits beyond the maximum required to represent the number of capture groups will be treated as ordinary characters, as will a $ not followed by digits. Backslash will escape both $ and itself. */ public func stringByReplacingMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange, withTemplate templ: String) -> String { var str: String = "" let length = string.length var previousRange = NSMakeRange(0, 0) let results = matches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) let start = string.utf16.startIndex for result in results { let currentRange = result.range let replacement = replacementString(for: result, in: string, offset: 0, template: templ) if currentRange.location > NSMaxRange(previousRange) { let min = start.advanced(by: NSMaxRange(previousRange)) let max = start.advanced(by: currentRange.location) str += String(string.utf16[min..<max])! } str += replacement previousRange = currentRange } if length > NSMaxRange(previousRange) { let min = start.advanced(by: NSMaxRange(previousRange)) let max = start.advanced(by: length) str += String(string.utf16[min..<max])! } return str } public func replaceMatches(in string: NSMutableString, options: NSRegularExpression.MatchingOptions = [], range: NSRange, withTemplate templ: String) -> Int { let results = matches(in: string._swiftObject, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) var count = 0 var offset = 0 for result in results { var currentRange = result.range let replacement = replacementString(for: result, in: string._swiftObject, offset: offset, template: templ) currentRange.location += offset string.replaceCharacters(in: currentRange, with: replacement) offset += replacement.length - currentRange.length count += 1 } return count } /* For clients implementing their own replace functionality, this is a method to perform the template substitution for a single result, given the string from which the result was matched, an offset to be added to the location of the result in the string (for example, in case modifications to the string moved the result since it was matched), and a replacement template. */ public func replacementString(for result: NSTextCheckingResult, in string: String, offset: Int, template templ: String) -> String { // ??? need to consider what happens if offset takes range out of bounds due to replacement struct once { static let characterSet = CharacterSet(charactersIn: "\\$") } let template = templ._nsObject var range = template.rangeOfCharacter(from: once.characterSet) if range.length > 0 { var numberOfDigits = 1 var orderOfMagnitude = 10 let numberOfRanges = result.numberOfRanges let str = templ._nsObject.mutableCopy(with: nil) as! NSMutableString var length = str.length while (orderOfMagnitude < numberOfRanges && numberOfDigits < 20) { numberOfDigits += 1 orderOfMagnitude *= 10 } while range.length > 0 { var c = str.character(at: range.location) if c == unichar(unicodeScalarLiteral: "\\") { str.deleteCharacters(in: range) length -= range.length range.length = 1 } else if c == unichar(unicodeScalarLiteral: "$") { var groupNumber: Int = NSNotFound var idx = NSMaxRange(range) while idx < length && idx < NSMaxRange(range) + numberOfDigits { c = str.character(at: idx) if c < unichar(unicodeScalarLiteral: "0") || c > unichar(unicodeScalarLiteral: "9") { break } if groupNumber == NSNotFound { groupNumber = 0 } groupNumber *= 10 groupNumber += Int(c) - Int(unichar(unicodeScalarLiteral: "0")) idx += 1 } if groupNumber != NSNotFound { let rangeToReplace = NSMakeRange(range.location, idx - range.location) var substringRange = NSMakeRange(NSNotFound, 0) var substring = "" if groupNumber < numberOfRanges { substringRange = result.range(at: groupNumber) } if substringRange.location != NSNotFound { substringRange.location += offset } if substringRange.location != NSNotFound && substringRange.length > 0 { let start = string.utf16.startIndex let min = start.advanced(by: substringRange.location) let max = start.advanced(by: substringRange.location + substringRange.length) substring = String(string.utf16[min..<max])! } str.replaceCharacters(in: rangeToReplace, with: substring) length += substringRange.length - rangeToReplace.length range.length = substringRange.length } } if NSMaxRange(range) > length { break } range = str.rangeOfCharacter(from: once.characterSet, options: [], range: NSMakeRange(NSMaxRange(range), length - NSMaxRange(range))) } return str._swiftObject } return templ } /* This class method will produce a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as template metacharacters. */ open class func escapedTemplate(for string: String) -> String { return _CFRegularExpressionCreateEscapedPattern(string._cfObject)._swiftObject } }
apache-2.0
4053be9f02af0de4e2c6dfcd2c1b97a3
56.855228
901
0.669972
5.357498
false
false
false
false
lb2281075105/LBXiongMaoTV
LBXiongMaoTV/LBXiongMaoTV/Entertainment(娱乐)/BaseVC/LBXMYuLeBaseVController.swift
1
2335
// // LBXMYuLeBaseVController.swift // LBXiongMaoTV // // Created by 云媒 on 2017/4/18. // Copyright © 2017年 YunMei. All rights reserved. // import UIKit ///间隔 private let itemMargin:CGFloat = 10 ///item宽度 private let itemWidth = (UIScreen.cz_screenWidth() - itemMargin * 3)/2.0 ///item高度 private let itemHeight = (itemWidth * 3)/4 class LBXMYuLeBaseVController: UIViewController { ///视图模型 lazy var lbxmYuleViewModel = LBXMYuLeViewModel() ///集合视图 lazy var baseCollectionView:UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize.init(width: itemWidth, height: itemHeight) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 10 layout.sectionInset = UIEdgeInsetsMake(itemMargin, itemMargin, itemMargin, itemMargin) let baseCollectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: UIScreen.cz_screenHeight() - 64 - 40 - 49), collectionViewLayout: layout) baseCollectionView.register(LBXMYuLeBaseCell.self, forCellWithReuseIdentifier: "YuLeCell") baseCollectionView.delegate = self baseCollectionView.dataSource = self return baseCollectionView }() ///模型数组 lazy var baseModelArray:[LBXMYuLeModel] = [LBXMYuLeModel]() override func viewDidLoad() { super.viewDidLoad() ///添加集合视图 print("添加集合视图") baseCollectionView.backgroundColor = UIColor.white view.addSubview(baseCollectionView) } } extension LBXMYuLeBaseVController:UICollectionViewDelegateFlowLayout,UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { print(baseModelArray.count) return baseModelArray.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let yuleCell = collectionView.dequeueReusableCell(withReuseIdentifier: "YuLeCell", for: indexPath) as?LBXMYuLeBaseCell yuleCell?.lbxmBaseModel = baseModelArray[indexPath.row] return yuleCell! } }
apache-2.0
04e77e955b0ad6e62562a793c6f0852d
36.180328
201
0.719136
4.54509
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/insert-interval.swift
2
1582
/** * https://leetcode.com/problems/insert-interval/ * * */ // Date: Thu Jul 23 16:32:51 PDT 2020 class Solution { /// Go through every interval in intervals /// 1. If pair is on left of newInterval, then append the pair to result /// 2. If pair is on right of newInterval, then append the newInterval and pair /// ps: set newInterval to empty, once it's been added to the result. /// 3. if pair has overlap with newInterval, then merge two and replace newInterval with the merged one. /// /// - Complexity: /// - Time: O(n), n is the number of intervals in intervals /// - Space: O(1), if we dont count the return result. /// func insert(_ intervals: [[Int]], _ newInterval: [Int]) -> [[Int]] { func merge(_ a: [Int], _ b: [Int]) -> [Int] { return [min(a[0], b[0]), max(a[1], b[1])] } var result: [[Int]] = [] var ainterval: [Int]? = newInterval for pair in intervals { if let interval = ainterval { if pair[1] < interval[0] { result.append(pair) } else if pair[0] > interval[1] { result.append(interval) result.append(pair) ainterval = nil } else { ainterval = merge(interval, pair) } } else { result.append(pair) } } if let interval = ainterval { result.append(interval) } return result } }
mit
f88080c41e811d267c6cc03055c2366d
34.954545
108
0.505057
4.119792
false
false
false
false
milseman/swift
test/Migrator/to_int_max.swift
12
920
// REQUIRES: objc_interop // RUN: %target-swift-frontend -typecheck -swift-version 3 %s // RUN: rm -rf %t && mkdir -p %t && %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/to_int_max.result -emit-remap-file-path %t/to_int_max.remap -o /dev/null // RUN: diff -u %S/to_int_max.swift.expected %t/to_int_max.result // RUN: %target-swift-frontend -typecheck -swift-version 4 %t/to_int_max.result let u: UInt = 0 let u8: UInt8 = 0 let u16: UInt16 = 0 let u32: UInt32 = 0 let u64: UInt64 = 0 let i: Int = 0 let i8: Int8 = 0 let i16: Int16 = 0 let i32: Int32 = 0 let i64: Int64 = 0 _ = u.toUIntMax() _ = u8.toUIntMax() _ = u16.toUIntMax() _ = u32.toUIntMax() _ = u64.toUIntMax() _ = i.toIntMax() _ = i8.toIntMax() _ = i16.toIntMax() _ = i32.toIntMax() _ = i64.toIntMax() func foo<T: UnsignedInteger>(x: T) { _ = x.toUIntMax() } func foo<T: SignedInteger>(x: T) { _ = x.toIntMax() }
apache-2.0
ef75c173c8be94aa11d3c547b5c1edde
23.864865
192
0.63913
2.473118
false
false
false
false
lchanmann/EightPuzzle
EightPuzzle/Puzzle.swift
1
1688
// // Puzzle.swift // EightPuzzle // // Created by mann on 12/2/14. // Copyright (c) 2014 mann. All rights reserved. // public class Puzzle { private var layout: [Int] private var blankIndex: Int = 0 init(layout: [Int]) { self.layout = layout for var i=0; i<layout.count; i++ { if layout[i] == 0 { blankIndex = i break } } } public func get_layout() -> [Int] { return layout } public func get_actions() -> [Action] { var actions = [Action.Left, Action.Right, Action.Up, Action.Down] var rowIndex = blankIndex / 3 var colIndex = blankIndex % 3 if rowIndex == 0 { actions.removeAtIndex(3) } if rowIndex == 2 { actions.removeAtIndex(2) } if colIndex == 0 { actions.removeAtIndex(0) } if colIndex == 2 { actions.removeAtIndex(1) } return actions } public func move(action: Action) { var swapIndex: Int switch action { case .Left: swapIndex = blankIndex - 1 case .Right: swapIndex = blankIndex + 1 case .Up: swapIndex = blankIndex + 3 case .Down: swapIndex = blankIndex - 3 } swap(blankIndex, j: swapIndex) blankIndex = swapIndex } private func swap(i: Int, j: Int) { var x = i, y = j // make x be the smaller index if i > j { x = j y = i } var yValue = layout.removeAtIndex(y) layout.insert(layout[x], atIndex: y) layout.removeAtIndex(x) layout.insert(yValue, atIndex: x) } }
mit
51911fe234b0e025d639b4afbc4c5d0a
24.984615
73
0.518957
3.943925
false
false
false
false
apple/swift-argument-parser
Sources/ArgumentParser/Utilities/StringExtensions.swift
1
8512
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// extension StringProtocol where SubSequence == Substring { func wrapped(to columns: Int, wrappingIndent: Int = 0) -> String { let columns = columns - wrappingIndent guard columns > 0 else { // Skip wrapping logic if the number of columns is less than 1 in release // builds and assert in debug builds. assertionFailure("`columns - wrappingIndent` should be always be greater than 0.") return "" } var result: [Substring] = [] var currentIndex = startIndex while true { let nextChunk = self[currentIndex...].prefix(columns) if let lastLineBreak = nextChunk.lastIndex(of: "\n") { result.append(contentsOf: self[currentIndex..<lastLineBreak].split(separator: "\n", omittingEmptySubsequences: false)) currentIndex = index(after: lastLineBreak) } else if nextChunk.endIndex == self.endIndex { result.append(self[currentIndex...]) break } else if let lastSpace = nextChunk.lastIndex(of: " ") { result.append(self[currentIndex..<lastSpace]) currentIndex = index(after: lastSpace) } else if let nextSpace = self[currentIndex...].firstIndex(of: " ") { result.append(self[currentIndex..<nextSpace]) currentIndex = index(after: nextSpace) } else { result.append(self[currentIndex...]) break } } return result .map { $0.isEmpty ? $0 : String(repeating: " ", count: wrappingIndent) + $0 } .joined(separator: "\n") } /// Returns this string prefixed using a camel-case style. /// /// Example: /// /// "hello".addingIntercappedPrefix("my") /// // myHello func addingIntercappedPrefix(_ prefix: String) -> String { guard let firstChar = first else { return prefix } return "\(prefix)\(firstChar.uppercased())\(self.dropFirst())" } /// Returns this string prefixed using kebab-, snake-, or camel-case style /// depending on what can be detected from the string. /// /// Examples: /// /// "hello".addingPrefixWithAutodetectedStyle("my") /// // my-hello /// "hello_there".addingPrefixWithAutodetectedStyle("my") /// // my_hello_there /// "hello-there".addingPrefixWithAutodetectedStyle("my") /// // my-hello-there /// "helloThere".addingPrefixWithAutodetectedStyle("my") /// // myHelloThere func addingPrefixWithAutodetectedStyle(_ prefix: String) -> String { if contains("-") { return "\(prefix)-\(self)" } else if contains("_") { return "\(prefix)_\(self)" } else if first?.isLowercase == true && contains(where: { $0.isUppercase }) { return addingIntercappedPrefix(prefix) } else { return "\(prefix)-\(self)" } } /// Returns a new string with the camel-case-based words of this string /// split by the specified separator. /// /// Examples: /// /// "myProperty".convertedToSnakeCase() /// // my_property /// "myURLProperty".convertedToSnakeCase() /// // my_url_property /// "myURLProperty".convertedToSnakeCase(separator: "-") /// // my-url-property func convertedToSnakeCase(separator: Character = "_") -> String { guard !isEmpty else { return "" } var result = "" // Whether we should append a separator when we see a uppercase character. var separateOnUppercase = true for index in indices { let nextIndex = self.index(after: index) let character = self[index] if character.isUppercase { if separateOnUppercase && !result.isEmpty { // Append the separator. result += "\(separator)" } // If the next character is uppercase and the next-next character is lowercase, like "L" in "URLSession", we should separate words. separateOnUppercase = nextIndex < endIndex && self[nextIndex].isUppercase && self.index(after: nextIndex) < endIndex && self[self.index(after: nextIndex)].isLowercase } else { // If the character is `separator`, we do not want to append another separator when we see the next uppercase character. separateOnUppercase = character != separator } // Append the lowercased character. result += character.lowercased() } return result } /// Returns the edit distance between this string and the provided target string. /// /// Uses the Levenshtein distance algorithm internally. /// /// See: https://en.wikipedia.org/wiki/Levenshtein_distance /// /// Examples: /// /// "kitten".editDistance(to: "sitting") /// // 3 /// "bar".editDistance(to: "baz") /// // 1 func editDistance(to target: String) -> Int { let rows = self.count let columns = target.count if rows <= 0 || columns <= 0 { return Swift.max(rows, columns) } // Trim common prefix and suffix var selfStartTrim = self.startIndex var targetStartTrim = target.startIndex while selfStartTrim < self.endIndex && targetStartTrim < target.endIndex && self[selfStartTrim] == target[targetStartTrim] { self.formIndex(after: &selfStartTrim) target.formIndex(after: &targetStartTrim) } var selfEndTrim = self.endIndex var targetEndTrim = target.endIndex while selfEndTrim > selfStartTrim && targetEndTrim > targetStartTrim { let selfIdx = self.index(before: selfEndTrim) let targetIdx = target.index(before: targetEndTrim) guard self[selfIdx] == target[targetIdx] else { break } selfEndTrim = selfIdx targetEndTrim = targetIdx } // Equal strings guard !(selfStartTrim == self.endIndex && targetStartTrim == target.endIndex) else { return 0 } // After trimming common prefix and suffix, self is empty. guard selfStartTrim < selfEndTrim else { return target.distance(from: targetStartTrim, to: targetEndTrim) } // After trimming common prefix and suffix, target is empty. guard targetStartTrim < targetEndTrim else { return distance(from: selfStartTrim, to: selfEndTrim) } let newSelf = self[selfStartTrim..<selfEndTrim] let newTarget = target[targetStartTrim..<targetEndTrim] let m = newSelf.count let n = newTarget.count // Initialize the levenshtein matrix with only two rows // current and previous. var previousRow = [Int](repeating: 0, count: n + 1) var currentRow = [Int](0...n) var sourceIdx = newSelf.startIndex for i in 1...m { swap(&previousRow, &currentRow) currentRow[0] = i var targetIdx = newTarget.startIndex for j in 1...n { // If characteres are equal for the levenshtein algorithm the // minimum will always be the substitution cost, so we can fast // path here in order to avoid min calls. if newSelf[sourceIdx] == newTarget[targetIdx] { currentRow[j] = previousRow[j - 1] } else { let deletion = previousRow[j] let insertion = currentRow[j - 1] let substitution = previousRow[j - 1] currentRow[j] = Swift.min(deletion, Swift.min(insertion, substitution)) + 1 } // j += 1 newTarget.formIndex(after: &targetIdx) } // i += 1 newSelf.formIndex(after: &sourceIdx) } return currentRow[n] } func indentingEachLine(by n: Int) -> String { let lines = self.split(separator: "\n", omittingEmptySubsequences: false) let spacer = String(repeating: " ", count: n) return lines.map { $0.isEmpty ? $0 : spacer + $0 }.joined(separator: "\n") } func hangingIndentingEachLine(by n: Int) -> String { let lines = self.split( separator: "\n", maxSplits: 1, omittingEmptySubsequences: false) guard lines.count == 2 else { return lines.joined(separator: "") } return "\(lines[0])\n\(lines[1].indentingEachLine(by: n))" } var nonEmpty: Self? { isEmpty ? nil : self } }
apache-2.0
fd56adb2f14b9d4da643f682ca206874
33.742857
174
0.616306
4.320812
false
false
false
false
pekoto/fightydot
FightyDot/FightyDot/NodeImageView.swift
1
7011
// // DraggableImageView.swift // FightyDot // // Created by Graham McRobbie on 23/01/2017. // Copyright © 2017 Graham McRobbie. All rights reserved. // import Foundation import UIKit class NodeImageView: UIImageView { // Image dragged around screen when moving/flying private var _draggableImg: UIImageView? // Image to restore if drag cancelled/invalid private var _originalImg: UIImage? // ImageViews this node can be dragged to private var _validMoveSpots: [NodeImageView]? // ImageViews intersecting with the draggable image private var _intersectingMoveSpots: [NodeImageView]? // For placing/taking pieces func enableTapDisableDrag() { self.gestureRecognizers?[Constants.View.tapGestureRecognizerIndex].isEnabled = true self.gestureRecognizers?[Constants.View.dragGestureRecognizerIndex].isEnabled = false self.isUserInteractionEnabled = true if(self.image != #imageLiteral(resourceName: "empty-node")) { guard let nodeImg = self.image else { return } let nodeColour = Constants.PieceDics.imgColours[nodeImg] self.addAnimatedShadow(colour: nodeColour?.cgColor) } } // For moving/flying func enableDragDisableTap() { self.gestureRecognizers?[Constants.View.dragGestureRecognizerIndex].isEnabled = true self.gestureRecognizers?[Constants.View.tapGestureRecognizerIndex].isEnabled = false self.isUserInteractionEnabled = true self.addAnimatedShadow() } func disable() { self.gestureRecognizers?[Constants.View.tapGestureRecognizerIndex].isEnabled = false self.gestureRecognizers?[Constants.View.dragGestureRecognizerIndex].isEnabled = false self.isUserInteractionEnabled = false self.removeAnimatedShadow() } // MARK: - UIGestureRecognizerState.began behaviours func startDragging(to validMoveSpots: [NodeImageView]) { _validMoveSpots = validMoveSpots _intersectingMoveSpots = [] _draggableImg = createDraggableImg() self.topLevelView?.addSubview(_draggableImg!) _originalImg = self.image self.image = #imageLiteral(resourceName: "empty-node") addAnimatedShadowToMoveSpots() } // MARK: - UIGestureRecognizerState.changed behaviours func updatePosition(to newPos: CGPoint) { _draggableImg?.center = newPos } func updateIntersects() { updateIntersectingMoveSpots() checkForNewIntersects() } // MARK: - UIGestureRecognizerState.ended/cancelled behaviours func intersectsWithMoveSpot() -> Bool { guard let intersectingMoveSpots = _intersectingMoveSpots else { return false } return intersectingMoveSpots.count > 0 } func getLastIntersectingMoveSpot() -> NodeImageView? { guard let intersectingMoveSpots = _intersectingMoveSpots else { return nil } return intersectingMoveSpots.last } func endDrag() { removeAnimatedShadowFromMoveSpots() resetIntersectingMoveSpots() _draggableImg?.removeFromSuperview() _draggableImg = nil } func resetOriginalImg () { self.image = _originalImg } // MARK: - Private functions private func createDraggableImg() -> UIImageView { let draggableImg: UIImage? = self.image let imageView = UIImageView(image: draggableImg) let framePosInSuperview = self.convert(self.bounds, to: self.topLevelView) imageView.frame = framePosInSuperview imageView.isUserInteractionEnabled = true imageView.contentMode = .center imageView.layer.shadowColor = UIColor.black.cgColor imageView.layer.shadowOffset = CGSize(width: 0, height: 18) imageView.layer.shadowOpacity = 0.3 imageView.layer.shadowRadius = 4 return imageView } private func addAnimatedShadowToMoveSpots() { guard let validMoveSpots = _validMoveSpots else { return } for moveSpot in validMoveSpots { moveSpot.addAnimatedShadow() } } private func removeAnimatedShadowFromMoveSpots() { guard let validMoveSpots = _validMoveSpots else { return } for moveSpot in validMoveSpots { moveSpot.removeAnimatedShadow() } } private func updateIntersectingMoveSpots() { guard let draggableImg = _draggableImg else { return } guard let intersectingMoveSpots = _intersectingMoveSpots else { return } var intersectingMoveSpotRemoved = false for intersectingMoveSpot in intersectingMoveSpots { if(!intersectingMoveSpot.intersectsIgnoringCoordinateSpace(draggableImg)) { removeIntersecting(moveSpot: intersectingMoveSpot) intersectingMoveSpotRemoved = true } } if(intersectingMoveSpotRemoved) { resetMoveSpotAnimations() } } private func removeIntersecting(moveSpot: NodeImageView) { _intersectingMoveSpots?.remove(object: moveSpot) _validMoveSpots?.append(moveSpot) moveSpot.image = #imageLiteral(resourceName: "empty-node") } private func resetMoveSpotAnimations() { guard let validMoveSpots = _validMoveSpots else { return } for moveSpot in validMoveSpots { moveSpot.removeAnimatedShadow() moveSpot.addAnimatedShadow() } } private func checkForNewIntersects() { guard let draggableImg = _draggableImg else { return } guard let validMoveSpots = _validMoveSpots else { return } for moveSpot in validMoveSpots { if(moveSpot.intersectsIgnoringCoordinateSpace(draggableImg)) { addIntersecting(moveSpot: moveSpot) } } } private func addIntersecting(moveSpot: NodeImageView) { _validMoveSpots?.remove(object: moveSpot) moveSpot.removeAnimatedShadow() moveSpot.image = #imageLiteral(resourceName: "empty-node-selectable") _intersectingMoveSpots?.append(moveSpot) } private func resetIntersectingMoveSpots() { guard let intersectingMoveSpots = _intersectingMoveSpots else { return } for intersectingMoveSpot in intersectingMoveSpots { if(intersectingMoveSpot.image == #imageLiteral(resourceName: "empty-node-selectable")) { intersectingMoveSpot.image = #imageLiteral(resourceName: "empty-node") } } } }
mit
b78e558cc59482a882194da0f82b8770
30.576577
100
0.631669
5.192593
false
false
false
false
Rostmen/TimelineController
RZTimelineCollection/ViewController.swift
1
3314
// // ViewController.swift // RZTimelineCollection // // Created by Rostyslav Kobizsky on 12/23/14. // Copyright (c) 2014 Rozdoum. All rights reserved. // import UIKit class ViewController: RZTimelineController { var dataSource = [RZPost]() var postBackgroundImage = RZPostImageFactory().postBackgroundImageRight(UIColor.lightGrayColor()) let postIcon = RZAvatarImageFactory.postIconImage(20) override func viewDidLoad() { super.viewDidLoad() senderId = "MySenderID" senderDisplayName = "Rozdoum timeline" for index in 0...39 { let postSenderId = index % 3 == 0 ? senderId : "" let post = RZPost(senderId: randomStringWithLength(10), senderDisplayName: randomStringWithLength(10), time: NSDate(), isMedia: false) post.text = randomStringWithLength(Int(arc4random_uniform(100))) dataSource.append(post) } } func randomStringWithLength (len : Int) -> NSString { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var randomString : NSMutableString = NSMutableString(capacity: len) for (var i=0; i < len; i++){ var length = UInt32 (letters.length) var rand = arc4random_uniform(length) randomString.appendFormat("%C", letters.characterAtIndex(Int(rand))) } return randomString } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as RZPostCollectionViewCell cell.textView.textColor = UIColor.blackColor() return cell } override func collectionView(collectionView: RZPostCollectionView, layout: RZTimelineCollectionLayout, heightForCellTopLabelAtIndexPath idnexPath: NSIndexPath) -> CGFloat { return 20 } func collectionView(collectionView: RZPostCollectionView, attributedTextForCellTopLabelAtIndexPath indexPath: NSIndexPath) -> NSAttributedString? { let post = dataSource[indexPath.item] return RZTimestampFormatter().attributedTimestampForDate(post.time) } // MARK: RZCollectionViewDataSource override func collectionView(collectionView: RZPostCollectionView, postDataForIndexPath indexPath: NSIndexPath) -> RZPostData { return dataSource[indexPath.item] } override func collectionView(collectionView: RZPostCollectionView, backgroundImageDataAtIndexPath indexPath: NSIndexPath) -> RZPostBackgroundImageSource? { return postBackgroundImage } override func collectionView(collectionView: RZPostCollectionView, avatarImageDataAtIndexPath indexPath: NSIndexPath) -> RZAvatarImageDataSource? { return postIcon } }
apache-2.0
109ad2eba1548aac3abccb740d4fcb70
35.021739
176
0.689801
5.773519
false
false
false
false
february29/Learning
swift/Fch_Contact/Fch_Contact/AppClasses/ViewController/ShareViewController.swift
1
1201
// // ShareViewController.swift // Fch_Contact // // Created by bai on 2018/3/9. // Copyright © 2018年 北京仙指信息技术有限公司. All rights reserved. // import UIKit class ShareViewController: BBaseViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "分享"; let imageView = UIImageView(image: #imageLiteral(resourceName: "img_share")); self.view.addSubview(imageView); imageView.snp.makeConstraints { (make) in make.center.equalTo(self.view); make.width.height.equalTo(self.view.snp.width).multipliedBy(0.75); }; let lable = UILabel(); lable .setTextFontSize(type: .primary); lable.setTextColor(.primary); lable.text = "扫描二维码下载风驰电话本"; lable.textAlignment = .center; self.view.addSubview(lable); lable.snp.makeConstraints { (make) in make.bottom.equalTo(imageView.snp.top); make.centerX.equalTo(imageView); make.left.right.equalTo(self.view); make.height.equalTo(40); } } }
mit
060900ceedeb98c8043dade7d297a27b
24.466667
85
0.586387
4.213235
false
false
false
false
Piwigo/Piwigo-Mobile
piwigo/Upload/Upload Queue/UploadQueueViewController.swift
1
21304
// // UploadQueueViewController.swift // piwigo // // Created by Eddy Lelièvre-Berna on 17/05/2020. // Copyright © 2020 Piwigo.org. All rights reserved. // import Photos import UIKit import piwigoKit @available(iOS 13.0, *) class UploadQueueViewController: UIViewController, UITableViewDelegate { // MARK: - Core Data /** The managedObjectContext that manages Core Data objects in the main queue. The UploadsProvider that collects upload data, saves it to Core Data, and serves it to the uploader. */ lazy var managedObjectContext: NSManagedObjectContext = { let context:NSManagedObjectContext = DataController.managedObjectContext return context }() private lazy var uploadsProvider: UploadsProvider = { let provider : UploadsProvider = UploadsProvider() provider.fetchedNonCompletedResultsControllerDelegate = self return provider }() // MARK: - View @IBOutlet weak var queueTableView: UITableView! private var actionBarButton: UIBarButtonItem? private var doneBarButton: UIBarButtonItem? typealias DataSource = UITableViewDiffableDataSource<String,NSManagedObjectID> private lazy var diffableDataSource: DataSource = configDataSource() // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Buttons actionBarButton = UIBarButtonItem(image: UIImage(named: "action"), landscapeImagePhone: UIImage(named: "actionCompact"), style: .plain, target: self, action: #selector(didTapActionButton)) doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(quitUpload)) doneBarButton?.accessibilityIdentifier = "Done" // Register section header view queueTableView.register(UploadImageHeaderView.self, forHeaderFooterViewReuseIdentifier:"UploadImageHeaderView") // Initialise dataSource and tableView applyInitialSnapshots() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Set colors, fonts, etc. applyColorPaletteToInitialViews() // Navigation bar button and identifier navigationItem.setLeftBarButtonItems([doneBarButton].compactMap { $0 }, animated: false) navigationController?.navigationBar.accessibilityIdentifier = "UploadQueueNav" updateNavBar() // Header informing user on network status setTableViewMainHeader() // Register palette changes NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette), name: .pwgPaletteChanged, object: nil) // Register network reachability NotificationCenter.default.addObserver(self, selector: #selector(setTableViewMainHeader), name: Notification.Name.AFNetworkingReachabilityDidChange, object: nil) // Register Low Power Mode status NotificationCenter.default.addObserver(self, selector: #selector(setTableViewMainHeader), name: Notification.Name.NSProcessInfoPowerStateDidChange, object: nil) // Register upload progress NotificationCenter.default.addObserver(self, selector: #selector(applyUploadProgress), name: .pwgUploadProgress, object: nil) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // Save position of collection view if queueTableView.visibleCells.count > 0, let cell = queueTableView.visibleCells.first { if let indexPath = queueTableView.indexPath(for: cell) { // Reload the tableview on orientation change, to match the new width of the table. coordinator.animate(alongsideTransition: { context in self.queueTableView.reloadData() // Scroll to previous position self.queueTableView.scrollToRow(at: indexPath, at: .middle, animated: true) }) } } } private func applyColorPaletteToInitialViews() { // Background color of the view view.backgroundColor = .piwigoColorBackground() // Navigation bar let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.piwigoColorWhiteCream(), NSAttributedString.Key.font: UIFont.piwigoFontNormal() ] navigationController?.navigationBar.titleTextAttributes = attributes navigationController?.navigationBar.prefersLargeTitles = false navigationController?.navigationBar.barStyle = AppVars.shared.isDarkPaletteActive ? .black : .default navigationController?.navigationBar.tintColor = .piwigoColorOrange() navigationController?.navigationBar.barTintColor = .piwigoColorBackground() navigationController?.navigationBar.backgroundColor = .piwigoColorBackground() if #available(iOS 15.0, *) { /// In iOS 15, UIKit has extended the usage of the scrollEdgeAppearance, /// which by default produces a transparent background, to all navigation bars. let barAppearance = UINavigationBarAppearance() barAppearance.configureWithOpaqueBackground() barAppearance.backgroundColor = .piwigoColorBackground() navigationController?.navigationBar.standardAppearance = barAppearance navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance } // Table view queueTableView.separatorColor = .piwigoColorSeparator() queueTableView.indicatorStyle = AppVars.shared.isDarkPaletteActive ? .white : .black } @objc func applyColorPalette() { // Set colors, fonts, etc. applyColorPaletteToInitialViews() // Table view items let visibleCells = queueTableView.visibleCells as? [UploadImageTableViewCell] ?? [] visibleCells.forEach { (cell) in cell.backgroundColor = .piwigoColorCellBackground() cell.uploadInfoLabel.textColor = .piwigoColorLeftLabel() cell.swipeBackgroundColor = .piwigoColorCellBackground() cell.imageInfoLabel.textColor = .piwigoColorRightLabel() } for section in 0..<queueTableView.numberOfSections { let header = queueTableView.headerView(forSection: section) as? UploadImageHeaderView header?.headerLabel.textColor = .piwigoColorHeader() header?.headerBckg.backgroundColor = .piwigoColorBackground().withAlphaComponent(0.75) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Update title of current scene (iPad only) view.window?.windowScene?.title = title } override func viewWillDisappear(_ animated: Bool) { // Allow device to sleep UIApplication.shared.isIdleTimerDisabled = false } deinit { // Unregister palette changes NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil) // Unregister network reachability NotificationCenter.default.removeObserver(self, name: Notification.Name.AFNetworkingReachabilityDidChange, object: nil) // Unregister Low Power Mode status NotificationCenter.default.removeObserver(self, name: Notification.Name.NSProcessInfoPowerStateDidChange, object: nil) // Unregister upload progress NotificationCenter.default.removeObserver(self, name: .pwgUploadProgress, object: nil) } // MARK: - Action Menu func updateNavBar() { // Title let nberOfImagesInQueue = diffableDataSource.snapshot().numberOfItems title = nberOfImagesInQueue > 1 ? String(format: "%ld %@", nberOfImagesInQueue, NSLocalizedString("severalImages", comment: "Photos")) : String(format: "%ld %@", nberOfImagesInQueue, NSLocalizedString("singleImage", comment: "Photo")) // Set title of current scene (iPad only) view.window?.windowScene?.title = title // Action menu var hasImpossibleUploadsSection = false if let _ = diffableDataSource.snapshot().indexOfSection(SectionKeys.Section1.rawValue) { hasImpossibleUploadsSection = true } var hasFailedUploadsSection = false if let _ = diffableDataSource.snapshot().indexOfSection(SectionKeys.Section2.rawValue) { hasFailedUploadsSection = true } if hasImpossibleUploadsSection || hasFailedUploadsSection { navigationItem.rightBarButtonItems = [actionBarButton].compactMap { $0 } } else { navigationItem.rightBarButtonItems = nil } } @objc func didTapActionButton() { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) // Cancel action let cancelAction = UIAlertAction(title: NSLocalizedString("alertCancelButton", comment: "Cancel"), style: .cancel, handler: { action in }) alert.addAction(cancelAction) // Resume upload requests in section 2 (preparingError, uploadingError, finishingError) if let _ = diffableDataSource.snapshot().indexOfSection(SectionKeys.Section2.rawValue) { let failedUploads = diffableDataSource.snapshot().numberOfItems(inSection: SectionKeys.Section2.rawValue) if failedUploads > 0 { let titleResume = failedUploads > 1 ? String(format: NSLocalizedString("imageUploadResumeSeveral", comment: "Resume %@ Failed Uploads"), NumberFormatter.localizedString(from: NSNumber(value: failedUploads), number: .decimal)) : NSLocalizedString("imageUploadResumeSingle", comment: "Resume Failed Upload") let resumeAction = UIAlertAction(title: titleResume, style: .default, handler: { action in if let _ = self.diffableDataSource.snapshot().indexOfSection(SectionKeys.Section2.rawValue) { // Get IDs of upload requests which can be resumed let uploadIds = self.diffableDataSource.snapshot().itemIdentifiers(inSection: SectionKeys.Section2.rawValue) // Resume failed uploads UploadManager.shared.backgroundQueue.async { UploadManager.shared.resume(failedUploads: uploadIds, completionHandler: { (error) in if let error = error { // Inform user let alert = UIAlertController(title: NSLocalizedString("errorHUD_label", comment: "Error"), message: error.localizedDescription, preferredStyle: .alert) let cancelAction = UIAlertAction(title: NSLocalizedString("alertDismissButton", comment: "Dismiss"), style: .destructive, handler: { action in }) alert.addAction(cancelAction) alert.view.tintColor = .piwigoColorOrange() alert.overrideUserInterfaceStyle = AppVars.shared.isDarkPaletteActive ? .dark : .light self.present(alert, animated: true, completion: { // Bugfix: iOS9 - Tint not fully Applied without Reapplying alert.view.tintColor = .piwigoColorOrange() }) } else { // Relaunch uploads UploadManager.shared.findNextImageToUpload() } }) } } }) alert.addAction(resumeAction) } } // Clear impossible upload requests in section 1 (preparingFail, formatError) if let _ = diffableDataSource.snapshot().indexOfSection(SectionKeys.Section1.rawValue) { let impossibleUploads = diffableDataSource.snapshot().numberOfItems(inSection: SectionKeys.Section1.rawValue) if impossibleUploads > 0 { let titleClear = impossibleUploads > 1 ? String(format: NSLocalizedString("imageUploadClearFailedSeveral", comment: "Clear %@ Failed"), NumberFormatter.localizedString(from: NSNumber(value: impossibleUploads), number: .decimal)) : NSLocalizedString("imageUploadClearFailedSingle", comment: "Clear 1 Failed") let clearAction = UIAlertAction(title: titleClear, style: .default, handler: { action in if let _ = self.diffableDataSource.snapshot().indexOfSection(SectionKeys.Section1.rawValue) { // Get IDs of upload requests which won't be possible to perform let uploadIds = self.diffableDataSource.snapshot().itemIdentifiers(inSection: SectionKeys.Section1.rawValue) // Delete failed uploads in the main thread self.uploadsProvider.delete(uploadRequests: uploadIds) { error in // Error encountered? if let error = error { DispatchQueue.main.async { self.dismissPiwigoError(withTitle: titleClear, message: error.localizedDescription) { } } } } } }) alert.addAction(clearAction) } } // Don't present the alert if there is only "Cancel" if alert.actions.count == 1 { updateNavBar() return } // Present list of actions alert.view.tintColor = .piwigoColorOrange() alert.overrideUserInterfaceStyle = AppVars.shared.isDarkPaletteActive ? .dark : .light alert.popoverPresentationController?.barButtonItem = actionBarButton present(alert, animated: true) { // Bugfix: iOS9 - Tint not fully Applied without Reapplying alert.view.tintColor = .piwigoColorOrange() } } @objc func quitUpload() { // Leave Upload action and return to Albums and Images dismiss(animated: true) } // MARK: - UITableView - DataSource private func configDataSource() -> DataSource { let dataSource = UITableViewDiffableDataSource<String, NSManagedObjectID>(tableView: queueTableView) { (tableView, indexPath, objectID) -> UITableViewCell? in guard let cell = tableView.dequeueReusableCell(withIdentifier: "UploadImageTableViewCell", for: indexPath) as? UploadImageTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a UploadImageTableViewCell!") return UploadImageTableViewCell() } let upload = self.managedObjectContext.object(with: objectID) as! Upload cell.configure(with: upload, availableWidth: Int(tableView.bounds.size.width)) return cell } return dataSource } private func applyInitialSnapshots() { var snapshot = NSDiffableDataSourceSnapshot<String, NSManagedObjectID>() // Sections let sectionInfos = uploadsProvider.fetchedNonCompletedResultsController.sections let sections = sectionInfos?.map({$0.name}) ?? Array(repeating: "—?—", count: sectionInfos?.count ?? 0) snapshot.appendSections(sections) diffableDataSource.apply(snapshot, animatingDifferences: false) // Items let items = uploadsProvider.fetchedNonCompletedResultsController.fetchedObjects ?? [] for section in SectionKeys.allValues { let objectIDsInSection = items.filter({$0.requestSectionKey == section.rawValue}).map({$0.objectID}) if objectIDsInSection.isEmpty { continue } snapshot.appendItems(objectIDsInSection, toSection: section.rawValue) } } // MARK: - UITableView - Headers @objc func setTableViewMainHeader() { DispatchQueue.main.async { if AFNetworkReachabilityManager.shared().isReachableViaWWAN && UploadVars.wifiOnlyUploading { // No Wi-Fi and user wishes to upload only on Wi-Fi let headerView = UploadQueueHeaderView(frame: .zero) headerView.configure(width: self.queueTableView.frame.size.width, text: NSLocalizedString("uploadNoWiFiNetwork", comment: "No Wi-Fi Connection")) self.queueTableView.tableHeaderView = headerView } else if ProcessInfo.processInfo.isLowPowerModeEnabled { // Low Power mode enabled let headerView = UploadQueueHeaderView(frame: .zero) headerView.configure(width: self.queueTableView.frame.size.width, text: NSLocalizedString("uploadLowPowerMode", comment: "Low Power Mode enabled")) self.queueTableView.tableHeaderView = headerView } else { // Prevent device from sleeping if uploads are in progress self.queueTableView.tableHeaderView = nil if let _ = self.diffableDataSource.snapshot().indexOfSection(SectionKeys.Section3.rawValue) { if self.diffableDataSource.snapshot().numberOfItems(inSection: SectionKeys.Section3.rawValue) > 0 { UIApplication.shared.isIdleTimerDisabled = true } } } } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let sectionKey = SectionKeys(rawValue: diffableDataSource.snapshot() .sectionIdentifiers[section]) ?? SectionKeys.Section4 return TableViewUtilities.shared.heightOfHeader(withTitle: sectionKey.name, width: tableView.frame.size.width) } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "UploadImageHeaderView") as? UploadImageHeaderView else { print("Error: tableView.dequeueReusableHeaderFooterView does not return a UploadImageHeaderView!") return UploadImageHeaderView() } let sectionKey = SectionKeys(rawValue: diffableDataSource.snapshot().sectionIdentifiers[section]) ?? SectionKeys.Section4 header.config(with: sectionKey) return header } // MARK: - UITableView - Rows func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return false } @objc func applyUploadProgress(_ notification: Notification) { if let localIdentifier = notification.userInfo?["localIdentifier"] as? String, localIdentifier.count > 0 { let visibleCells = queueTableView.visibleCells as! [UploadImageTableViewCell] for cell in visibleCells { if cell.localIdentifier == localIdentifier { cell.update(with: notification.userInfo!) break } } } } } // MARK: - Uploads Provider NSFetchedResultsControllerDelegate @available(iOS 13.0, *) extension UploadQueueViewController: NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) { // Update UI let snapshot = snapshot as NSDiffableDataSourceSnapshot<String,NSManagedObjectID> DispatchQueue.main.async { // Apply modifications self.diffableDataSource.apply(snapshot, animatingDifferences: self.queueTableView.window != nil) // Update the navigation bar self.updateNavBar() // Refresh header informing user on network status when UploadManager restarted running self.setTableViewMainHeader() } // If all upload requests are done, delete all temporary files (in case some would not be deleted) if snapshot.numberOfItems == 0 { // Delete remaining files from Upload directory (if any) UploadManager.shared.backgroundQueue.async { UploadManager.shared.deleteFilesInUploadsDirectory() } // Close the view when there is no more upload request to display self.dismiss(animated: true, completion: nil) } } }
mit
e8895719b4efa7c2df2e905f188c3520
48.187067
323
0.63574
5.876932
false
false
false
false
a736220388/FinestFood
FinestFood/FinestFood/classes/FoodSubject/FSSearchPage/controllers/FSSearchResultViewController.swift
1
9840
// // FSSearchResultViewController.swift // FinestFood // // Created by qianfeng on 16/8/30. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit class FSSearchResultViewController: FSSearchViewController { var itemUrlString = "" var postUrlString = "" lazy var foodItemArray = NSMutableArray() lazy var foodPostArray = NSMutableArray() var convertListIdClosure:((NSNumber)->Void)? var isItem:Bool = true{ didSet{ if isItem{ for subView in self.view.subviews{ if subView.tag == 700{ subView.removeFromSuperview() } } createCollView() }else{ for subView in self.view.subviews{ if subView.tag == 701{ subView.removeFromSuperview() } } createTableView() } } } private var collView:UICollectionView? private var titleView:UIView? var searchBarKey = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. automaticallyAdjustsScrollViewInsets = false createTitleBtn() downloadPostData() isItem = true searchBar?.text = searchBarKey } func createTitleBtn(){ titleView = UIView() titleView!.backgroundColor = UIColor(white: 0.9, alpha: 1.0) view.addSubview(titleView!) titleView!.snp_makeConstraints { [weak self] (make) in make.left.right.equalTo(self!.view) make.top.equalTo((self?.view)!).offset(64) make.height.equalTo(30) } let postBtn = UIButton() postBtn.layer.borderWidth = 1 postBtn.layer.borderColor = UIColor.blackColor().CGColor if isItem{ postBtn.backgroundColor = UIColor.whiteColor() }else{ postBtn.backgroundColor = UIColor.orangeColor() } postBtn.setTitleColor(UIColor.blackColor(), forState: .Normal) postBtn.setTitle("攻略", forState: .Normal) titleView!.addSubview(postBtn) postBtn.snp_makeConstraints { (make) in make.bottom.left.top.equalTo(titleView!) make.width.equalTo(kScreenWidth/2) } let listBtn = UIButton() if isItem { listBtn.backgroundColor = UIColor.orangeColor() }else{ listBtn.backgroundColor = UIColor.whiteColor() } listBtn.layer.borderWidth = 1 listBtn.layer.borderColor = UIColor.blackColor().CGColor listBtn.setTitle("商品", forState: .Normal) listBtn.setTitleColor(UIColor.blackColor(), forState: .Normal) titleView!.addSubview(listBtn) listBtn.snp_makeConstraints { (make) in make.bottom.right.top.equalTo(titleView!) make.width.equalTo(kScreenWidth/2) } postBtn.tag = 650 listBtn.tag = 651 postBtn.addTarget(self, action: #selector(clickAction(_:)), forControlEvents: .TouchUpInside) listBtn.addTarget(self, action: #selector(clickAction(_:)), forControlEvents: .TouchUpInside) } func clickAction(btn:UIButton){ if btn.tag == 650{ btn.backgroundColor = UIColor.orangeColor() let btn1 = btn.superview?.viewWithTag(651) as! UIButton btn1.backgroundColor = UIColor.whiteColor() isItem = false }else if btn.tag == 651{ btn.backgroundColor = UIColor.orangeColor() let btn1 = btn.superview?.viewWithTag(650) as! UIButton btn1.backgroundColor = UIColor.whiteColor() isItem = true } } override func createTableView(){ tbView = UITableView(frame: CGRectMake(0, 64 + 30, kScreenWidth, kScreenHeight-64-30), style: .Plain) tbView?.tag = 700 tbView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0) view.addSubview(tbView!) tbView?.delegate = self tbView?.dataSource = self } func createCollView(){ let layout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10) layout.itemSize = CGSizeMake((kScreenWidth-30)/2, (kScreenWidth-30)/2*1.2) layout.minimumLineSpacing = 10 layout.minimumInteritemSpacing = 10 collView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) collView?.tag = 701 collView?.delegate = self collView?.dataSource = self collView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0) view.addSubview(collView!) collView?.snp_makeConstraints(closure: { [weak self] (make) in make.top.equalTo((self?.view.snp_top)!).offset(64 + 30) make.right.left.equalTo((self?.view)!) make.bottom.equalTo((self?.view.snp_bottom)!).offset(0) }) let nib = UINib(nibName: "FSFoodListCell", bundle: nil) collView?.registerNib(nib, forCellWithReuseIdentifier: "foodListCellId") } override func downloadData() { if itemUrlString == ""{ return } let downloader = MyDownloader() downloader.downloadWithUrlString(itemUrlString) downloader.didFailWithError = { error in print(error) } downloader.didFinishWithData = { [weak self] data in let jsonData = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) if jsonData.isKindOfClass(NSDictionary.self){ let dict = jsonData as! NSDictionary let dataDict = dict["data"] as! NSDictionary let itemsArray = dataDict["items"] as! Array<Dictionary<String,AnyObject>> for itemDict in itemsArray{ let model = FoodListItemModel() model.setValuesForKeysWithDictionary(itemDict) self!.foodItemArray.addObject(model) } dispatch_async(dispatch_get_main_queue(), { self!.collView?.reloadData() }) } } } func downloadPostData(){ if postUrlString == ""{ return } let downloader = MyDownloader() downloader.downloadWithUrlString(postUrlString) downloader.didFailWithError = { error in print(error) } downloader.didFinishWithData = { [weak self] data in let jsonData = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) if jsonData.isKindOfClass(NSDictionary.self){ let dict = jsonData as! NSDictionary let dataDict = dict["data"] as! NSDictionary let itemsArray = dataDict["posts"] as! Array<Dictionary<String,AnyObject>> for itemDict in itemsArray{ let model = FSFoodMoreListModel() model.setValuesForKeysWithDictionary(itemDict) self!.foodPostArray.addObject(model) } dispatch_async(dispatch_get_main_queue(), { self!.tbView?.reloadData() }) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension FSSearchResultViewController{ override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if foodPostArray.count == 0{ return 0 } return foodPostArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let model = foodPostArray[indexPath.row] as! FSFoodMoreListModel let cell = FoodMoreListCell.createFoodMoreListCellFor(tableView, atIndexPath: indexPath, withModel: model) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 200 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let model = foodPostArray[indexPath.row] as! FSFoodMoreListModel let foodDetailCtrl = FoodDetailViewController() foodDetailCtrl.id = Int(model.id!) self.navigationController?.pushViewController(foodDetailCtrl, animated: true) } } extension FSSearchResultViewController:UICollectionViewDelegate,UICollectionViewDataSource{ func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return foodItemArray.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cellId = "foodListCellId" let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as? FSFoodListCell let model = foodItemArray[indexPath.item] as! FoodListItemModel cell?.configModel(model) return cell! } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let model = foodItemArray[indexPath.item] as! FoodListItemModel let detailCtrl = FoodListDetailViewController() detailCtrl.itemId = Int(model.id!) detailCtrl.isSearchResult = true detailCtrl.detailModel = model navigationController?.pushViewController(detailCtrl, animated: true) } }
mit
5d5dbeb59c1c7e4ffaaacf2a75f05121
37.849802
130
0.614101
5.138003
false
false
false
false
practicalswift/swift
test/SILGen/function_conversion.swift
4
36831
// RUN: %target-swift-emit-silgen -module-name function_conversion -enable-sil-ownership -primary-file %s | %FileCheck %s // RUN: %target-swift-emit-ir -module-name function_conversion -enable-sil-ownership -primary-file %s // Check SILGen against various FunctionConversionExprs emitted by Sema. // ==== Representation conversions // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion7cToFuncyS2icS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @callee_guaranteed (Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @$sS2iIetCyd_S2iIegyd_TR // CHECK: [[FUNC:%.*]] = partial_apply [callee_guaranteed] [[THUNK]](%0) // CHECK: return [[FUNC]] func cToFunc(_ arg: @escaping @convention(c) (Int) -> Int) -> (Int) -> Int { return arg } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion8cToBlockyS2iXBS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @convention(block) (Int) -> Int // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] // CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) (Int) -> Int // CHECK: return [[COPY]] func cToBlock(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(block) (Int) -> Int { return arg } // ==== Throws variance // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToThrowsyyyKcyycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @owned @callee_guaranteed () -> @error Error // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed () -> ()): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed () -> () to $@callee_guaranteed () -> @error Error // CHECK: return [[FUNC]] // CHECK: } // end sil function '$s19function_conversion12funcToThrowsyyyKcyycF' func funcToThrows(_ x: @escaping () -> ()) -> () throws -> () { return x } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12thinToThrowsyyyKXfyyXfF : $@convention(thin) (@convention(thin) () -> ()) -> @convention(thin) () -> @error Error // CHECK: [[FUNC:%.*]] = convert_function %0 : $@convention(thin) () -> () to $@convention(thin) () -> @error Error // CHECK: return [[FUNC]] : $@convention(thin) () -> @error Error func thinToThrows(_ x: @escaping @convention(thin) () -> ()) -> @convention(thin) () throws -> () { return x } // FIXME: triggers an assert because we always do a thin to thick conversion on DeclRefExprs /* func thinFunc() {} func thinToThrows() { let _: @convention(thin) () -> () = thinFunc } */ // ==== Class downcasts and upcasts class Feral {} class Domesticated : Feral {} // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> @owned Domesticated) -> @owned @callee_guaranteed () -> @owned Feral { // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed () -> @owned Domesticated): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed () -> @owned Domesticated to $@callee_guaranteed () -> @owned Feral // CHECK: return [[FUNC]] // CHECK: } // end sil function '$s19function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF' func funcToUpcast(_ x: @escaping () -> Domesticated) -> () -> Feral { return x } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToUpcastyyAA12DomesticatedCcyAA5FeralCcF : $@convention(thin) (@guaranteed @callee_guaranteed (@guaranteed Feral) -> ()) -> @owned @callee_guaranteed (@guaranteed Domesticated) -> () // CHECK: bb0([[ARG:%.*]] : // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed (@guaranteed Feral) -> () to $@callee_guaranteed (@guaranteed Domesticated) -> (){{.*}} // CHECK: return [[FUNC]] func funcToUpcast(_ x: @escaping (Feral) -> ()) -> (Domesticated) -> () { return x } // ==== Optionals struct Trivial { let n: Int8 } class C { let n: Int8 init(n: Int8) { self.n = n } } struct Loadable { let c: C var n: Int8 { return c.n } init(n: Int8) { c = C(n: n) } } struct AddrOnly { let a: Any var n: Int8 { return a as! Int8 } init(n: Int8) { a = n } } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion19convOptionalTrivialyyAA0E0VADSgcF func convOptionalTrivial(_ t1: @escaping (Trivial?) -> Trivial) { // CHECK: function_ref @$s19function_conversion7TrivialVSgACIegyd_AcDIegyd_TR // CHECK: partial_apply let _: (Trivial) -> Trivial? = t1 // CHECK: function_ref @$s19function_conversion7TrivialVSgACIegyd_A2DIegyd_TR // CHECK: partial_apply let _: (Trivial?) -> Trivial? = t1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion7TrivialVSgACIegyd_AcDIegyd_TR : $@convention(thin) (Trivial, @guaranteed @callee_guaranteed (Optional<Trivial>) -> Trivial) -> Optional<Trivial> // CHECK: [[ENUM:%.*]] = enum $Optional<Trivial> // CHECK-NEXT: apply %1([[ENUM]]) // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion7TrivialVSgACIegyd_A2DIegyd_TR : $@convention(thin) (Optional<Trivial>, @guaranteed @callee_guaranteed (Optional<Trivial>) -> Trivial) -> Optional<Trivial> // CHECK: apply %1(%0) // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: return // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion20convOptionalLoadableyyAA0E0VADSgcF func convOptionalLoadable(_ l1: @escaping (Loadable?) -> Loadable) { // CHECK: function_ref @$s19function_conversion8LoadableVSgACIeggo_AcDIeggo_TR // CHECK: partial_apply let _: (Loadable) -> Loadable? = l1 // CHECK: function_ref @$s19function_conversion8LoadableVSgACIeggo_A2DIeggo_TR // CHECK: partial_apply let _: (Loadable?) -> Loadable? = l1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion8LoadableVSgACIeggo_A2DIeggo_TR : $@convention(thin) (@guaranteed Optional<Loadable>, @guaranteed @callee_guaranteed (@guaranteed Optional<Loadable>) -> @owned Loadable) -> @owned Optional<Loadable> // CHECK: apply %1(%0) // CHECK-NEXT: enum $Optional<Loadable> // CHECK-NEXT: return // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion20convOptionalAddrOnlyyyAA0eF0VADSgcF func convOptionalAddrOnly(_ a1: @escaping (AddrOnly?) -> AddrOnly) { // CHECK: function_ref @$s19function_conversion8AddrOnlyVSgACIegnr_A2DIegnr_TR // CHECK: partial_apply let _: (AddrOnly?) -> AddrOnly? = a1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion8AddrOnlyVSgACIegnr_A2DIegnr_TR : $@convention(thin) (@in_guaranteed Optional<AddrOnly>, @guaranteed @callee_guaranteed (@in_guaranteed Optional<AddrOnly>) -> @out AddrOnly) -> @out Optional<AddrOnly> // CHECK: [[TEMP:%.*]] = alloc_stack $AddrOnly // CHECK-NEXT: apply %2([[TEMP]], %1) // CHECK-NEXT: init_enum_data_addr %0 : $*Optional<AddrOnly> // CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*AddrOnly // CHECK-NEXT: inject_enum_addr %0 : $*Optional<AddrOnly> // CHECK-NEXT: tuple () // CHECK-NEXT: dealloc_stack {{.*}} : $*AddrOnly // CHECK-NEXT: return // ==== Existentials protocol Q { var n: Int8 { get } } protocol P : Q {} extension Trivial : P {} extension Loadable : P {} extension AddrOnly : P {} // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion22convExistentialTrivial_2t3yAA0E0VAA1Q_pc_AeaF_pSgctF func convExistentialTrivial(_ t2: @escaping (Q) -> Trivial, t3: @escaping (Q?) -> Trivial) { // CHECK: function_ref @$s19function_conversion1Q_pAA7TrivialVIegnd_AdA1P_pIegyr_TR // CHECK: partial_apply let _: (Trivial) -> P = t2 // CHECK: function_ref @$s19function_conversion1Q_pSgAA7TrivialVIegnd_AESgAA1P_pIegyr_TR // CHECK: partial_apply let _: (Trivial?) -> P = t3 // CHECK: function_ref @$s19function_conversion1Q_pAA7TrivialVIegnd_AA1P_pAaE_pIegnr_TR // CHECK: partial_apply let _: (P) -> P = t2 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pAA7TrivialVIegnd_AdA1P_pIegyr_TR : $@convention(thin) (Trivial, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> Trivial) -> @out P // CHECK: alloc_stack $Q // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK-NEXT: apply // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pSgAA7TrivialVIegnd_AESgAA1P_pIegyr_TR // CHECK: switch_enum // CHECK: bb1([[TRIVIAL:%.*]] : $Trivial): // CHECK: init_existential_addr // CHECK: init_enum_data_addr // CHECK: copy_addr // CHECK: inject_enum_addr // CHECK: bb2: // CHECK: inject_enum_addr // CHECK: bb3: // CHECK: apply // CHECK: init_existential_addr // CHECK: store // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pAA7TrivialVIegnd_AA1P_pAaE_pIegnr_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> Trivial) -> @out P // CHECK: [[TMP:%.*]] = alloc_stack $Q // CHECK-NEXT: open_existential_addr immutable_access %1 : $*P // CHECK-NEXT: init_existential_addr [[TMP]] : $*Q // CHECK-NEXT: copy_addr {{.*}} to [initialization] {{.*}} // CHECK-NEXT: apply // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK: destroy_addr // CHECK: return // ==== Existential metatypes // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion23convExistentialMetatypeyyAA7TrivialVmAA1Q_pXpSgcF func convExistentialMetatype(_ em: @escaping (Q.Type?) -> Trivial.Type) { // CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR // CHECK: partial_apply let _: (Trivial.Type) -> P.Type = em // CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtSgAA1P_pXmTIegyd_TR // CHECK: partial_apply let _: (Trivial.Type?) -> P.Type = em // CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AA1P_pXmTAaF_pXmTIegyd_TR // CHECK: partial_apply let _: (P.Type) -> P.Type = em } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR : $@convention(thin) (@thin Trivial.Type, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: [[META:%.*]] = metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype [[META]] : $@thick Trivial.Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK-NEXT: apply // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtSgAA1P_pXmTIegyd_TR : $@convention(thin) (Optional<@thin Trivial.Type>, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: switch_enum %0 : $Optional<@thin Trivial.Type> // CHECK: bb1([[META:%.*]] : $@thin Trivial.Type): // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK: bb2: // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK: bb3({{.*}}): // CHECK-NEXT: apply // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AA1P_pXmTAaF_pXmTIegyd_TR : $@convention(thin) (@thick P.Type, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: open_existential_metatype %0 : $@thick P.Type to $@thick (@opened({{.*}}) P).Type // CHECK-NEXT: init_existential_metatype %2 : $@thick (@opened({{.*}}) P).Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK-NEXT: apply %1 // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // ==== Class metatype upcasts class Parent {} class Child : Parent {} // Note: we add a Trivial => Trivial? conversion here to force a thunk // to be generated // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion18convUpcastMetatype_2c5yAA5ChildCmAA6ParentCm_AA7TrivialVSgtc_AEmAGmSg_AJtctF func convUpcastMetatype(_ c4: @escaping (Parent.Type, Trivial?) -> Child.Type, c5: @escaping (Parent.Type?, Trivial?) -> Child.Type) { // CHECK: function_ref @$s19function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR // CHECK: partial_apply let _: (Child.Type, Trivial) -> Parent.Type = c4 // CHECK: function_ref @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTAfCXMTIegyyd_TR // CHECK: partial_apply let _: (Child.Type, Trivial) -> Parent.Type = c5 // CHECK: function_ref @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTSgAfDIegyyd_TR // CHECK: partial_apply let _: (Child.Type?, Trivial) -> Parent.Type? = c5 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @guaranteed @callee_guaranteed (@thick Parent.Type, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type // CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTAfCXMTIegyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @guaranteed @callee_guaranteed (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type // CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: enum $Optional<@thick Parent.Type> // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTSgAfDIegyyd_TR : $@convention(thin) (Optional<@thick Child.Type>, Trivial, @guaranteed @callee_guaranteed (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> Optional<@thick Parent.Type> // CHECK: unchecked_trivial_bit_cast %0 : $Optional<@thick Child.Type> to $Optional<@thick Parent.Type> // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: enum $Optional<@thick Parent.Type> // CHECK: return // ==== Function to existential -- make sure we maximally abstract it // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion19convFuncExistentialyyS2icypcF : $@convention(thin) (@guaranteed @callee_guaranteed (@in_guaranteed Any) -> @owned @callee_guaranteed (Int) -> Int) -> () // CHECK: bb0([[ARG:%.*]] : // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @$sypS2iIegyd_Iegno_S2iIegyd_ypIeggr_TR : // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_THUNK]]([[ARG_COPY]]) // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '$s19function_conversion19convFuncExistentialyyS2icypcF' func convFuncExistential(_ f1: @escaping (Any) -> (Int) -> Int) { let _: (@escaping (Int) -> Int) -> Any = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sypS2iIegyd_Iegno_S2iIegyd_ypIeggr_TR : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int, @guaranteed @callee_guaranteed (@in_guaranteed Any) -> @owned @callee_guaranteed (Int) -> Int) -> @out Any { // CHECK: alloc_stack $Any // CHECK: function_ref @$sS2iIegyd_S2iIegnr_TR // CHECK-NEXT: [[COPIED_VAL:%.*]] = copy_value // CHECK-NEXT: partial_apply [callee_guaranteed] {{%.*}}([[COPIED_VAL]]) // CHECK-NEXT: init_existential_addr %3 : $*Any, $(Int) -> Int // CHECK-NEXT: store // CHECK-NEXT: apply // CHECK: function_ref @$sS2iIegyd_S2iIegnr_TR // CHECK-NEXT: partial_apply // CHECK-NEXT: init_existential_addr %0 : $*Any, $(Int) -> Int // CHECK-NEXT: store {{.*}} to {{.*}} : $*@callee_guaranteed (@in_guaranteed Int) -> @out Int // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sS2iIegyd_S2iIegnr_TR : $@convention(thin) (@in_guaranteed Int, @guaranteed @callee_guaranteed (Int) -> Int) -> @out Int // CHECK: [[LOADED:%.*]] = load [trivial] %1 : $*Int // CHECK-NEXT: apply %2([[LOADED]]) // CHECK-NEXT: store {{.*}} to [trivial] %0 // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK: return [[VOID]] // ==== Class-bound archetype upcast // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion29convClassBoundArchetypeUpcast{{[_0-9a-zA-Z]*}}F func convClassBoundArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent) -> (T, Trivial)) { // CHECK: function_ref @$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR // CHECK: partial_apply let _: (T) -> (Parent, Trivial?) = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR : $@convention(thin) <T where T : Parent> (@guaranteed T, @guaranteed @callee_guaranteed (@guaranteed Parent) -> (@owned T, Trivial)) -> (@owned Parent, Optional<Trivial>) // CHECK: bb0([[ARG:%.*]] : @guaranteed $T, [[CLOSURE:%.*]] : @guaranteed $@callee_guaranteed (@guaranteed Parent) -> (@owned T, Trivial)): // CHECK: [[CASTED_ARG:%.*]] = upcast [[ARG]] : $T to $Parent // CHECK: [[RESULT:%.*]] = apply %1([[CASTED_ARG]]) // CHECK: ([[LHS:%.*]], [[RHS:%.*]]) = destructure_tuple [[RESULT]] // CHECK: [[LHS_CAST:%.*]] = upcast [[LHS]] : $T to $Parent // CHECK: [[RHS_OPT:%.*]] = enum $Optional<Trivial>, #Optional.some!enumelt.1, [[RHS]] // CHECK: [[RESULT:%.*]] = tuple ([[LHS_CAST]] : $Parent, [[RHS_OPT]] : $Optional<Trivial>) // CHECK: return [[RESULT]] // CHECK: } // end sil function '$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR' // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion37convClassBoundMetatypeArchetypeUpcast{{[_0-9a-zA-Z]*}}F func convClassBoundMetatypeArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent.Type) -> (T.Type, Trivial)) { // CHECK: function_ref @$s19function_conversion6ParentCXMTxXMTAA7TrivialVIegydd_xXMTACXMTAESgIegydd_ACRbzlTR // CHECK: partial_apply let _: (T.Type) -> (Parent.Type, Trivial?) = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTxXMTAA7TrivialVIegydd_xXMTACXMTAESgIegydd_ACRbzlTR : $@convention(thin) <T where T : Parent> (@thick T.Type, @guaranteed @callee_guaranteed (@thick Parent.Type) -> (@thick T.Type, Trivial)) -> (@thick Parent.Type, Optional<Trivial>) // CHECK: bb0([[META:%.*]] : // CHECK: upcast %0 : $@thick T.Type // CHECK-NEXT: apply // CHECK-NEXT: destructure_tuple // CHECK-NEXT: upcast {{.*}} : $@thick T.Type to $@thick Parent.Type // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: tuple // CHECK-NEXT: return // ==== Make sure we destructure one-element tuples // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion15convTupleScalar_2f22f3yyAA1Q_pc_yAaE_pcySi_SitSgctF // CHECK: function_ref @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR // CHECK: function_ref @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR // CHECK: function_ref @$sSi_SitSgIegy_S2iIegyy_TR // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> ()) -> () // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sSi_SitSgIegy_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (Optional<(Int, Int)>) -> ()) -> () func convTupleScalar(_ f1: @escaping (Q) -> (), f2: @escaping (_ parent: Q) -> (), f3: @escaping (_ tuple: (Int, Int)?) -> ()) { let _: (P) -> () = f1 let _: (P) -> () = f2 let _: ((Int, Int)) -> () = f3 } func convTupleScalarOpaque<T>(_ f: @escaping (T...) -> ()) -> ((_ args: T...) -> ())? { return f } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> (Int, Int)) -> @owned @callee_guaranteed (Int) -> Optional<(Int, Int)> // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (Int) -> (Int, Int)): // CHECK: [[FN:%.*]] = copy_value [[ARG]] // CHECK: [[THUNK_FN:%.*]] = function_ref @$sS3iIegydd_S2i_SitSgIegyd_TR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[FN]]) // CHECK-NEXT: return [[THUNK]] // CHECK-NEXT: } // end sil function '$s19function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF' // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sS3iIegydd_S2i_SitSgIegyd_TR : $@convention(thin) (Int, @guaranteed @callee_guaranteed (Int) -> (Int, Int)) -> Optional<(Int, Int)> // CHECK: bb0(%0 : $Int, %1 : @guaranteed $@callee_guaranteed (Int) -> (Int, Int)): // CHECK: [[RESULT:%.*]] = apply %1(%0) // CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]] // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Int) // CHECK-NEXT: [[OPTIONAL:%.*]] = enum $Optional<(Int, Int)>, #Optional.some!enumelt.1, [[RESULT]] // CHECK-NEXT: return [[OPTIONAL]] // CHECK-NEXT: } // end sil function '$sS3iIegydd_S2i_SitSgIegyd_TR' func convTupleToOptionalDirect(_ f: @escaping (Int) -> (Int, Int)) -> (Int) -> (Int, Int)? { return f } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF : $@convention(thin) <T> (@guaranteed @callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)) -> @owned @callee_guaranteed (@in_guaranteed T) -> @out Optional<(T, T)> // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)): // CHECK: [[FN:%.*]] = copy_value [[ARG]] // CHECK: [[THUNK_FN:%.*]] = function_ref @$sxxxIegnrr_xx_xtSgIegnr_lTR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<T>([[FN]]) // CHECK-NEXT: return [[THUNK]] // CHECK-NEXT: } // end sil function '$s19function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF' // CHECK: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sxxxIegnrr_xx_xtSgIegnr_lTR : $@convention(thin) <T> (@in_guaranteed T, @guaranteed @callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)) -> @out Optional<(T, T)> // CHECK: bb0(%0 : $*Optional<(T, T)>, %1 : $*T, %2 : @guaranteed $@callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)): // CHECK: [[OPTIONAL:%.*]] = init_enum_data_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt.1 // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[OPTIONAL]] : $*(T, T), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[OPTIONAL]] : $*(T, T), 1 // CHECK-NEXT: apply %2([[LEFT]], [[RIGHT]], %1) // CHECK-NEXT: inject_enum_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt.1 // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK: return [[VOID]] func convTupleToOptionalIndirect<T>(_ f: @escaping (T) -> (T, T)) -> (T) -> (T, T)? { return f } // ==== Make sure we support AnyHashable erasure // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion15convAnyHashable1tyx_tSHRzlF // CHECK: function_ref @$s19function_conversion15convAnyHashable1tyx_tSHRzlFSbs0dE0V_AEtcfU_ // CHECK: function_ref @$ss11AnyHashableVABSbIegnnd_xxSbIegnnd_SHRzlTR // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$ss11AnyHashableVABSbIegnnd_xxSbIegnnd_SHRzlTR : $@convention(thin) <T where T : Hashable> (@in_guaranteed T, @in_guaranteed T, @guaranteed @callee_guaranteed (@in_guaranteed AnyHashable, @in_guaranteed AnyHashable) -> Bool) -> Bool // CHECK: alloc_stack $AnyHashable // CHECK: function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF // CHECK: apply {{.*}}<T> // CHECK: alloc_stack $AnyHashable // CHECK: function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF // CHECK: apply {{.*}}<T> // CHECK: return func convAnyHashable<T : Hashable>(t: T) { let fn: (T, T) -> Bool = { (x: AnyHashable, y: AnyHashable) in x == y } } // ==== Convert exploded tuples to Any or Optional<Any> // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12convTupleAnyyyyyc_Si_SitycyypcyypSgctF // CHECK: function_ref @$sIeg_ypIegr_TR // CHECK: partial_apply // CHECK: function_ref @$sIeg_ypSgIegr_TR // CHECK: partial_apply // CHECK: function_ref @$sS2iIegdd_ypIegr_TR // CHECK: partial_apply // CHECK: function_ref @$sS2iIegdd_ypSgIegr_TR // CHECK: partial_apply // CHECK: function_ref @$sypIegn_S2iIegyy_TR // CHECK: partial_apply // CHECK: function_ref @$sypSgIegn_S2iIegyy_TR // CHECK: partial_apply func convTupleAny(_ f1: @escaping () -> (), _ f2: @escaping () -> (Int, Int), _ f3: @escaping (Any) -> (), _ f4: @escaping (Any?) -> ()) { let _: () -> Any = f1 let _: () -> Any? = f1 let _: () -> Any = f2 let _: () -> Any? = f2 let _: ((Int, Int)) -> () = f3 let _: ((Int, Int)) -> () = f4 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sIeg_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Any // CHECK: init_existential_addr %0 : $*Any, $() // CHECK-NEXT: apply %1() // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sIeg_ypSgIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Optional<Any> // CHECK: [[ENUM_PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Optional<Any>, #Optional.some!enumelt.1 // CHECK-NEXT: init_existential_addr [[ENUM_PAYLOAD]] : $*Any, $() // CHECK-NEXT: apply %1() // CHECK-NEXT: inject_enum_addr %0 : $*Optional<Any>, #Optional.some!enumelt.1 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sS2iIegdd_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Any // CHECK: [[ANY_PAYLOAD:%.*]] = init_existential_addr %0 // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RESULT:%.*]] = apply %1() // CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]] // CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sS2iIegdd_ypSgIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Optional<Any> { // CHECK: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr %0 // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[OPTIONAL_PAYLOAD]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RESULT:%.*]] = apply %1() // CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]] // CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: inject_enum_addr %0 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sypIegn_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Any) -> ()) -> () // CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: apply %2([[ANY_VALUE]]) // CHECK-NEXT: tuple () // CHECK-NEXT: destroy_addr [[ANY_VALUE]] // CHECK-NEXT: dealloc_stack [[ANY_VALUE]] // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sypSgIegn_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Optional<Any>) -> ()) -> () // CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: [[OPTIONAL_VALUE:%.*]] = alloc_stack $Optional<Any> // CHECK-NEXT: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: copy_addr [take] [[ANY_VALUE]] to [initialization] [[OPTIONAL_PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: apply %2([[OPTIONAL_VALUE]]) // CHECK-NEXT: tuple () // CHECK-NEXT: destroy_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: dealloc_stack [[OPTIONAL_VALUE]] // CHECK-NEXT: dealloc_stack [[ANY_VALUE]] // CHECK-NEXT: return // ==== Support collection subtyping in function argument position protocol Z {} class A: Z {} func foo_arr<T: Z>(type: T.Type, _ fn: ([T]?) -> Void) {} func foo_map<T: Z>(type: T.Type, _ fn: ([Int: T]) -> Void) {} func rdar35702810() { let fn_arr: ([Z]?) -> Void = { _ in } let fn_map: ([Int: Z]) -> Void = { _ in } // CHECK: function_ref @$ss15_arrayForceCastySayq_GSayxGr0_lF : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1> // CHECK: apply %5<A, Z>(%4) : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1> foo_arr(type: A.self, fn_arr) // CHECK: function_ref @$ss17_dictionaryUpCastySDyq0_q1_GSDyxq_GSHRzSHR0_r2_lF : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3> // CHECK: apply %2<Int, A, Int, Z>(%0) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3> // CHECK: apply %1(%4) : $@callee_guaranteed (@guaranteed Dictionary<Int, Z>) -> () foo_map(type: A.self, fn_map) } protocol X: Hashable {} class B: X { func hash(into hasher: inout Hasher) {} static func == (lhs: B, rhs: B) -> Bool { return true } } func bar_arr<T: X>(type: T.Type, _ fn: ([T]?) -> Void) {} func bar_map<T: X>(type: T.Type, _ fn: ([T: Int]) -> Void) {} func bar_set<T: X>(type: T.Type, _ fn: (Set<T>) -> Void) {} func rdar35702810_anyhashable() { let fn_arr: ([AnyHashable]?) -> Void = { _ in } let fn_map: ([AnyHashable: Int]) -> Void = { _ in } let fn_set: (Set<AnyHashable>) -> Void = { _ in } // CHECK: [[FN:%.*]] = function_ref @$sSays11AnyHashableVGSgIegg_Say19function_conversion1BCGSgIegg_TR : $@convention(thin) (@guaranteed Optional<Array<B>>, @guaranteed @callee_guaranteed (@guaranteed Optional<Array<AnyHashable>>) -> ()) -> () // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Optional<Array<B>>, @guaranteed @callee_guaranteed (@guaranteed Optional<Array<AnyHashable>>) -> ()) -> () // CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Optional<Array<B>>) -> () to $@noescape @callee_guaranteed (@guaranteed Optional<Array<B>>) -> () bar_arr(type: B.self, fn_arr) // CHECK: [[FN:%.*]] = function_ref @$sSDys11AnyHashableVSiGIegg_SDy19function_conversion1BCSiGIegg_TR : $@convention(thin) (@guaranteed Dictionary<B, Int>, @guaranteed @callee_guaranteed (@guaranteed Dictionary<AnyHashable, Int>) -> ()) -> () // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Dictionary<B, Int>, @guaranteed @callee_guaranteed (@guaranteed Dictionary<AnyHashable, Int>) -> ()) -> () // CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Dictionary<B, Int>) -> () to $@noescape @callee_guaranteed (@guaranteed Dictionary<B, Int>) -> () bar_map(type: B.self, fn_map) // CHECK: [[FN:%.*]] = function_ref @$sShys11AnyHashableVGIegg_Shy19function_conversion1BCGIegg_TR : $@convention(thin) (@guaranteed Set<B>, @guaranteed @callee_guaranteed (@guaranteed Set<AnyHashable>) -> ()) -> () // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Set<B>, @guaranteed @callee_guaranteed (@guaranteed Set<AnyHashable>) -> ()) -> () // CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Set<B>) -> () to $@noescape @callee_guaranteed (@guaranteed Set<B>) -> () bar_set(type: B.self, fn_set) } // ==== Function conversion with parameter substToOrig reabstraction. struct FunctionConversionParameterSubstToOrigReabstractionTest { typealias SelfTy = FunctionConversionParameterSubstToOrigReabstractionTest class Klass: Error {} struct Foo<T> { static func enum1Func(_ : (T) -> Foo<Error>) -> Foo<Error> { // Just to make it compile. return Optional<Foo<Error>>.none! } } static func bar<T>(t: T) -> Foo<T> { // Just to make it compile. return Optional<Foo<T>>.none! } static func testFunc() -> Foo<Error> { return Foo<Klass>.enum1Func(SelfTy.bar) } } // CHECK: sil {{.*}} [ossa] @$sS4SIgggoo_S2Ss11AnyHashableVyps5Error_pIegggrrzo_TR // CHECK: [[TUPLE:%.*]] = apply %4(%2, %3) : $@noescape @callee_guaranteed (@guaranteed String, @guaranteed String) -> (@owned String, @owned String) // CHECK: ([[LHS:%.*]], [[RHS:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: [[ADDR:%.*]] = alloc_stack $String // CHECK: store [[LHS]] to [init] [[ADDR]] : $*String // CHECK: [[CVT:%.*]] = function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF : $@convention(thin) <τ_0_0 where τ_0_0 : Hashable> (@in_guaranteed τ_0_0) -> @out AnyHashable // CHECK: apply [[CVT]]<String>(%0, [[ADDR]]) // CHECK: } // end sil function '$sS4SIgggoo_S2Ss11AnyHashableVyps5Error_pIegggrrzo_TR' func dontCrash() { let userInfo = ["hello": "world"] let d = [AnyHashable: Any](uniqueKeysWithValues: userInfo.map { ($0.key, $0.value) }) }
apache-2.0
ab5895c0da7ec9bdfc0aad22a71b9a6a
53.599407
368
0.643668
3.33696
false
false
false
false
blkbrds/intern09_final_project_tung_bien
MyApp/ViewModel/Cart/CartViewModel.swift
1
3481
// // CartViewModel.swift // MyApp // // Created by AST on 8/9/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import Foundation import MVVM import SwiftUtils import RealmS import RealmSwift final class CartViewModel: MVVM.ViewModel { // MARK: - Properties typealias SendOrderCompletion = (GetResult) -> Void typealias GetCurrentBalanceCompletion = (GetResult) -> Void private var cartItems: Results<CartItem>? private var totalOrder: Double = 0 private var currentBalance: Double = 0 enum GetResult { case success case failure(Error) } // MARK: - Public func numberOfSections() -> Int { guard let _ = cartItems else { return 0 } return 1 } func numberOfItems(inSection section: Int) -> Int { guard let items = cartItems else { return 0 } return items.count } func viewModelForItem(at indexPath: IndexPath) -> CartCellViewModel { guard let items = cartItems else { fatalError("Not have food in cart") } if indexPath.row < items.count { let item = items[indexPath.row] return CartCellViewModel(item: item) } return CartCellViewModel(item: nil) } func fetchCartItem() { cartItems = RealmS().objects(CartItem.self) } func cartItemIsEmpty() -> Bool { guard let cartItems = cartItems else { return true } return cartItems.isEmpty } func caculateTotal() { guard let carts = cartItems else { return } var total: Double = 0 for item in carts { total += item.price * Double(item.quantity) } totalOrder = total } /** Function for ConfirmView */ func fetchCurrentBalance(completion: @escaping GetCurrentBalanceCompletion) { Api.Profile.query { [weak self] (result) in guard let this = self else { return } switch result { case .success(let value): guard let profile = value as? Profile else { return } this.currentBalance = profile.balance completion(.success) case .failure(let error): completion(.failure(error)) } } } func getCurrentBalance() -> Double { return currentBalance } func getRemainingBalance() -> Double { caculateTotal() return currentBalance - totalOrder } func getTotalOrder() -> Double { caculateTotal() return totalOrder } func sendOrderToServer(completion: @escaping SendOrderCompletion) { guard let cartItems = cartItems else { return } var data: [JSObject] = [] for item in cartItems { let temp: JSObject = ["menuItemId": item.id, "quantity": item.quantity] data.append(temp) } let param = Api.Order.OrderParams(data: data, shopId: 1) Api.Order.query(params: param) { (result) in switch result { case .success(_): completion(.success) case .failure(let error): completion(.failure(error)) } } } func sendedToServer() { let realm = RealmS() realm.write { guard let cartItems = cartItems else { return } realm.delete(cartItems) } } }
mit
a3a7c840f1bab7852bcdff58785744ee
25.165414
83
0.57069
4.741144
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/ACAcademy.swift
1
3315
// // ACAcademy.swift // AwesomeCore // // Created by Antonio da Silva on 29/08/2017. // import Foundation public struct ACAcademy: Equatable { public let id: Int public let domain: String public let name: String public let type: String public let subscription: Bool public let awcProductId: String public let themeColor: String public let tribeLearnTribeId: String public let courseOrdering: String public let authors: [ACAuthor] public let numberOfCourses: Int public let featuredCourseId: Int public let coverPhotoURL: String public let courseCoverImages: [String] public let purchased: Bool public let purchasedAt: Date? public init(id: Int, domain: String, name:String, type: String, subscription: Bool, awcProductId: String, themeColor:String, tribeLearnTribeId: String, courseOrdering: String, authors: [ACAuthor], numberOfCourses: Int, featuredCourseId: Int, coverPhotoURL: String, courseCoverImages: [String], purchased: Bool, purchasedAt: Date?) { self.id = id self.domain = domain self.name = name self.type = type self.subscription = subscription self.awcProductId = awcProductId self.themeColor = themeColor self.tribeLearnTribeId = tribeLearnTribeId self.courseOrdering = courseOrdering self.authors = authors.sorted(by: {$0.name < $1.name}) self.numberOfCourses = numberOfCourses self.featuredCourseId = featuredCourseId self.coverPhotoURL = coverPhotoURL self.courseCoverImages = courseCoverImages.sorted(by: { $0 < $1 }) self.purchased = purchased self.purchasedAt = purchasedAt } } // MARK: - Equatable extension ACAcademy { public static func ==(lhs: ACAcademy, rhs: ACAcademy) -> Bool { if lhs.id != rhs.id { return false } if lhs.domain != rhs.domain { return false } if lhs.name != rhs.name { return false } if lhs.type != rhs.type { return false } if lhs.subscription != rhs.subscription { return false } if lhs.awcProductId != rhs.awcProductId { return false } if lhs.themeColor != rhs.themeColor { return false } if lhs.tribeLearnTribeId != rhs.tribeLearnTribeId { return false } if lhs.courseOrdering != rhs.courseOrdering { return false } if lhs.authors != rhs.authors { return false } if lhs.numberOfCourses != rhs.numberOfCourses { return false } if lhs.featuredCourseId != rhs.featuredCourseId { return false } if lhs.coverPhotoURL != rhs.coverPhotoURL { return false } if lhs.courseCoverImages != rhs.courseCoverImages { return false } if lhs.purchased != rhs.purchased { return false } if lhs.purchasedAt != rhs.purchasedAt { return false } return true } }
mit
2add6f8c4ac8e488d31fe09795b832a8
26.625
74
0.578884
4.47973
false
false
false
false
ajijoyo/xmppBuildChat
HiBro/HiBro/chatViewController.swift
1
3363
// // chatViewController.swift // HiBro // // Created by Dealjava on 12/2/15. // Copyright © 2015 dealjava. All rights reserved. // import UIKit import Foundation class chatViewController: UIViewController ,xmppMessageDelegate ,UITableViewDelegate,UITableViewDataSource , UITextFieldDelegate{ @IBOutlet weak var msgTextField : UITextField! @IBOutlet weak var myTable : UITableView! internal var toChatName = "" let xmpp = xmppClientAppDelegate.sharedInstance private var chatM : [AnyObject] = [] { didSet{ self.myTable.reloadData() } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) navigationItem.title = toChatName } override func viewDidLoad() { super.viewDidLoad() xmpp.registration() msgTextField.delegate = self xmpp.messageDelegate = self myTable.estimatedRowHeight = 20 myTable.rowHeight = UITableViewAutomaticDimension; let hidekeyTap = UITapGestureRecognizer(target: self, action: "hidekey") myTable.addGestureRecognizer(hidekeyTap) } func hidekey(){ msgTextField.resignFirstResponder() } //MARK: - uitextfield delegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } //MARK: uitableview func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return chatM.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell! cell.textLabel?.frame = cell.contentView.bounds cell.textLabel?.numberOfLines = 0 if let dic = chatM[indexPath.row] as? [String : String] { cell.textLabel?.text = dic["msg"] if dic["sender"] == xmpp.xmppStream?.myJID.user { cell.textLabel?.textAlignment = NSTextAlignment.Left }else{ cell.textLabel?.textAlignment = NSTextAlignment.Right } } return cell } @IBAction func sendBttnListener(){ if let notNull = msgTextField.text { sendMessage(notNull) }else{ Log.D("Kosong") } } func sendMessage(msg : String){ let body = DDXMLElement(name: "body") body.setStringValue(msg) let message = DDXMLElement(name: "message") message.addAttributeWithName("type", stringValue: "chat") message.addAttributeWithName("to", stringValue: toChatName) message.addChild(body) xmpp.xmppStream?.sendElement(message) msgTextField.text = "" chatM.append(["msg":msg,"sender":xmpp.xmppStream!.myJID.user]) } func MESSAGEnewMessageReceive(message: AnyObject) { chatM.append(message) } //MARK: - memory managment deinit{ chatM.removeAll() toChatName = "" } override func didReceiveMemoryWarning() { } }
mit
bc2b1e7cf887586cc5191cc419cfee1f
27.016667
129
0.614813
5.063253
false
false
false
false
harlanhaskins/Swifter-1
Sources/String++.swift
1
2859
// // String+Swifter.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension String { internal func indexOf(_ sub: String) -> Int? { guard let range = self.range(of: sub), !range.isEmpty else { return nil } return self.characters.distance(from: self.startIndex, to: range.lowerBound) } internal subscript (r: Range<Int>) -> String { get { let startIndex = self.characters.index(self.startIndex, offsetBy: r.lowerBound) let endIndex = self.characters.index(startIndex, offsetBy: r.upperBound - r.lowerBound) return self[startIndex..<endIndex] } } func urlEncodedString(_ encodeAll: Bool = false) -> String { var allowedCharacterSet: CharacterSet = .urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\n:#/?@!$&'()*+,;=") if !encodeAll { allowedCharacterSet.insert(charactersIn: "[]") } return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)! } var queryStringParameters: Dictionary<String, String> { var parameters = Dictionary<String, String>() let scanner = Scanner(string: self) var key: NSString? var value: NSString? while !scanner.isAtEnd { key = nil scanner.scanUpTo("=", into: &key) scanner.scanString("=", into: nil) value = nil scanner.scanUpTo("&", into: &value) scanner.scanString("&", into: nil) if let key = key as String?, let value = value as String? { parameters.updateValue(value, forKey: key) } } return parameters } }
mit
fa803f3de83d9513dafa0e106ba995ab
34.296296
99
0.649878
4.671569
false
false
false
false
crossroadlabs/Boilerplate
Sources/Boilerplate/String.swift
2
6899
//===--- String.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import Foundation #if swift(>=3.0) #else public extension String { public func substring(from index: Index) -> String { return substringFromIndex(index) } public func substring(to index: Index) -> String { return substringToIndex(index) } public func substring(with range: Range<String.Index>) -> String { return substringWithRange(range) } } #endif #if swift(>=3.0) #else public extension String { /// Return `self` converted to lower case. /// /// - Complexity: O(n) public func lowercased() -> String { return lowercaseString } /// Return `self` converted to upper case. /// /// - Complexity: O(n) public func uppercased() -> String { return uppercaseString } } extension String { /// Create a new `String` by copying the nul-terminated UTF-8 data /// referenced by a `cString`. /// /// If `cString` contains ill-formed UTF-8 code unit sequences, replaces them /// with replacement characters (U+FFFD). /// /// - Precondition: `cString != nil` public init(cString: UnsafePointer<CChar>) { // Must crash if cString is nil self = String.fromCStringRepairingIllFormedUTF8(cString).0! } /// Create a new `String` by copying the nul-terminated UTF-8 data /// referenced by a `cString`. /// /// Does not try to repair ill-formed UTF-8 code unit sequences, fails if any /// such sequences are found. /// /// - Precondition: `cString != nil` public init?(validatingUTF8 cString: UnsafePointer<CChar>) { if cString == .null { CommonRuntimeError.PreconditionFailed(description: "cString is nil").panic() } else { guard let string = String.fromCString(cString) else { return nil } self = string } } /// Create a new `String` by copying the nul-terminated data /// referenced by a `cString` using `encoding`. /// /// Returns `nil` if the `cString` is `NULL` or if it contains ill-formed code /// units and no repairing has been requested. Otherwise replaces /// ill-formed code units with replacement characters (U+FFFD). /*public static func decodeCString<Encoding : UnicodeCodec>(cString: UnsafePointer<Encoding.CodeUnit>, as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = false) -> (result: String, repairsMade: Bool)? { //Too much work for now }*/ } extension String { public mutating func append<S : Sequence where S.Generator.Element == Character>(contentsOf newElements: S) { self.appendContentsOf(newElements) } public mutating func append(string: String) { self.appendContentsOf(string) } } extension String { /// Insert `newElement` at position `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). public mutating func insert(newElement: Character, at i: Index) { self.insert(newElement, atIndex: i) } /// Insert `newElements` at position `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count + newElements.count`). public mutating func insert<S : Collection where S.Generator.Element == Character>(contentsOf newElements: S, at i: Index) { self.insertContentsOf(newElements, at: i) } /// Remove and return the `Character` at position `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). public mutating func remove(at i: Index) -> Character { return self.removeAtIndex(i) } /// Replace `self` with the empty string. /// /// Invalidates all indices with respect to `self`. /// /// - parameter keepCapacity: If `true`, prevents the release of /// allocated storage, which can be a useful optimization /// when `self` is going to be grown again. public mutating func removeAll(keepingCapacity keepCapacity: Bool = true) { self.removeAll(keepCapacity: keepCapacity) } } public typealias UnicodeCodec = UnicodeCodecType public extension UnicodeCodec { /// Encode a `UnicodeScalar` as a series of `CodeUnit`s by /// calling `output` on each `CodeUnit`. public static func encode(input: UnicodeScalar, sendingOutputTo processCodeUnit: (CodeUnit) -> Swift.Void) { self.encode(input, output: processCodeUnit) } } public extension String { /// A type used to represent the number of steps between two `String.Index` /// values, where one value is reachable from the other. /// /// In Swift, *reachability* refers to the ability to produce one value from /// the other through zero or more applications of `index(after:)`. public typealias IndexDistance = Int public func index(after i: Index) -> Index { return i.successor() } public func index(before i: Index) -> Index { return i.predecessor() } public func index(i: Index, offsetBy n: IndexDistance) -> Index { return i.advanced(by: n) } public func index(i: Index, offsetBy n: IndexDistance, limitedBy limit: Index) -> Index? { return i.advancedBy(n, limit: limit) } public func distance(from start: Index, to end: Index) -> IndexDistance { return start.distance(to: end) } } #endif
apache-2.0
6f60638b177d4ad812dca07c6f69b81b
35.696809
233
0.572257
5.013808
false
false
false
false
esttorhe/Moya
Source/Plugins/NetworkLoggerPlugin.swift
2
4220
import Foundation import Result /// Logs network activity (outgoing requests and incoming responses). public final class NetworkLoggerPlugin: PluginType { private let loggerId = "Moya_Logger" private let dateFormatString = "dd/MM/yyyy HH:mm:ss" private let dateFormatter = NSDateFormatter() private let separator = ", " private let terminator = "\n" private let cURLTerminator = "\\\n" private let output: (items: Any..., separator: String, terminator: String) -> Void private let responseDataFormatter: ((NSData) -> (NSData))? /// If true, also logs response body data. public let verbose: Bool public let cURL: Bool public init(verbose: Bool = false, cURL: Bool = false, output: (items: Any..., separator: String, terminator: String) -> Void = print, responseDataFormatter: ((NSData) -> (NSData))? = nil) { self.cURL = cURL self.verbose = verbose self.output = output self.responseDataFormatter = responseDataFormatter } public func willSendRequest(request: RequestType, target: TargetType) { if let request = request as? CustomDebugStringConvertible where cURL { output(items: request.debugDescription, separator: separator, terminator: terminator) return } outputItems(logNetworkRequest(request.request)) } public func didReceiveResponse(result: Result<Moya.Response, Moya.Error>, target: TargetType) { if case .Success(let response) = result { outputItems(logNetworkResponse(response.response, data: response.data, target: target)) } else { outputItems(logNetworkResponse(nil, data: nil, target: target)) } } private func outputItems(items: [String]) { if verbose { items.forEach { output(items: $0, separator: separator, terminator: terminator) } } else { output(items: items, separator: separator, terminator: terminator) } } } private extension NetworkLoggerPlugin { private var date: String { dateFormatter.dateFormat = dateFormatString dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return dateFormatter.stringFromDate(NSDate()) } private func format(loggerId: String, date: String, identifier: String, message: String) -> String { return "\(loggerId): [\(date)] \(identifier): \(message)" } func logNetworkRequest(request: NSURLRequest?) -> [String] { var output = [String]() output += [format(loggerId, date: date, identifier: "Request", message: request?.description ?? "(invalid request)")] if let headers = request?.allHTTPHeaderFields { output += [format(loggerId, date: date, identifier: "Request Headers", message: headers.description)] } if let bodyStream = request?.HTTPBodyStream { output += [format(loggerId, date: date, identifier: "Request Body Stream", message: bodyStream.description)] } if let httpMethod = request?.HTTPMethod { output += [format(loggerId, date: date, identifier: "HTTP Request Method", message: httpMethod)] } if let body = request?.HTTPBody where verbose == true { if let stringOutput = NSString(data: body, encoding: NSUTF8StringEncoding) as? String { output += [format(loggerId, date: date, identifier: "Request Body", message: stringOutput)] } } return output } func logNetworkResponse(response: NSURLResponse?, data: NSData?, target: TargetType) -> [String] { guard let response = response else { return [format(loggerId, date: date, identifier: "Response", message: "Received empty network response for \(target).")] } var output = [String]() output += [format(loggerId, date: date, identifier: "Response", message: response.description)] if let data = data where verbose == true { if let stringData = String(data: responseDataFormatter?(data) ?? data , encoding: NSUTF8StringEncoding) { output += [stringData] } } return output } }
mit
386d299f3ce6d0288b66b42ad0547977
38.074074
194
0.64218
4.850575
false
false
false
false
TsuiOS/LoveFreshBeen
LoveFreshBeenX/Class/View/Home/XNBuyView.swift
1
5577
// // XNBuyView.swift // LoveFreshBeenX // // Created by xuning on 16/6/25. // Copyright © 2016年 hus. All rights reserved. // import UIKit private extension Selector { static let addGoodsButtonClick = #selector(XNBuyView.addGoodsButtonClick) static let reduceGoodsButtonClick = #selector(XNBuyView.reduceGoodsButtonClick) } class XNBuyView: UIView { /// 添加按钮 private lazy var addGoodsButton: UIButton = { let addGoodsButton = UIButton(type: .Custom) addGoodsButton.setImage(UIImage(named: "v2_increase"), forState: .Normal) addGoodsButton.addTarget(self, action: .addGoodsButtonClick, forControlEvents: .TouchUpInside) return addGoodsButton }() /// 删除按钮 private lazy var reduceGoodsButton: UIButton = { let reduceGoodsButton = UIButton(type: .Custom) reduceGoodsButton.setImage(UIImage(named: "v2_reduce"), forState: .Normal) reduceGoodsButton.addTarget(self, action: .reduceGoodsButtonClick, forControlEvents: .TouchUpInside) reduceGoodsButton.hidden = true return reduceGoodsButton }() /// 购买数量 private lazy var buyCountLabel: UILabel = { let buyCountLabel = UILabel() buyCountLabel.hidden = true buyCountLabel.textColor = UIColor.blackColor() buyCountLabel.textAlignment = .Center buyCountLabel.font = HomeCollectionTextFont return buyCountLabel }() /// 补货中 private lazy var supplementLabel: UILabel = { let supplementLabel = UILabel() supplementLabel.text = "补货中" supplementLabel.hidden = true supplementLabel.textColor = UIColor.redColor() supplementLabel.textAlignment = .Right supplementLabel.font = HomeCollectionTextFont return supplementLabel }() private var buyNumber: Int = 0 { willSet { if newValue > 0 { reduceGoodsButton.hidden = false buyCountLabel.text = "\(newValue)" } else { reduceGoodsButton.hidden = true buyCountLabel.hidden = false buyCountLabel.text = "\(newValue)" } } } override init(frame: CGRect) { super.init(frame: frame) addSubview(addGoodsButton) addSubview(reduceGoodsButton) addSubview(buyCountLabel) addSubview(supplementLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let bugCountWidth: CGFloat = 25 addGoodsButton.snp_makeConstraints { (make) in make.top.right.bottom.equalTo(self) } buyCountLabel.snp_makeConstraints { (make) in make.top.bottom.equalTo(self) make.right.equalTo(addGoodsButton.snp_left) make.width.equalTo(bugCountWidth) } reduceGoodsButton.snp_makeConstraints { (make) in make.right.equalTo(buyCountLabel.snp_left) make.top.equalTo(addGoodsButton) } supplementLabel.snp_makeConstraints { (make) in make.top.right.bottom.equalTo(self) } } /// 商品模型set方法 var goods: XNGoods? { didSet { buyNumber = goods!.userBuyNumber if goods?.number <= 0 { showSupplementLabel() } else { hideSupplementLabel() } if buyNumber == 0 { reduceGoodsButton.hidden = true buyCountLabel.hidden = true }else { reduceGoodsButton.hidden = false buyCountLabel.hidden = false } } } /// 显示补货中 private func showSupplementLabel() { supplementLabel.hidden = false addGoodsButton.hidden = true reduceGoodsButton.hidden = true buyCountLabel.hidden = true } /// 隐藏补货中,显示添加按钮 private func hideSupplementLabel() { supplementLabel.hidden = true addGoodsButton.hidden = false reduceGoodsButton.hidden = false buyCountLabel.hidden = false } //MARK: - action func addGoodsButtonClick() { if buyNumber >= goods?.number { NSNotificationCenter.defaultCenter().postNotificationName(GoodsInventoryProblem, object: goods?.name) return } reduceGoodsButton.hidden = false buyNumber += 1 goods?.userBuyNumber = buyNumber buyCountLabel.text = "\(buyNumber)" buyCountLabel.hidden = false XNUserShopCarTool.sharedUserShopCar.addSupermarkProductToShopCar(goods!) NSNotificationCenter.defaultCenter().postNotificationName(LFBShopCarBuyNumberDidChangeNotification, object: nil) } func reduceGoodsButtonClick() { if buyNumber <= 0 { return } buyNumber -= 1 if buyNumber == 0 { reduceGoodsButton.hidden = true buyCountLabel.hidden = true buyCountLabel.text = "" } else { buyCountLabel.text = "\(buyNumber)" } NSNotificationCenter.defaultCenter().postNotificationName(LFBShopCarBuyNumberDidChangeNotification, object: nil) } }
mit
3ca086ebdd625920d6dc0ed4b59db592
28.379679
121
0.595923
4.802448
false
false
false
false
MakeSchool/TripPlanner
TripPlanner/Networking/API Clients/TripPlannerClient.swift
1
5239
// // TripPlannerClient.swift // TripPlanner // // Created by Benjamin Encz on 9/7/15. // Copyright © 2015 Make School. All rights reserved. // import Foundation import Result import CoreLocation typealias FetchTripsCallback = Result<[JSONTrip], Reason> -> Void typealias UploadTripCallback = Result<JSONTrip, Reason> -> Void typealias UpdateTripCallback = Result<JSONTrip, Reason> -> Void typealias DeleteTripCallback = Result<JSONTripDeletionResponse, Reason> -> Void class TripPlannerClient { static let baseURL = "http://127.0.0.1:5000/" let urlSession: NSURLSession init(urlSession: NSURLSession = NSURLSession.sharedSession()) { self.urlSession = urlSession } func fetchTrips(callback: FetchTripsCallback) { let resource: Resource<[JSONTrip]> = Resource( baseURL: TripPlannerClient.baseURL, path: "trip/", queryString: nil, method: .GET, requestBody: nil, headers: ["Authorization": BasicAuth.generateBasicAuthHeader("user", password: "password")], parse: parse ) let client = HTTPClient() client.apiRequest(self.urlSession, resource: resource, failure: { (reason: Reason, data: NSData?) -> () in dispatch_async(dispatch_get_main_queue()) { callback(.Failure(reason)) } }) { (trips: [JSONTrip]) in dispatch_async(dispatch_get_main_queue()) { callback(.Success(trips)) } } } func createDeleteTripRequest(tripServerID: TripServerID) -> TripPlannerClientDeleteTripRequest { let resource: Resource<JSONTripDeletionResponse> = Resource( baseURL: TripPlannerClient.baseURL, path: "trip/\(tripServerID)", queryString: nil, method: .DELETE, requestBody: nil, headers: ["Authorization": BasicAuth.generateBasicAuthHeader("user", password: "password")], parse: parse ) return TripPlannerClientDeleteTripRequest(resource: resource, tripServerID: tripServerID) } func createUpdateTripRequest(trip: Trip) -> TripPlannerClientUpdateTripRequest { let resource: Resource<JSONTrip> = Resource( baseURL: TripPlannerClient.baseURL, path: "trip/\(trip.serverID!)", queryString: nil, method: .PUT, requestBody: JSONEncoding.encodeJSONTrip(trip), headers: ["Authorization": BasicAuth.generateBasicAuthHeader("user", password: "password"), "Content-Type": "application/json"], parse: parse ) return TripPlannerClientUpdateTripRequest(resource: resource, trip: trip) } func createCreateTripRequest(trip: Trip) -> TripPlannerClientCreateTripRequest { let resource: Resource<JSONTrip> = Resource( baseURL: TripPlannerClient.baseURL, path: "trip/", queryString: nil, method: .POST, requestBody: JSONEncoding.encodeJSONTrip(trip), headers: ["Authorization": BasicAuth.generateBasicAuthHeader("user", password: "password"), "Content-Type": "application/json"], parse: parse ) return TripPlannerClientCreateTripRequest(resource: resource, trip: trip) } } // TODO: reduce redundancy class TripPlannerClientDeleteTripRequest { var resource: Resource<JSONTripDeletionResponse> var tripServerID: TripServerID required init(resource: Resource<JSONTripDeletionResponse>, tripServerID: TripServerID) { self.resource = resource self.tripServerID = tripServerID } func perform(urlSession: NSURLSession, callback: DeleteTripCallback) { let client = HTTPClient() client.apiRequest(urlSession, resource: resource, failure: { (reason: Reason, data: NSData?) -> () in dispatch_async(dispatch_get_main_queue()) { callback(.Failure(reason)) } }) { (deletedTripResponse: JSONTripDeletionResponse) in dispatch_async(dispatch_get_main_queue()) { callback(.Success(deletedTripResponse)) } } } } class TripPlannerClientCreateTripRequest { var resource: Resource<JSONTrip> var trip: Trip required init(resource: Resource<JSONTrip>, trip: Trip) { self.resource = resource self.trip = trip } func perform(urlSession: NSURLSession, callback: UploadTripCallback) { let client = HTTPClient() client.apiRequest(urlSession, resource: resource, failure: { (reason: Reason, data: NSData?) -> () in dispatch_async(dispatch_get_main_queue()) { callback(.Failure(reason)) } }) { (uploadedTrip: JSONTrip) in dispatch_async(dispatch_get_main_queue()) { callback(.Success(uploadedTrip)) } } } } class TripPlannerClientUpdateTripRequest { var resource: Resource<JSONTrip> var trip: Trip required init(resource: Resource<JSONTrip>, trip: Trip) { self.resource = resource self.trip = trip } func perform(urlSession: NSURLSession, callback: UpdateTripCallback) { let client = HTTPClient() client.apiRequest(urlSession, resource: resource, failure: { (reason: Reason, data: NSData?) -> () in dispatch_async(dispatch_get_main_queue()) { callback(.Failure(reason)) } }) { (updatedTrip: JSONTrip) in dispatch_async(dispatch_get_main_queue()) { callback(.Success(updatedTrip)) } } } }
mit
74a6f6947fd273b50e2e39f5c75d61e3
30.945122
134
0.682894
4.234438
false
false
false
false
WebAPIKit/WebAPIKit
Tests/WebAPIKitTests/Stub/StubTemplateSpec.swift
1
1643
/** * WebAPIKit * * Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows: * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import Foundation import Quick import Nimble import WebAPIKit class StubTemplateSpec: QuickSpec { override func spec() { it("parse variables") { let template = StubPathTemplate("/api/v{version}/{owner}/{repo}/tags") let path = "/api/v3/me/test/tags" expect(template.match(path)) == true expect(template.parse(path)) == ["version": "3", "owner": "me", "repo": "test"] } } }
mit
a41f9bd33d833e0d2ef5a6d3e27f2f06
37.209302
91
0.701765
4.180662
false
false
false
false
vmachiel/swift
LearningSwift.playground/Pages/String Extra.xcplaygroundpage/Contents.swift
1
3211
// Strings are made off Unicodes, but there are also Character s // Characters is what a human would see a a char. // In Swift 4+, each char counts as one. // Counting chars let testEmoji: String = "👨‍👩‍👧" testEmoji.count // 4+ for char in testEmoji { print(char) } // Basic string stuff var s = "hello there" for c in s { print(c) // 11 } let count = s.count // Put characters of string in an Array: let charArray = Array(s) // Indexing // Find the index of a certain char let firstSpace: String.Index = s.firstIndex(of: " ")! // This returns an optional in case there is no space. // You can use this to perform useful actions actions: If space is found, // insert something there if let firstSpace = s.firstIndex(of: " ") { // insert collection of characters at an index s.insert(contentsOf: " you", at: firstSpace) } print(s) // Getting a char can be done with [] but the index is not an int! // It's actually a String.Index. This is because it counts human understandable // caracters, which can be made up of different unicode points. // Strings have properties called startIndex and endIndex of type String.Index // If string is empty, these are equal. // Types are added for clarity let s2: String = "hello" let firstIndex: String.Index = s2.startIndex // NOT AN INT! let firstChar: Character = s2[firstIndex] // Get a index after a certain one: let secondIndex: String.Index = s2.index(after: firstIndex) let secondChar: Character = s2[secondIndex] // Jump ahead and write it shorter: let fifthChar: Character = s2[s2.index(firstIndex, offsetBy: 4)] // And use ranges of String.Index let firstTwoChars = s2[firstIndex ... secondIndex] // String is a valuetype!!! So if you do let s = "hello" you can't mutate! let hello = "hello" // hello += "there" can't be done var greeting = hello greeting += " there" // Some more stuff with UTF-8 let dogString = "Dog‼🐶" dogString.count // 3 letter, one double ! and emoji for codeUnit in dogString.utf8 { print("\(codeUnit) ", terminator: "") } // String slicing creates a new type!! let someStringToSlice = "One,Two,Three" let listOfSlices = someStringToSlice.split(separator: ",") // Its type is a substring: type(of: listOfSlices) // This is because of ARC: if it was a regular string you would have two refferences, // to the original string: one from someStringToSlice, and one from listOfSlices. // If the original strings goes out of scope, the whole string would be kept in // memory. This can be bad if you are slicing small parts out of HUGE strings. So you // can copy on write, but that has performance trade offs. So you use a new type // Substring. This cause you to use a String contructor if you want to use the // part you sliced. This will allow the original string to be destroyed, and the buffer // is freed. let firstSlice = listOfSlices[0] let firstWord = String(listOfSlices[0]) // now it's a string. // Range is generic, it doesn't have to be over strings. Can be over String.Index let pizzaPlace = "Je moeders eettent" if let someindex = pizzaPlace.firstIndex(of: "m") { let partOfPizzaPlace = pizzaPlace[someindex..<pizzaPlace.endIndex] print(partOfPizzaPlace) }
mit
f4cfb0f8c0b0e28f1cee89e0cdfc2ebd
31.917526
87
0.719386
3.632537
false
false
false
false
ZhiQiang-Yang/pppt
v2exProject 2/Pods/Kingfisher/Sources/ImageDownloader.swift
12
21457
// // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2016 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(OSX) import AppKit #else import UIKit #endif /// Progress update block of downloader. public typealias ImageDownloaderProgressBlock = DownloadProgressBlock /// Completion block of downloader. public typealias ImageDownloaderCompletionHandler = ((image: Image?, error: NSError?, imageURL: NSURL?, originalData: NSData?) -> ()) /// Download task. public struct RetrieveImageDownloadTask { let internalTask: NSURLSessionDataTask /// Downloader by which this task is intialized. public private(set) weak var ownerDownloader: ImageDownloader? /** Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error. */ public func cancel() { ownerDownloader?.cancelDownloadingTask(self) } /// The original request URL of this download task. public var URL: NSURL? { return internalTask.originalRequest?.URL } /// The relative priority of this download task. /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task. /// The value for it is between 0.0~1.0. Default priority is value of 0.5. /// See documentation on `priority` of `NSURLSessionTask` for more about it. public var priority: Float { get { return internalTask.priority } set { internalTask.priority = newValue } } } private let defaultDownloaderName = "default" private let downloaderBarrierName = "com.onevcat.Kingfisher.ImageDownloader.Barrier." private let imageProcessQueueName = "com.onevcat.Kingfisher.ImageDownloader.Process." private let instance = ImageDownloader(name: defaultDownloaderName) /** The error code. - BadData: The downloaded data is not an image or the data is corrupted. - NotModified: The remote server responsed a 304 code. No image data downloaded. - InvalidURL: The URL is invalid. */ public enum KingfisherError: Int { case BadData = 10000 case NotModified = 10001 case InvalidURL = 20000 } /// Protocol of `ImageDownloader`. @objc public protocol ImageDownloaderDelegate { /** Called when the `ImageDownloader` object successfully downloaded an image from specified URL. - parameter downloader: The `ImageDownloader` object finishes the downloading. - parameter image: Downloaded image. - parameter URL: URL of the original request URL. - parameter response: The response object of the downloading process. */ optional func imageDownloader(downloader: ImageDownloader, didDownloadImage image: Image, forURL URL: NSURL, withResponse response: NSURLResponse) } /// Protocol indicates that an authentication challenge could be handled. public protocol AuthenticationChallengeResponable: class { /** Called when an session level authentication challenge is received. This method provide a chance to handle and response to the authentication challenge before downloading could start. - parameter downloader: The downloader which receives this challenge. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call. - Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`. */ func downloder(downloader: ImageDownloader, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) } extension AuthenticationChallengeResponable { func downloder(downloader: ImageDownloader, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let trustedHosts = downloader.trustedHosts where trustedHosts.contains(challenge.protectionSpace.host) { let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!) completionHandler(.UseCredential, credential) return } } completionHandler(.PerformDefaultHandling, nil) } } /// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server. public class ImageDownloader: NSObject { class ImageFetchLoad { var callbacks = [CallbackPair]() var responseData = NSMutableData() var options: KingfisherOptionsInfo? var downloadTaskCount = 0 var downloadTask: RetrieveImageDownloadTask? } // MARK: - Public property /// This closure will be applied to the image download request before it being sent. You can modify the request for some customizing purpose, like adding auth token to the header or do a url mapping. public var requestModifier: (NSMutableURLRequest -> Void)? /// The duration before the download is timeout. Default is 15 seconds. public var downloadTimeout: NSTimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead. public var trustedHosts: Set<String>? /// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly. public var sessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration() { didSet { session = NSURLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: NSOperationQueue.mainQueue()) } } /// Whether the download requests should use pipeling or not. Default is false. public var requestsUsePipeling = false private let sessionHandler: ImageDownloaderSessionHandler private var session: NSURLSession? /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. public weak var delegate: ImageDownloaderDelegate? /// A responder for authentication challenge. /// Downloader will forward the received authentication challenge for the downloading session to this responder. public weak var authenticationChallengeResponder: AuthenticationChallengeResponable? // MARK: - Internal property let barrierQueue: dispatch_queue_t let processQueue: dispatch_queue_t typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHander: ImageDownloaderCompletionHandler?) var fetchLoads = [NSURL: ImageFetchLoad]() // MARK: - Public method /// The default downloader. public class var defaultDownloader: ImageDownloader { return instance } /** Init a downloader with name. - parameter name: The name for the downloader. It should not be empty. - returns: The downloader object. */ public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.") } barrierQueue = dispatch_queue_create(downloaderBarrierName + name, DISPATCH_QUEUE_CONCURRENT) processQueue = dispatch_queue_create(imageProcessQueueName + name, DISPATCH_QUEUE_CONCURRENT) sessionHandler = ImageDownloaderSessionHandler() super.init() // Provide a default implement for challenge responder. authenticationChallengeResponder = sessionHandler session = NSURLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: NSOperationQueue.mainQueue()) } func fetchLoadForKey(key: NSURL) -> ImageFetchLoad? { var fetchLoad: ImageFetchLoad? dispatch_sync(barrierQueue, { () -> Void in fetchLoad = self.fetchLoads[key] }) return fetchLoad } } // MARK: - Download method extension ImageDownloader { /** Download an image with a URL. - parameter URL: Target URL. - parameter progressBlock: Called when the download progress updated. - parameter completionHandler: Called when the download progress finishes. - returns: A downloading task. You could call `cancel` on it to stop the downloading process. */ public func downloadImageWithURL(URL: NSURL, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask? { return downloadImageWithURL(URL, options: nil, progressBlock: progressBlock, completionHandler: completionHandler) } /** Download an image with a URL and option. - parameter URL: Target URL. - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`. - parameter progressBlock: Called when the download progress updated. - parameter completionHandler: Called when the download progress finishes. - returns: A downloading task. You could call `cancel` on it to stop the downloading process. */ public func downloadImageWithURL(URL: NSURL, options: KingfisherOptionsInfo?, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask? { return downloadImageWithURL(URL, retrieveImageTask: nil, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } internal func downloadImageWithURL(URL: NSURL, retrieveImageTask: RetrieveImageTask?, options: KingfisherOptionsInfo?, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask? { if let retrieveImageTask = retrieveImageTask where retrieveImageTask.cancelledBeforeDownlodStarting { return nil } let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL. let request = NSMutableURLRequest(URL: URL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: timeout) request.HTTPShouldUsePipelining = requestsUsePipeling self.requestModifier?(request) // There is a possiblility that request modifier changed the url to `nil` or empty. if request.URL == nil || request.URL!.absoluteString.isEmpty { completionHandler?(image: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.InvalidURL.rawValue, userInfo: nil), imageURL: nil, originalData: nil) return nil } var downloadTask: RetrieveImageDownloadTask? setupProgressBlock(progressBlock, completionHandler: completionHandler, forURL: request.URL!) {(session, fetchLoad) -> Void in if fetchLoad.downloadTask == nil { let dataTask = session.dataTaskWithRequest(request) fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self) fetchLoad.options = options dataTask.priority = options?.downloadPriority ?? NSURLSessionTaskPriorityDefault dataTask.resume() // Hold self while the task is executing. self.sessionHandler.downloadHolder = self } fetchLoad.downloadTaskCount += 1 downloadTask = fetchLoad.downloadTask retrieveImageTask?.downloadTask = downloadTask } return downloadTask } // A single key may have multiple callbacks. Only download once. internal func setupProgressBlock(progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?, forURL URL: NSURL, started: ((NSURLSession, ImageFetchLoad) -> Void)) { dispatch_barrier_sync(barrierQueue, { () -> Void in let loadObjectForURL = self.fetchLoads[URL] ?? ImageFetchLoad() let callbackPair = (progressBlock: progressBlock, completionHander: completionHandler) loadObjectForURL.callbacks.append(callbackPair) self.fetchLoads[URL] = loadObjectForURL if let session = self.session { started(session, loadObjectForURL) } }) } func cancelDownloadingTask(task: RetrieveImageDownloadTask) { dispatch_barrier_sync(barrierQueue) { () -> Void in if let URL = task.internalTask.originalRequest?.URL, imageFetchLoad = self.fetchLoads[URL] { imageFetchLoad.downloadTaskCount -= 1 if imageFetchLoad.downloadTaskCount == 0 { task.internalTask.cancel() } } } } func cleanForURL(URL: NSURL) { dispatch_barrier_sync(barrierQueue, { () -> Void in self.fetchLoads.removeValueForKey(URL) return }) } } // MARK: - NSURLSessionDataDelegate // See https://github.com/onevcat/Kingfisher/issues/235 /// Delegate class for `NSURLSessionTaskDelegate`. /// The session object will hold its delegate until it gets invalidated. /// If we use `ImageDownloader` as the session delegate, it will not be released. /// So we need an additional handler to break the retain cycle. class ImageDownloaderSessionHandler: NSObject, NSURLSessionDataDelegate, AuthenticationChallengeResponable { // The holder will keep downloader not released while a data task is being executed. // It will be set when the task started, and reset when the task finished. var downloadHolder: ImageDownloader? /** This method is exposed since the compiler requests. Do not call it. */ internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { completionHandler(NSURLSessionResponseDisposition.Allow) } /** This method is exposed since the compiler requests. Do not call it. */ internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { guard let downloader = downloadHolder else { return } if let URL = dataTask.originalRequest?.URL, fetchLoad = downloader.fetchLoadForKey(URL) { fetchLoad.responseData.appendData(data) for callbackPair in fetchLoad.callbacks { dispatch_async(dispatch_get_main_queue(), { () -> Void in callbackPair.progressBlock?(receivedSize: Int64(fetchLoad.responseData.length), totalSize: dataTask.response!.expectedContentLength) }) } } } /** This method is exposed since the compiler requests. Do not call it. */ internal func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let URL = task.originalRequest?.URL { if let error = error { // Error happened callbackWithImage(nil, error: error, imageURL: URL, originalData: nil) } else { //Download finished without error processImageForTask(task, URL: URL) } } } /** This method is exposed since the compiler requests. Do not call it. */ internal func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { guard let downloader = downloadHolder else { return } downloader.authenticationChallengeResponder?.downloder(downloader, didReceiveChallenge: challenge, completionHandler: completionHandler) } private func callbackWithImage(image: Image?, error: NSError?, imageURL: NSURL, originalData: NSData?) { guard let downloader = downloadHolder else { return } if let callbackPairs = downloader.fetchLoadForKey(imageURL)?.callbacks { let options = downloader.fetchLoadForKey(imageURL)?.options ?? KingfisherEmptyOptionsInfo downloader.cleanForURL(imageURL) for callbackPair in callbackPairs { dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in callbackPair.completionHander?(image: image, error: error, imageURL: imageURL, originalData: originalData) }) } if downloader.fetchLoads.isEmpty { downloadHolder = nil } } } private func processImageForTask(task: NSURLSessionTask, URL: NSURL) { guard let downloader = downloadHolder else { return } // We are on main queue when receiving this. dispatch_async(downloader.processQueue, { () -> Void in if let fetchLoad = downloader.fetchLoadForKey(URL) { let options = fetchLoad.options ?? KingfisherEmptyOptionsInfo if let image = Image.kf_imageWithData(fetchLoad.responseData, scale: options.scaleFactor) { downloader.delegate?.imageDownloader?(downloader, didDownloadImage: image, forURL: URL, withResponse: task.response!) if options.backgroundDecode { self.callbackWithImage(image.kf_decodedImage(scale: options.scaleFactor), error: nil, imageURL: URL, originalData: fetchLoad.responseData) } else { self.callbackWithImage(image, error: nil, imageURL: URL, originalData: fetchLoad.responseData) } } else { // If server response is 304 (Not Modified), inform the callback handler with NotModified error. // It should be handled to get an image from cache, which is response of a manager object. if let res = task.response as? NSHTTPURLResponse where res.statusCode == 304 { self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.NotModified.rawValue, userInfo: nil), imageURL: URL, originalData: nil) return } self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil) } } else { self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil) } }) } }
apache-2.0
aee5507f53ecc53b63b7e3a755aee2c7
43.983229
429
0.673487
5.706649
false
false
false
false
silence0201/Swift-Study
Swifter/64Where.playground/Contents.swift
1
882
//: Playground - noun: a place where people can play import Foundation let name = ["王小二","张三","李四","王二小"] name.forEach { switch $0 { case let x where x.hasPrefix("王"): print("\(x)是笔者本家") default: print("你好,\($0)") } } // 输出: // 王小二是笔者本家 // 你好,张三 // 你好,李四 // 王二小是笔者本家 let num: [Int?] = [48, 99, nil] let n = num.flatMap {$0} for score in n where score > 60 { print("及格啦 - \(score)") } // 输出: // 及格啦 - Optional(99) num.forEach { if let score = $0, score > 60 { print("及格啦 - \(score)") } else { print(":(") } } // 输出: // :( // 及格啦 - 99 // :( let sortableArray: [Int] = [3,1,2,4,5] let unsortableArray: [Any?] = ["Hello", 4, nil] sortableArray.sorted() //unsortableArray.sorted()
mit
9ee7bb2df50849d11dd0d78885a1fdd4
14.625
52
0.530667
2.491694
false
false
false
false
orta/eidolon
Kiosk/App/Models/Bid.swift
1
457
import Foundation class Bid: JSONAble { let id: String let amountCents: Int init(id: String, amountCents: Int) { self.id = id self.amountCents = amountCents } override class func fromJSON(json:[String: AnyObject]) -> JSONAble { let json = JSON(object: json) let id = json["id"].stringValue let amount = json["amount_cents"].integerValue return Bid(id: id, amountCents: amount) } }
mit
d3051ec3dbc105f121ba7374dfd00d7a
23.052632
72
0.61488
4.080357
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/RightSide/Topic/Controllers/ThemeTopic/QSThemeTopicInteractor.swift
1
3061
// // QSThemeTopicInteractor.swift // zhuishushenqi // // Created Nory Cao on 2017/4/13. // Copyright © 2017年 QS. All rights reserved. // // Template generated by Juanpe Catalán @JuanpeCMiOS // import UIKit import ZSAPI class QSThemeTopicInteractor: QSThemeTopicInteractorProtocol { var output: QSThemeTopicInteractorOutputProtocol! var models:[[ThemeTopicModel]] = [[],[],[]] var selectedIndex = 0 var tag = "" var gender = "" let segTitles = ["本周最热","最新发布","最多收藏"] func filter(index:Int,title:String,name:String){ //此处index为tag的index var titleString = title let genders = ["male","female"] if name == "性别" { gender = genders[index] tag = "" titleString = "\(titleString)生书单" }else{ gender = "" tag = title } self.output.showFilter(title: titleString,index: selectedIndex, tag: tag, gender: gender) } func initTitle(index:Int){ self.output.showFilter(title: "全部书单", index: index, tag: tag, gender: gender) } func setupSeg(index:Int){ self.output.showSegView(titles:segTitles ) } // func requestTitle(index:Int,tag:String,gender:String){ selectedIndex = index models = [[],[],[]] request(index: index, tag: tag, gender: gender) } func requestDetail(index:Int){ if selectedIndex == index { return } selectedIndex = index if self.models[index].count > 0 { self.output.fetchModelSuccess(models: self.models[index]) return } request(index: index, tag: tag, gender: gender) } func request(index:Int,tag:String,gender:String){ //本周最热 // http://api.zhuishushenqi.com/book-list?sort=collectorCount&duration=last-seven-days&start=0 //最新发布 // http://api.zhuishushenqi.com/book-list?sort=created&duration=all&start=0 //最多收藏 (全部书单) // http://api.zhuishushenqi.com/book-list?sort=collectorCount&duration=all&start=0 var sorts:[String] = ["collectorCount","created","collectorCount"] var durations:[String] = ["last-seven-days","all","all"] let api = ZSAPI.themeTopic(sort: sorts[index], duration: durations[index], start: "0", gender: gender, tag: tag) zs_get(api.path, parameters: api.parameters) { (response) in QSLog(response) if let books = response?["bookLists"] { if let models = [ThemeTopicModel].deserialize(from: books as? [Any]) as? [ThemeTopicModel] { self.models[index] = models self.output.fetchModelSuccess(models: models) } else { self.output.fetchModelFailed() } } else{ self.output.fetchModelFailed() } } } }
mit
ffd6b7b2f644aa305edafa14e4c015bb
31.293478
120
0.571525
4.020298
false
false
false
false
22377832/swiftdemo
Peek/Peek/AppDelegate.swift
1
3042
// // AppDelegate.swift // Peek // // Created by adults on 2017/4/5. // Copyright © 2017年 adults. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. guard let splitViewController = self.window!.rootViewController as? UISplitViewController else { fatalError("Unexpected view controller setup") } splitViewController.delegate = self return true } func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } // Return true if the `sampleTitle` has not been set, collapsing the secondary controller. return topAsDetailController.sampleTitle == nil } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
9bc11a14d13fdb349f513ba3a17d6b20
48.016129
285
0.750576
6.139394
false
false
false
false
stendahls/AsyncTask
Tests/Helper.swift
1
2119
// // Helper.swift // AsyncTask // // Created by Zhixuan Lai on 6/10/16. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Collection { /// Return a copy of `self` with its elements shuffled func shuffle() -> [Generator.Element] { var list = Array(self) list.shuffle() return list } } extension MutableCollection where Index == Int { /// Shuffle the elements of `self` in-place. mutating func shuffle() { // empty and single-element collections don't shuffle if count < 2 { return } for i in startIndex ..< endIndex - 1 { let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i if i != j { swap(&self[i], &self[j]) } } } } // Helpers extension Double { static var random: Double { get { return Double(arc4random()) / 0xFFFFFFFF } } static func random(min: Double, max: Double) -> Double { return Double.random * (max - min) + min } }
mit
1cc670a8f3e35f51aed91ca840ba44ba
31.106061
81
0.65361
4.263581
false
false
false
false
baiyidjp/SwiftWB
SwiftWeibo/SwiftWeibo/Classes/Tools(工具)/SwiftExtension/Date+Extensions.swift
1
2574
// // Date+Extensions.swift // SwiftWeibo // // Created by tztddong on 2016/12/15. // Copyright © 2016年 dongjiangpeng. All rights reserved. // import Foundation /// 日期格式化器 fileprivate let dateFormatter = DateFormatter() /// 当前日历对象 fileprivate let calendar = Calendar.current extension Date { //结构体重要定义类似于OC的'类'函数 不在使用class 使用static /// 用于计算DB的缓存是否过期 /// /// - Parameter max_time: 最大缓存时间 /// - Returns: 缓存不清除的最早时间 < 这个时间将清除 static func jp_dateString(max_time: TimeInterval) -> String { let nowDate = Date(timeIntervalSinceNow: max_time) dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return dateFormatter.string(from: nowDate) } /// 将新浪格式的日期转换成date /// /// - Parameter string: 新浪格式的日期 /// - Returns: date static func jp_sinaDateString(str: String) -> Date? { //设置日期格式 dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyy" //必须设置,否则无法解析 dateFormatter.locale = Locale(identifier: "en_US") //转换并且返回日期 return dateFormatter.date(from: str) } /// 返回显示时间本文 var jp_dateDescription: String { //判断是否是今天 if calendar.isDateInToday(self) { //计算传入 的时间 距离当前时间的差值 let delta = -Int(self.timeIntervalSinceNow) //返回 if delta < 60 { return "刚刚" } if delta < 60*60 { return "\(delta/60)分钟前" } return "\(delta/(60*60))小时前" } //其他天 var fmt = " HH:mm" //是昨天 if calendar.isDateInYesterday(self) { fmt = "昨天"+fmt }else { //今年 fmt = "MM-dd"+fmt //当前日期所在的年份 let currentYear = calendar.component(.year, from: Date()) //传入日期所在的年份 let year = calendar.component(.year, from: self) if year != currentYear { //不是今年 fmt = "yyyy-"+fmt } } //设置日期格式 dateFormatter.dateFormat = fmt return dateFormatter.string(from: self) } }
mit
1d1a447e3e5faf505f43763590c43b7c
23.943182
69
0.519818
4.042357
false
false
false
false
brentdax/swift
benchmark/single-source/DictionaryCompactMapValues.swift
6
1628
// Dictionary compact map values benchmark import TestsUtils public let DictionaryCompactMapValues = [ BenchmarkInfo(name: "DictionaryCompactMapValuesOfNilValue", runFunction: run_DictionaryCompactMapValuesOfNilValue, tags: [.validation, .api, .Dictionary]), BenchmarkInfo(name: "DictionaryCompactMapValuesOfCastValue", runFunction: run_DictionaryCompactMapValuesOfCastValue, tags: [.validation, .api, .Dictionary]), ] @inline(never) public func run_DictionaryCompactMapValuesOfNilValue(_ N: Int) { let size = 100 var dict = [Int: Int?](minimumCapacity: size) // Fill Dictionary for i in 1...size { if i % 2 == 0 { dict[i] = nil } else { dict[i] = i } } CheckResults(dict.count == size / 2) var refDict = [Int: Int]() for i in stride(from: 1, to: 100, by: 2) { refDict[i] = i } var newDict = [Int: Int]() for _ in 1...1000*N { newDict = dict.compactMapValues({$0}) if newDict != refDict { break } } CheckResults(newDict == refDict) } @inline(never) public func run_DictionaryCompactMapValuesOfCastValue(_ N: Int) { let size = 100 var dict = [Int: String](minimumCapacity: size) // Fill Dictionary for i in 1...size { if i % 2 == 0 { dict[i] = "dummy" } else { dict[i] = "\(i)" } } CheckResults(dict.count == size) var refDict = [Int: Int]() for i in stride(from: 1, to: 100, by: 2) { refDict[i] = i } var newDict = [Int: Int]() for _ in 1...1000*N { newDict = dict.compactMapValues(Int.init) if newDict != refDict { break } } CheckResults(newDict == refDict) }
apache-2.0
1372f847a5d33a4dad92104a33acadd3
21.929577
159
0.628378
3.420168
false
false
false
false
alpascual/DigitalWil
Configuration.swift
1
5092
// // Configuration.swift // FrostedSidebar // // Created by Al Pascual on 8/26/14. // Copyright (c) 2014 Evan Dekhayser. All rights reserved. // import Foundation class Configuration { let Code = "Configuration_Code" let NumberOfTries = "Configuration_NumberOfTries" let BestTimeOfDay = "Configuration_BestTimeOfDay" let HowLongBetweenRequests = "Configuration_HowLongBetweenRequests" let ConfigurationText = "Configuration_Text" init() { var defaults = NSUserDefaults() if defaults.objectForKey(NumberOfTries) == nil { defaults.setInteger(5, forKey: NumberOfTries) } if defaults.objectForKey(BestTimeOfDay) == nil { defaults.setInteger(1, forKey: BestTimeOfDay) // Morning } if defaults.objectForKey(HowLongBetweenRequests) == nil { defaults.setInteger(30, forKey: HowLongBetweenRequests) // Month } defaults.synchronize() } func setCode(valueString: String) { var defaults = NSUserDefaults() defaults.setObject(valueString, forKey: Code) defaults.synchronize() } func setNumberOfTries(value: Int) { var defaults = NSUserDefaults() defaults.setInteger(value, forKey: NumberOfTries) defaults.synchronize() } func setBestTimeOfDay(value: Int) { var defaults = NSUserDefaults() defaults.setInteger(value, forKey: BestTimeOfDay) defaults.synchronize() } func setHowLongBetweenRequests(value: Int) { var defaults = NSUserDefaults() defaults.setInteger(value, forKey: HowLongBetweenRequests) defaults.synchronize() } func getConfigurationArray() -> NSArray { var configuration : NSMutableArray = [] let defaults = NSUserDefaults() var code: AnyObject? = defaults.objectForKey(Code) != nil ? defaults.objectForKey(Code) : "" configuration.addObject(code!) configuration.addObject(defaults.objectForKey(NumberOfTries)!) configuration.addObject(defaults.objectForKey(BestTimeOfDay)!) configuration.addObject(defaults.objectForKey(HowLongBetweenRequests)!) return configuration } func getTimeOfTheDay() -> NSArray { return ["Morning","Afternoon", "Evening"] } func getHowOften() -> NSArray { return ["Every Day","Weekly", "Monthly", "Every 2 months", "Every 3 months", "Every 6 months", "Never"] } func getCodeValue() -> String { var defaults = NSUserDefaults() return defaults.objectForKey(Code) as String } func getNumberOfTriesValue() ->Int { var defaults = NSUserDefaults() return defaults.objectForKey(NumberOfTries) as Int } func getTimeOfTheDayValue() -> String { var defaults = NSUserDefaults() return self.convertValueFor(defaults.objectForKey(BestTimeOfDay) as Int, position: 2) } func getHowOftenValue() -> String { var defaults = NSUserDefaults() return self.convertValueFor(defaults.objectForKey(HowLongBetweenRequests) as Int, position: 3) } func convertValueFor(obj : AnyObject!, position: Int) -> String { println(obj) var timeOfDay = self.getTimeOfTheDay() var howOften = self.getHowOften() switch(position) { case 0: return "•••••••••" case 1: return String(obj as Int) case 2: switch(obj as Int) { case 1: return timeOfDay[0] as String case 2: return timeOfDay[1] as String default: return timeOfDay[2] as String } case 3: switch(obj as Int) { case 1: return howOften[0] as String case 7: return howOften[1] as String case 30: return howOften[2] as String case 60: return howOften[3] as String case 90: return howOften[4] as String case 180: return howOften[5] as String default: return howOften[6] as String } default: return "" } } func getLegacyText() -> String { var defaults = NSUserDefaults() if defaults.objectForKey(ConfigurationText) != nil { var text : String! = defaults.objectForKey(ConfigurationText) as String if text == nil { text = "Add any extra message you want here..." } return text } return "Nothing yet" } func setLegacyText(text : String) { var defaults = NSUserDefaults() defaults.setObject(text, forKey: ConfigurationText) defaults.synchronize() } }
mit
348ed83f2cd352d2927d4adf1b836ebd
27.194444
111
0.574497
4.846227
false
true
false
false
box/box-ios-sdk
Tests/Responses/BoxModel/BoxModelSpecs.swift
1
3866
// // BoxModelSpecs.swift // BoxSDKTests-iOS // // Created by Martina Stremenova on 19/07/2019. // Copyright © 2019 box. All rights reserved. // import Foundation @testable import BoxSDK import Nimble import Quick class BoxModelSpecs: QuickSpec { override func spec() { describe("testing boxmodel on comment") { it("should make call to init() to initalize comment response object from JSON dictionary") { guard let filepath = Bundle(for: type(of: self)).path(forResource: "FullComment", ofType: "json") else { fail("Could not find fixture file.") return } do { let contents = try String(contentsOfFile: filepath) guard let data = contents.data(using: .utf8) else { fail("Could not get spec file data") return } guard let commentDictionary = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { fail("Could not create dictionary from data") return } let comment = try Comment(json: commentDictionary) expect(JSONComparer.match(json1: comment.rawData, json2: commentDictionary)).to(equal(true)) expect(comment.json()).to(equal(comment.toJSONString())) guard let jsonString = String(data: data, encoding: .utf8) else { fail("Could not create json string from data") return } expect(JSONComparer.match(json1String: jsonString, json2String: comment.json())).to(equal(true)) } catch { fail("Failed with Error: \(error)") } } it("should make call to init() to initalize comment response object from JSON Data") { guard let filepath = Bundle(for: type(of: self)).path(forResource: "FullComment", ofType: "json") else { fail("Could not find fixture file.") return } do { let contents = try String(contentsOfFile: filepath) guard let data = contents.data(using: .utf8) else { fail("Could not get spec file data") return } guard let commentDictionary = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { fail("Could not create dictionary from data") return } let comment = try Comment(json: data) expect(JSONComparer.match(json1: comment.rawData, json2: commentDictionary)).to(equal(true)) expect(comment.json()).to(equal(comment.toJSONString())) guard let jsonString = String(data: data, encoding: .utf8) else { fail("Could not create json string from data") return } expect(JSONComparer.match(json1String: jsonString, json2String: comment.json())).to(equal(true)) } catch { fail("Failed with Error: \(error)") } } it("should throw an exception when call init() with invalid JSON Data object structure") { guard let data = "[1, 2, 3]".data(using: .utf8) else { fail("Could not get spec file data") return } expect { try Comment(json: data) }.to(throwError(errorType: BoxAPIError.self)) } } } }
apache-2.0
ba211a3beb6200b7872b0207ead27811
38.845361
120
0.504269
5.208895
false
false
false
false
zisko/swift
test/SILGen/switch_abstraction.swift
1
1636
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -parse-stdlib %s | %FileCheck %s struct A {} enum Optionable<T> { case Summn(T) case Nuttn } // CHECK-LABEL: sil hidden @$S18switch_abstraction18enum_reabstraction1x1ayAA10OptionableOyAA1AVAHcG_AHtF : $@convention(thin) (@owned Optionable<(A) -> A>, A) -> () // CHECK: switch_enum {{%.*}} : $Optionable<(A) -> A>, case #Optionable.Summn!enumelt.1: [[DEST:bb[0-9]+]] // CHECK: [[DEST]]([[ORIG:%.*]] : @owned $@callee_guaranteed (@in A) -> @out A): // CHECK: [[REABSTRACT:%.*]] = function_ref @$S{{.*}}TR : // CHECK: [[SUBST:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[ORIG]]) func enum_reabstraction(x x: Optionable<(A) -> A>, a: A) { switch x { case .Summn(var f): f(a) case .Nuttn: () } } enum Wacky<A, B> { case Foo(A) case Bar((B) -> A) } // CHECK-LABEL: sil hidden @$S18switch_abstraction45enum_addr_only_to_loadable_with_reabstraction{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@in Wacky<T, A>, A) -> @out T { // CHECK: switch_enum_addr [[ENUM:%.*]] : $*Wacky<T, A>, {{.*}} case #Wacky.Bar!enumelt.1: [[DEST:bb[0-9]+]] // CHECK: [[DEST]]: // CHECK: [[ORIG_ADDR:%.*]] = unchecked_take_enum_data_addr [[ENUM]] : $*Wacky<T, A>, #Wacky.Bar // CHECK: [[ORIG:%.*]] = load [take] [[ORIG_ADDR]] // CHECK: [[REABSTRACT:%.*]] = function_ref @$S{{.*}}TR : // CHECK: [[SUBST:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]<T>([[ORIG]]) func enum_addr_only_to_loadable_with_reabstraction<T>(x x: Wacky<T, A>, a: A) -> T { switch x { case .Foo(var b): return b case .Bar(var f): return f(a) } }
apache-2.0
f6d73485bb43c1cb13bdca3cf8690cb0
35.355556
173
0.589242
2.835355
false
false
false
false
marklin2012/iOS_Animation
Section3/Chapter16/O2Iris_starter/O2Iris/MicMonitor.swift
2
2073
// // MicMonitor.swift // O2Iris // // Created by O2.LinYi on 16/3/21. // Copyright © 2016年 jd.com. All rights reserved. // import Foundation import AVFoundation class MicMonitor: NSObject { private var recorder: AVAudioRecorder! private var timer: NSTimer? private var levelsHandler: ((Float) -> Void)? override init() { let url = NSURL(fileURLWithPath: "/dev/null", isDirectory: true) let settings: [String: AnyObject] = [ AVSampleRateKey: 44100.0, AVNumberOfChannelsKey: 1, AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatAppleLossless), AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue ] let audioSession = AVAudioSession.sharedInstance() if audioSession.recordPermission() != .Granted { audioSession.requestRecordPermission({ (success) -> Void in print("microphone permission: \(success)") }) } do { try recorder = AVAudioRecorder(URL: url, settings: settings) try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord) } catch { print("Couldn't initialize the mic input") } if let aRecorder = recorder { // start observing mic levels aRecorder.prepareToRecord() aRecorder.meteringEnabled = true } } func startMonitoringWithHandler(handler: (Float)->Void) { levelsHandler = handler // start meters timer = NSTimer.scheduledTimerWithTimeInterval(0.02, target: self, selector: "handleMicLeverl", userInfo: nil, repeats: true) recorder.record() } func stopMonitoring() { levelsHandler = nil timer?.invalidate() recorder.stop() } func handleMicLevel(timer: NSTimer) { recorder.updateMeters() levelsHandler?(recorder.averagePowerForChannel(0)) } deinit { stopMonitoring() } }
mit
17cfda8e88c26cbfd533ab30d0c69daa
26.972973
133
0.594686
5.214106
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Sources/StartMarker.swift
2
1689
// // StartMarker.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import SceneKit public final class StartMarker: Item, NodeConstructible { // MARK: Static static let template: SCNNode = { let resourcePath = "\(WorldConfiguration.propsDir)zon_prop_startTile_c" let node = loadTemplate(named: resourcePath) // Slight offset to avoid z-fighting. node.position.y = 0.01 return node }() // MARK: Item public static let identifier: WorldNodeIdentifier = .startMarker public weak var world: GridWorld? public let node: NodeWrapper public var worldIndex = -1 /// The type of actor this startMarker is used for. let type: ActorType init(type: ActorType) { self.type = type node = NodeWrapper(identifier: .startMarker) } init?(node: SCNNode) { guard node.identifier == .startMarker && node.identifierComponents.count >= 2 else { return nil } guard let type = ActorType(rawValue: node.identifierComponents[1]) else { return nil } self.type = type self.node = NodeWrapper(node) } public func loadGeometry() { guard scnNode.childNodes.isEmpty else { return } scnNode.addChildNode(StartMarker.template.clone()) } } import PlaygroundSupport extension StartMarker: MessageConstructor { // MARK: MessageConstructor var message: PlaygroundValue { return .array(baseMessage + stateInfo) } var stateInfo: [PlaygroundValue] { return [.string(type.rawValue)] } }
mit
7854e28e5f0c2309eb4b44e5bf2a04d0
23.478261
94
0.613381
4.504
false
false
false
false
primetimer/PrimeFactors
PrimeFactors/Classes/Lehman.swift
1
3245
// // FermatFactor.swift // PrimeBase // // Created by Stephan Jancar on 28.11.16. // Copyright © 2016 esjot. All rights reserved. // import Foundation import BigInt public class PrimeFactorLehman : PFactor { public func GetFactor(n: BigUInt, cancel: CalcCancelProt?) -> BigUInt { return Lehman(n: n, cancel: cancel) } private var sieve : PrimeSieve! private var trial : TrialDivision! var stopped = false var skipTrialDivision = false public init () { sieve = PSieve.shared trial = TrialDivision() } public init( sieve : PrimeSieve, cancel : CalcCancelProt) { self.sieve = sieve trial = TrialDivision(sieve: sieve) } private func IsCancelled(prot: CalcCancelProt?) -> Bool { return prot?.IsCancelled() ?? false } func Lehman(n: BigUInt,cancel : CalcCancelProt?) -> BigUInt { stopped = false if n <= 2 { return n } //let n64 = UInt64(n) var q : BigUInt = 1 if !self.skipTrialDivision { q = LehmanStep1(n: n, cancel: cancel) } if q > 1 { return BigUInt(q) } if n < BigUInt(UInt64.max) { let q64 = LehmanStep2(n: UInt64(n),cancel: cancel) q = BigUInt(q64) } else { q = LehmanStep2Big(n: n, cancel: cancel) } return BigUInt(q) } private func LehmanStep1(n: BigUInt,cancel : CalcCancelProt?) -> BigUInt { let upto = n.iroot3() let divisor = trial.BigTrialDivision(n: n, upto: upto, cancel: cancel) return divisor } private func LehmanStep2(n: UInt64, cancel : CalcCancelProt?) -> UInt64 { let n3 = n.iroot3() let n6 = n3.squareRoot() for k in 1...n3 { if cancel?.IsCancelled() ?? false { return 0 } let rk = k.squareRoot() let rkn = (k*n).squareRoot() let amin = 2*rkn - 1 var amax = n6 / 4 / rk amax = 1 + 2 * rkn + amax for a in amin...amax { if cancel?.IsCancelled() ?? false { return 0 } //Converting to 128 bit let a_128 = UInt128(a) let k_128 = UInt128(k) let n_128 = UInt128(n) // a^2 - 4 kn let a2 = a_128 * a_128 let kn4 = k_128 * n_128 * UInt128(4) if kn4 > a2 { //This case can occure, because you should use the ceil of the root in amin //But i use the floor continue } let y = a2 - kn4 let ry = y.squareRoot() //Perfect Square ? if ry * ry == y { let c = a + UInt64(ry) let d = c.greatestCommonDivisor(with: n) if (d != 1) { return d } } } } return 1 } private func LehmanStep2Big(n: BigUInt, cancel: CalcCancelProt?) -> BigUInt { let n3 = n.iroot3() let n6 = n3.squareRoot() for k in 1...n3 { if cancel?.IsCancelled() ?? false { return 0 } let rk = k.squareRoot() let rkn = (k*n).squareRoot() let amin = 2*rkn - 1 var amax = n6 / 4 / rk amax = 1 + 2 * rkn + amax for a in amin...amax { if cancel?.IsCancelled() ?? false { return 0 } let a2 = a*a let kn4 = k*n*4 if kn4 > a2 { //This case can occure, because you should use the ceil of the root in amin //But i use the floor continue } let y = a2 - kn4 let ry = y.squareRoot() //Perfect Square ? if ry * ry == y { let c = a + ry let d = c.greatestCommonDivisor(with: n) if (d != 1) { return d } } } } return 1 } }
mit
8112e067272d4950fce02346c1049d5a
22.507246
80
0.594328
2.855634
false
false
false
false
msahins/myTV
SwiftRadio/StationsViewController.swift
1
10727
import UIKit import MediaPlayer import AVFoundation class StationsViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var stationNowPlayingButton: UIButton! @IBOutlet weak var nowPlayingAnimationImageView: UIImageView! var stations = [RadioStation]() var currentStation: RadioStation? var currentTrack: Track? var refreshControl: UIRefreshControl! var firstTime = true //***************************************************************** // MARK: - ViewDidLoad //***************************************************************** override func viewDidLoad() { super.viewDidLoad() // Register 'Nothing Found' cell xib let cellNib = UINib(nibName: "NothingFoundCell", bundle: nil) tableView.registerNib(cellNib, forCellReuseIdentifier: "NothingFound") // Load Data loadStationsFromJSON() // Setup TableView tableView.backgroundColor = UIColor.clearColor() tableView.backgroundView = nil tableView.separatorStyle = UITableViewCellSeparatorStyle.None // Setup Pull to Refresh setupPullToRefresh() // Create NowPlaying Animation createNowPlayingAnimation() // Set AVFoundation category, required for background audio var error: NSError? var success: Bool do { try AVAudioSession.sharedInstance().setCategory( AVAudioSessionCategoryPlayAndRecord, withOptions: .DefaultToSpeaker) success = true } catch let error1 as NSError { error = error1 success = false } if !success { print("Ses ayarlama başarısız oldu. Hata: \(error)") } } override func viewWillAppear(animated: Bool) { self.title = "myTV" // If a station has been selected, create "Now Playing" button to get back to current station if !firstTime { createNowPlayingBarButton() } // If a track is playing, display title & artist information and animation if currentTrack != nil && currentTrack!.isPlaying { let title = currentStation!.stationName + ": " + currentTrack!.title + " - " + currentTrack!.artist + "..." stationNowPlayingButton.setTitle(title, forState: .Normal) nowPlayingAnimationImageView.startAnimating() } else { nowPlayingAnimationImageView.stopAnimating() nowPlayingAnimationImageView.image = UIImage(named: "NowPlayingBars") } } //***************************************************************** // MARK: - Setup UI Elements //***************************************************************** func setupPullToRefresh() { self.refreshControl = UIRefreshControl() self.refreshControl.attributedTitle = NSAttributedString(string: "Yenilemek için çekin") self.refreshControl.backgroundColor = UIColor.blackColor() self.refreshControl.tintColor = UIColor.whiteColor() self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) self.tableView.addSubview(refreshControl) } func createNowPlayingAnimation() { nowPlayingAnimationImageView.animationImages = AnimationFrames.createFrames() nowPlayingAnimationImageView.animationDuration = 0.7 } func createNowPlayingBarButton() { if self.navigationItem.rightBarButtonItem == nil { let btn = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action:"nowPlayingBarButtonPressed") btn.image = UIImage(named: "btn-nowPlaying") self.navigationItem.rightBarButtonItem = btn } } //***************************************************************** // MARK: - Actions //***************************************************************** func nowPlayingBarButtonPressed() { performSegueWithIdentifier("NowPlaying", sender: self) } @IBAction func nowPlayingPressed(sender: UIButton) { performSegueWithIdentifier("NowPlaying", sender: self) } func refresh(sender: AnyObject) { // Pull to Refresh stations.removeAll(keepCapacity: false) loadStationsFromJSON() // Wait 2 seconds then refresh screen let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))); dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in self.refreshControl.endRefreshing() self.view.setNeedsDisplay() } } //***************************************************************** // MARK: - Load Station Data //***************************************************************** func loadStationsFromJSON() { UIApplication.sharedApplication().networkActivityIndicatorVisible = true DataManager.getStationDataWithSuccess() { (data) in if DEBUG_LOG { print("JSON İstasyonlar Yüklendi") } let json = JSON(data: data) if let stationArray = json["station"].array { for stationJSON in stationArray { let station = RadioStation.parseStation(stationJSON) self.stations.append(station) } dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.view.setNeedsDisplay() } } else { if DEBUG_LOG { print("JSON İstasyonlar Yüklenemedi!") } } UIApplication.sharedApplication().networkActivityIndicatorVisible = true } } //***************************************************************** // MARK: - Segue //***************************************************************** override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "NowPlaying" { self.title = "Geri" firstTime = false let nowPlayingVC = segue.destinationViewController as! NowPlayingViewController nowPlayingVC.delegate = self if let indexPath = (sender as? NSIndexPath) { // User clicked on row, load/reset station currentStation = stations[indexPath.row] nowPlayingVC.currentStation = currentStation nowPlayingVC.newStation = true } else { // User clicked on a now playing button if let currentTrack = currentTrack { // Return to NowPlaying controller without reloading station nowPlayingVC.track = currentTrack nowPlayingVC.currentStation = currentStation nowPlayingVC.newStation = false } else { // Issue with track, reload station nowPlayingVC.currentStation = currentStation nowPlayingVC.newStation = true } } } } } //***************************************************************** // MARK: - TableViewDataSource //***************************************************************** extension StationsViewController: UITableViewDataSource { // MARK: - Table view data source func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 88 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if stations.count == 0 { return 1 } else { return stations.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if stations.isEmpty { let cell = tableView.dequeueReusableCellWithIdentifier("NothingFound", forIndexPath: indexPath) cell.backgroundColor = UIColor.clearColor() cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("StationCell", forIndexPath: indexPath) as! StationTableViewCell // alternate background color if indexPath.row % 2 == 0 { cell.backgroundColor = UIColor.clearColor() } else { cell.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.2) } // Configure the cell... let station = stations[indexPath.row] cell.configureStationCell(station) return cell } } } //***************************************************************** // MARK: - TableViewDelegate //***************************************************************** extension StationsViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if !stations.isEmpty { // Set Now Playing Buttons let title = stations[indexPath.row].stationName + " - Son İzlenen..." stationNowPlayingButton.setTitle(title, forState: .Normal) stationNowPlayingButton.enabled = true performSegueWithIdentifier("NowPlaying", sender: indexPath) } } } //***************************************************************** // MARK: - NowPlayingViewControllerDelegate //***************************************************************** extension StationsViewController: NowPlayingViewControllerDelegate { func artworkDidUpdate(track: Track) { currentTrack?.artworkURL = track.artworkURL currentTrack?.artworkImage = track.artworkImage } func songMetaDataDidUpdate(track: Track) { currentTrack = track let title = currentStation!.stationName + ": " + currentTrack!.title + " - " + currentTrack!.artist + "..." stationNowPlayingButton.setTitle(title, forState: .Normal) } }
mit
18eb61dfcb560c924bf6e8df77ae7c97
36.211806
134
0.541569
6.364014
false
false
false
false
dsay/POPDataSources
Example/POPDataSource/Example/ViewControllers/MenuViewController.swift
1
4484
import UIKit import POPDataSource class MenuViewController: UITableViewController { var hiddenCellIds: [String: IndexPath] = [:] override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destinationController = segue.destination as? TableViewController { switch segue.identifier! { case "showGenres": let dataSourceLoader: PagingDataSource.Loader = { result in let deadlineTime = DispatchTime.now() + .seconds(3) DispatchQueue.main.asyncAfter(deadline: deadlineTime) { result(false, [AlbumsDataSource()]) } } let albums = AlbumsDataSource() let dataSource = PagingDataSource([albums], dataSourceLoader) destinationController.shim = TableViewDataSourceShim(dataSource) case "showArtists": let dataSource = ComposedDataSource(LedZeppelin.artists) destinationController.shim = TableViewDataSourceShim(dataSource) case "showAlbums": let dataSource = AlbumsDataSource() dataSource.cellConfigurator?.on(.willDisplay) { cell, index, item in print("tap on cell") } dataSource.cellConfigurator?.on(.custom(Actions.Album.onButton)) { cell, index, item in print("tap on button in cell") } dataSource.header?.on(.custom(Actions.Album.onSection)) { header, index in print("tap on button in section") } let composed = ComposedDataSource([dataSource, dataSource, dataSource]) destinationController.shim = TableViewDataSourceShim(composed) case "showCollapsible": let albums = AlbumsDataSource() // albums.header?.on(.custom(Actions.Album.onSection)) { // [weak controller = destinationController, unowned albums] (header, index) in // if albums.open { // controller?.tableView.collapse(albums) // } else { // controller?.tableView.expand(albums) // } // } destinationController.shim = TableViewDataSourceShim(albums) case "showFilterable": // let composed = ComposedDataSource([createDataSource(destinationController: destinationController), // createDataSource(destinationController: destinationController), // createDataSource(destinationController: destinationController)]) let composed = ComposedDataSource([]) destinationController.shim = TableViewDataSourceShim(composed) default: fatalError("not implemented") } } } // MARK: - Filter logic func createDataSource(destinationController: TableViewController) -> AlbumsDataSource { let dataSource = AlbumsDataSource() dataSource.cellConfigurator?.on(.custom(Actions.Album.onButton)) { [weak dataSource, weak destinationController] cell, index, item in guard let ds = dataSource else { return } destinationController?.tableView.filter(ds, at: index.section) { dataSource?.toggleState(for: item, at: index) } } dataSource.header?.on(.custom(Actions.Album.onSection)) { [weak dataSource, weak destinationController] header, index in guard let ds = dataSource else { return } destinationController?.tableView.filter(ds, at: index) { dataSource?.showAll() } } return dataSource } } extension Album { var id: String { return "\(name)_\(artistName)" } } extension DataFilterable { func toggleState(for item: Item, at index: IndexPath) { if let index = hiddenItems.firstIndex(of: item) { hiddenItems.remove(at: index) } else { hiddenItems.append(item) } } func showAll() { hiddenItems.removeAll() } }
mit
a562663cf77a00755081f07dd7e2eb83
37.991304
141
0.550178
5.915567
false
false
false
false
anfema/DEjson
Sources/JSONDecoder.swift
1
14643
// // dejson.swift // dejson // // Created by Johannes Schriewer on 30.01.15. // Copyright (c) 2015 anfema. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the conditions of the 3-clause // BSD license (see LICENSE.txt for full license text) import Foundation open class JSONDecoder { public let string : String.UnicodeScalarView? public init(_ string: String) { self.string = string.unicodeScalars } open var jsonObject: JSONObject { var generator = self.string!.makeIterator() let result = self.scanObject(&generator) return result.obj } func scanObject(_ generator: inout String.UnicodeScalarView.Iterator, currentChar: UnicodeScalar = UnicodeScalar(0)) -> (obj: JSONObject, backtrackChar: UnicodeScalar?) { func parse(_ c: UnicodeScalar, generator: inout String.UnicodeScalarView.Iterator) -> (obj: JSONObject?, backtrackChar: UnicodeScalar?) { switch c.value { case 9, 10, 13, 32: // space, tab, newline, cr return (obj: nil, backtrackChar: nil) case 123: // { if let dict = self.parseDict(&generator) { return (obj: .jsonDictionary(dict), backtrackChar: nil) } else { return (obj: .jsonInvalid, backtrackChar: nil) } case 91: // [ return (obj: .jsonArray(self.parseArray(&generator)), backtrackChar: nil) case 34: // " return (obj: .jsonString(self.parseString(&generator)), backtrackChar: nil) case 43, 45, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57: // 0-9, -, + let result = self.parseNumber(&generator, currentChar: c) if let num = result.number { return (obj: .jsonNumber(num), backtrackChar: result.backtrackChar) } else { return (obj: .jsonInvalid, backtrackChar: result.backtrackChar) } case 102, 110, 116: // f, n, t if let b = self.parseStatement(&generator, currentChar: c) { return (obj: .jsonBoolean(b), backtrackChar: nil) } else { return (obj: .jsonNull, backtrackChar: nil) } default: // found an invalid char return (obj: .jsonInvalid, backtrackChar: nil) } } if currentChar.value != 0 { let obj = parse(currentChar, generator: &generator) if obj.obj != nil { return (obj: obj.obj!, backtrackChar: obj.backtrackChar) } } else { while let c = generator.next() { let obj = parse(c, generator: &generator) if obj.obj != nil { return (obj: obj.obj!, backtrackChar: obj.backtrackChar) } } } return (obj: .jsonInvalid, backtrackChar: nil) } // TODO: Add tests for escaped characters func parseString(_ generator: inout String.UnicodeScalarView.Iterator) -> (String) { var stringEnded = false var slash = false var string = String() while let c = generator.next() { if slash { switch c.value { case 34: // " string.append(String(describing: UnicodeScalar(34)!)) case 110: // n -> linefeed string.append(String(describing: UnicodeScalar(10)!)) case 98: // b -> backspace string.append(String(describing: UnicodeScalar(8)!)) case 102: // f -> formfeed string.append(String(describing: UnicodeScalar(12)!)) case 114: // r -> carriage return string.append(String(describing: UnicodeScalar(13)!)) case 116: // t -> tab string.append(String(describing: UnicodeScalar(9)!)) case 92: // \ -> \ string.append(String(describing: UnicodeScalar(92)!)) case 117: // u -> unicode value // gather 4 chars let d1 = self.parseHexDigit(generator.next()) let d2 = self.parseHexDigit(generator.next()) let d3 = self.parseHexDigit(generator.next()) let d4 = self.parseHexDigit(generator.next()) var codepoint = (d1 << 12) | (d2 << 8) | (d3 << 4) | d4; // validate that the codepoint is actually valid unicode, else apple likes to crash our app // see: https://bugs.swift.org/browse/SR-1930 if (codepoint > 0xD800 && codepoint < 0xDFFF) || (codepoint > 0x10FFFF) { codepoint = 0x3F } string.append(String(describing: UnicodeScalar(codepoint)!)) default: string.append(String(c)) } slash = false continue } switch c.value { case 92: // \ // skip next char (could be a ") slash = true case 34: // " stringEnded = true default: string.append(String(c)) } if stringEnded { break } } return string.replacingOccurrences(of: "\\n", with: "\n") } func parseHexDigit(_ digit: UnicodeScalar?) -> UInt32 { guard let digit = digit else { return 0 } switch digit.value { case 48, 49, 50, 51, 52, 53, 54, 55, 56, 57: return digit.value - 48 case 97, 98, 99, 100, 101, 102: return digit.value - 87 default: return 0 } } func parseDict(_ generator: inout String.UnicodeScalarView.Iterator) -> (Dictionary<String, JSONObject>?) { var dict : Dictionary<String, JSONObject> = Dictionary() var dictKey: String? = nil var dictEnded = false while var c = generator.next() { while true { switch c.value { case 9, 10, 13, 32, 44: // space, tab, newline, cr, ',' break case 34: // " dictKey = self.parseString(&generator) case 58: // : if let key = dictKey { let result = self.scanObject(&generator) dict.updateValue(result.obj, forKey: key) dictKey = nil // Backtrack one character if let backTrack = result.backtrackChar { c = backTrack continue } } else { dictEnded = true } case 125: // } dictEnded = true default: return nil } break } if dictEnded { break } } return dict } func parseArray(_ generator: inout String.UnicodeScalarView.Iterator) -> (Array<JSONObject>) { var arr : Array<JSONObject> = Array() var arrayEnded = false while var c = generator.next() { while true { switch c.value { case 9, 10, 13, 32, 44: // space, tab, newline, cr, ',' break case 93: // ] arrayEnded = true default: let result = self.scanObject(&generator, currentChar: c) arr.append(result.obj) // Backtrack one character if let backTrack = result.backtrackChar { c = backTrack continue } } break } if (arrayEnded) { break } } return arr } // TODO: Add tests for negative numbers and exponential notations func parseNumber(_ generator: inout String.UnicodeScalarView.Iterator, currentChar: UnicodeScalar) -> (number: Double?, backtrackChar: UnicodeScalar?) { var numberEnded = false var numberStarted = false var exponentStarted = false var exponentNumberStarted = false var decimalStarted = false var sign : Double = 1.0 var exponent : Int = 0 var decimalCount : Int = 0 var number : Double = 0.0 func parse(_ c: UnicodeScalar, generator: inout String.UnicodeScalarView.Iterator) -> (numberEnded: Bool?, backtrackChar: UnicodeScalar?) { var backtrack: UnicodeScalar? = nil switch (c.value) { case 9, 10, 13, 32: // space, tab, newline, cr if numberStarted { numberEnded = true } case 43, 45: // +, - if (numberStarted && !exponentStarted) || (exponentStarted && exponentNumberStarted) { // error return (numberEnded: nil, backtrackChar: nil) } else if !numberStarted { numberStarted = true if c.value == 45 { sign = -1.0 } } case 48, 49, 50, 51, 52, 53, 54, 55, 56, 57: // 0-9 if !numberStarted { numberStarted = true } if exponentStarted && !exponentNumberStarted { exponentNumberStarted = true } if decimalStarted { decimalCount += 1 number = number * 10.0 + Double(c.value - 48) } else if numberStarted { number = number * 10.0 + Double(c.value - 48) } else if exponentStarted { exponent = exponent * 10 + Int(c.value - 48) } case 46: // . if decimalStarted { // error return (numberEnded: nil, backtrackChar: nil) } else { decimalStarted = true } case 69, 101: // E, e if exponentStarted { // error return (numberEnded: nil, backtrackChar: nil) } else { exponentStarted = true } default: if numberStarted { backtrack = c numberEnded = true } else { return (numberEnded: nil, backtrackChar: nil) } } if numberEnded { let e = __exp10(Double(exponent - decimalCount)) number = number * e number *= sign return (numberEnded: true, backtrackChar: backtrack) } return (numberEnded: false, backtrackChar: backtrack) } let result = parse(currentChar, generator: &generator) if let numberEnded = result.numberEnded { if numberEnded { return (number: number, backtrackChar: result.backtrackChar) } } else { return (number: nil, backtrackChar: result.backtrackChar) } while let c = generator.next() { let result = parse(c, generator: &generator) if let numberEnded = result.numberEnded { if numberEnded { return (number: number, backtrackChar: result.backtrackChar) } } else { return (number: nil, backtrackChar: result.backtrackChar) } } let e = __exp10(Double(exponent - decimalCount)) number = number * e number *= sign return (number: number, backtrackChar: nil) } // TODO: Add tests for true, false and null func parseStatement(_ generator: inout String.UnicodeScalarView.Iterator, currentChar: UnicodeScalar) -> (Bool?) { enum parseState { case parseStateUnknown case parseStateTrue(Int) case parseStateNull(Int) case parseStateFalse(Int) init() { self = .parseStateUnknown } } var state = parseState() switch currentChar.value { case 116: // t state = .parseStateTrue(1) case 110: // n state = .parseStateNull(1) case 102: // f state = .parseStateFalse(1) default: return nil } while let c = generator.next() { switch state { case .parseStateUnknown: return nil case .parseStateTrue(let index): let search = "true" let i = search.unicodeScalars.index(search.unicodeScalars.startIndex, offsetBy: index) if c == search.unicodeScalars[i] { state = .parseStateTrue(index+1) if index == search.count - 1 { return true } } case .parseStateFalse(let index): let search = "false" let i = search.unicodeScalars.index(search.unicodeScalars.startIndex, offsetBy: index) if c == search.unicodeScalars[i] { state = .parseStateFalse(index+1) if index == search.count - 1 { return false } } case .parseStateNull(let index): let search = "null" let i = search.unicodeScalars.index(search.unicodeScalars.startIndex, offsetBy: index) if c == search.unicodeScalars[i] { state = .parseStateNull(index+1) if index == search.count - 1{ return nil } } } } return nil } }
bsd-3-clause
c1414f9661b3968f5a669cfdcd9ff167
36.450128
174
0.472512
5.165079
false
false
false
false
karstengresch/rw_studies
CoreData/Bow Ties/Bow Ties/AppDelegate.swift
1
3963
/* * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { guard let rootViewController = window?.rootViewController as? ViewController else { return true } rootViewController.managedContext = persistentContainer.viewContext return true } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Bow_Ties") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
unlicense
6adc1dc9778528b7932b86ccb6526c11
43.033333
191
0.725965
5.305221
false
false
false
false
bromas/Architect
UIArchitect/ConstrainingEquate.swift
1
3249
// // ConstrainingEquate.swift // LayoutArchitect // // Created by Brian Thomas on 5/7/15. // Copyright (c) 2015 Brian Thomas. All rights reserved. // public typealias EquateResult = [BlueprintMeasure: NSLayoutConstraint] public typealias ExtendedEquateOptions = (relation: BlueprintRelation, magnitude: CGFloat, multiplier: CGFloat, priority: BlueprintPriority) import Foundation import UIKit public func equate(heightOf view: UIView, #fromRatioToWidth: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: fromRatioToWidth, constant: 0) view.addConstraint(constraint) return constraint } public func equate(widthOf view: UIView, #fromRatioToHeight: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: view, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: fromRatioToHeight, constant: 0) view.addConstraint(constraint) return constraint } public func equate(view: UIView, with options: [BlueprintMeasure: CGFloat]) -> EquateResult { var newOptions = [BlueprintMeasure: ExtendedEquateOptions]() for (measure, float) in options { let option = (BlueprintRelation.Equal, options[measure]!, CGFloat(1.0), BlueprintPriority.Required) newOptions[measure] = option } return equate(view, to: view, withExtendedOptions: newOptions) } public func equate(view: UIView, withExtendedOptions options: [BlueprintMeasure: ExtendedEquateOptions]) -> EquateResult { return equate(view, to: view, withExtendedOptions: options) } public func equate(view: UIView, to toView: UIView, with options: [BlueprintMeasure: CGFloat]) -> EquateResult { var newOptions = [BlueprintMeasure: ExtendedEquateOptions]() for (measure, float) in options { let option = (BlueprintRelation.Equal, options[measure]!, CGFloat(1.0), BlueprintPriority.Required) newOptions[measure] = option } return equate(view, to: toView, withExtendedOptions: newOptions) } public func equate(view: UIView, to toView: UIView, withExtendedOptions options: [BlueprintMeasure: ExtendedEquateOptions]) -> EquateResult { let superview = assertCommonSuperview(view, and: toView) var constraints = EquateResult() let finalToView: UIView? = view == toView ? .None : toView for (attribute: BlueprintMeasure, with: ExtendedEquateOptions) in options { let relation = with.relation.layoutRelation() let priority = with.priority.float() switch attribute { case .Width: var constraint = NSLayoutConstraint(item: view, attribute: .Width, relatedBy: relation, toItem: finalToView, attribute: .Width, multiplier: with.multiplier, constant: with.magnitude) constraint.priority = priority constraints[.Width] = constraint superview.addConstraint(constraints[.Width]!) case .Height: var constraint = NSLayoutConstraint(item: view, attribute: .Height, relatedBy: relation, toItem: finalToView, attribute: .Height, multiplier: with.multiplier, constant: with.magnitude) constraint.priority = priority constraints[.Height] = constraint superview.addConstraint(constraints[.Height]!) } } return constraints }
mit
6ba55c6a14f59972551c61d255bc9a77
43.506849
190
0.753463
4.28628
false
false
false
false
eliasbagley/Pesticide
debugdrawer/CocoaLumberjack.swift
1
2311
// Created by Ullrich Schäfer on 16/08/14. // Updated to Swift 1.1 and CocoaLumberjack beta4 by Stan Serebryakov on 24/10/14 // https://gist.github.com/cfr/7da8da56654288fad7aa import Foundation extension DDLog { private struct State { static var logLevel: DDLogLevel = .Error static var logAsync: Bool = true } class var logLevel: DDLogLevel { get { return State.logLevel } set { State.logLevel = newValue } } class var logAsync: Bool { get { return (self.logLevel != .Error) && State.logAsync } set { State.logAsync = newValue } } class func log(flag: DDLogFlag, message: @autoclosure () -> String, function: String = __FUNCTION__, file: String = __FILE__, line: UInt = __LINE__) { if flag.rawValue & logLevel.rawValue != 0 { var logMsg = DDLogMessage(message: message(), level: logLevel, flag: flag, context: 0, file: file, function: function, line: line, tag: nil, options: DDLogMessageOptions(0), timestamp: nil) DDLog.log(logAsync, message: logMsg) } } } func logError(message: @autoclosure () -> String, function: String = __FUNCTION__, file: String = __FILE__, line: UInt = __LINE__) { DDLog.log(.Error, message: message, function: function, file: file, line: line) } func logWarn(message: @autoclosure () -> String, function: String = __FUNCTION__, file: String = __FILE__, line: UInt = __LINE__) { DDLog.log(.Warning, message: message, function: function, file: file, line: line) } func logInfo(message: @autoclosure () -> String, function: String = __FUNCTION__, file: String = __FILE__, line: UInt = __LINE__) { DDLog.log(.Info, message: message, function: function, file: file, line: line) } func logDebug(message: @autoclosure () -> String, function: String = __FUNCTION__, file: String = __FILE__, line: UInt = __LINE__) { DDLog.log(.Debug, message: message, function: function, file: file, line: line) } func logVerbose(message: @autoclosure () -> String, function: String = __FUNCTION__, file: String = __FILE__, line: UInt = __LINE__) { DDLog.log(.Verbose, message: message, function: function, file: file, line: line) }
mit
690b3f47786293a486b0dc31c99c3273
38.844828
102
0.611255
3.908629
false
false
false
false
r-mckay/montreal-iqa
montrealIqaCore/Carthage/Checkouts/realm-cocoa/RealmSwift/Results.swift
12
18568
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm // MARK: MinMaxType /** Types of properties which can be used with the minimum and maximum value APIs. - see: `min(ofProperty:)`, `max(ofProperty:)` */ public protocol MinMaxType {} extension NSNumber: MinMaxType {} extension Double: MinMaxType {} extension Float: MinMaxType {} extension Int: MinMaxType {} extension Int8: MinMaxType {} extension Int16: MinMaxType {} extension Int32: MinMaxType {} extension Int64: MinMaxType {} extension Date: MinMaxType {} extension NSDate: MinMaxType {} // MARK: AddableType /** Types of properties which can be used with the sum and average value APIs. - see: `sum(ofProperty:)`, `average(ofProperty:)` */ public protocol AddableType {} extension NSNumber: AddableType {} extension Double: AddableType {} extension Float: AddableType {} extension Int: AddableType {} extension Int8: AddableType {} extension Int16: AddableType {} extension Int32: AddableType {} extension Int64: AddableType {} /** `Results` is an auto-updating container type in Realm returned from object queries. `Results` can be queried with the same predicates as `List<T>`, and you can chain queries to further filter query results. `Results` always reflect the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over the objects which matched the query when the enumeration is begun, even if some of them are deleted or modified to be excluded by the filter during the enumeration. `Results` are lazily evaluated the first time they are accessed; they only run queries when the result of the query is requested. This means that chaining several temporary `Results` to sort and filter your data does not perform any unnecessary work processing the intermediate state. Once the results have been evaluated or a notification block has been added, the results are eagerly kept up-to-date, with the work done to keep them up-to-date done on a background thread whenever possible. Results instances cannot be directly instantiated. */ public final class Results<T: Object>: NSObject, NSFastEnumeration { internal let rlmResults: RLMResults<RLMObject> /// A human-readable description of the objects represented by the results. public override var description: String { let type = "Results<\(rlmResults.objectClassName)>" return gsub(pattern: "RLMResults <0x[a-z0-9]+>", template: type, string: rlmResults.description) ?? type } // MARK: Fast Enumeration /// :nodoc: public func countByEnumerating(with state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>, count len: Int) -> Int { return Int(rlmResults.countByEnumerating(with: state, objects: buffer, count: UInt(len))) } /// The type of the objects described by the results. public typealias Element = T // MARK: Properties /// The Realm which manages this results. Note that this property will never return `nil`. public var realm: Realm? { return Realm(rlmResults.realm) } /** Indicates if the results are no longer valid. The results becomes invalid if `invalidate()` is called on the containing `realm`. An invalidated results can be accessed, but will always be empty. */ public var isInvalidated: Bool { return rlmResults.isInvalidated } /// The number of objects in the results. public var count: Int { return Int(rlmResults.count) } // MARK: Initializers internal init(_ rlmResults: RLMResults<RLMObject>) { self.rlmResults = rlmResults } // MARK: Index Retrieval /** Returns the index of the given object in the results, or `nil` if the object is not present. */ public func index(of object: T) -> Int? { return notFoundToNil(index: rlmResults.index(of: object.unsafeCastToRLMObject())) } /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: predicate)) } /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func index(matching predicateFormat: String, _ args: Any...) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: NSPredicate(format: predicateFormat, argumentArray: args))) } // MARK: Object Retrieval /** Returns the object at the given `index`. - parameter index: The index. */ public subscript(position: Int) -> T { throwForNegativeIndex(position) return unsafeBitCast(rlmResults.object(at: UInt(position)), to: T.self) } /// Returns the first object in the results, or `nil` if the results are empty. public var first: T? { return unsafeBitCast(rlmResults.firstObject(), to: Optional<T>.self) } /// Returns the last object in the results, or `nil` if the results are empty. public var last: T? { return unsafeBitCast(rlmResults.lastObject(), to: Optional<T>.self) } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the results. - parameter key: The name of the property whose values are desired. */ public override func value(forKey key: String) -> Any? { return value(forKeyPath: key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the results. - parameter keyPath: The key path to the property whose values are desired. */ public override func value(forKeyPath keyPath: String) -> Any? { return rlmResults.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the objects represented by the results using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ public override func setValue(_ value: Any?, forKey key: String) { return rlmResults.setValue(value, forKeyPath: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<T> { return Results<T>(rlmResults.objects(with: NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate with which to filter the objects. */ public func filter(_ predicate: NSPredicate) -> Results<T> { return Results<T>(rlmResults.objects(with: predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects represented by the results, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter keyPath: The key path to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<T> { return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)]) } /** Returns a `Results` containing the objects represented by the results, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byProperty: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ @available(*, deprecated, renamed: "sorted(byKeyPath:ascending:)") public func sorted(byProperty property: String, ascending: Bool = true) -> Results<T> { return sorted(byKeyPath: property, ascending: ascending) } /** Returns a `Results` containing the objects represented by the results, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { return Results<T>(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the results, or `nil` if the results are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<U: MinMaxType>(ofProperty property: String) -> U? { return rlmResults.min(ofProperty: property).map(dynamicBridgeCast) } /** Returns the maximum (highest) value of the given property among all the results, or `nil` if the results are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func max<U: MinMaxType>(ofProperty property: String) -> U? { return rlmResults.max(ofProperty: property).map(dynamicBridgeCast) } /** Returns the sum of the values of a given property over all the results. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<U: AddableType>(ofProperty property: String) -> U { return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property)) } /** Returns the average value of a given property over all the results, or `nil` if the results are empty. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<U: AddableType>(ofProperty property: String) -> U? { return rlmResults.average(ofProperty: property).map(dynamicBridgeCast) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.addNotificationBlock { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func addNotificationBlock(_ block: @escaping (RealmCollectionChange<Results>) -> Void) -> NotificationToken { return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: self, change: change, error: error)) } } } extension Results: RealmCollection { // MARK: Sequence Support /// Returns a `RLMIterator` that yields successive elements in the results. public func makeIterator() -> RLMIterator<T> { return RLMIterator(collection: rlmResults) } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// :nodoc: public func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error)) } } } // MARK: AssistedObjectiveCBridgeable extension Results: AssistedObjectiveCBridgeable { static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Results { return Results(objectiveCValue as! RLMResults) } var bridged: (objectiveCValue: Any, metadata: Any?) { return (objectiveCValue: rlmResults, metadata: nil) } } // MARK: Unavailable extension Results { @available(*, unavailable, renamed: "isInvalidated") public var invalidated: Bool { fatalError() } @available(*, unavailable, renamed: "index(matching:)") public func index(of predicate: NSPredicate) -> Int? { fatalError() } @available(*, unavailable, renamed: "index(matching:_:)") public func index(of predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() } @available(*, unavailable, renamed: "sorted(byKeyPath:ascending:)") public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() } @available(*, unavailable, renamed: "sorted(by:)") public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { fatalError() } @available(*, unavailable, renamed: "min(ofProperty:)") public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "max(ofProperty:)") public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "sum(ofProperty:)") public func sum<U: AddableType>(_ property: String) -> U { fatalError() } @available(*, unavailable, renamed: "average(ofProperty:)") public func average<U: AddableType>(_ property: String) -> U? { fatalError() } }
mit
81af77e55174c6ee03cff592fb85fb6c
39.630197
120
0.684888
4.829129
false
false
false
false
calt/Moya
Examples/Basic/ViewController.swift
2
4930
import UIKit import Moya class ViewController: UITableViewController { var progressView = UIView() var repos = NSArray() override func viewDidLoad() { super.viewDidLoad() progressView.frame = CGRect(origin: .zero, size: CGSize(width: 0, height: 2)) progressView.backgroundColor = .blue navigationController?.navigationBar.addSubview(progressView) downloadRepositories("ashfurrow") } fileprivate func showAlert(_ title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(ok) present(alertController, animated: true, completion: nil) } // MARK: - API Stuff func downloadRepositories(_ username: String) { gitHubProvider.request(.userRepositories(username)) { result in do { let response = try result.dematerialize() let value = try response.mapNSArray() self.repos = value self.tableView.reloadData() } catch { let printableError = error as CustomStringConvertible self.showAlert("GitHub Fetch", message: printableError.description) } } } func downloadZen() { gitHubProvider.request(.zen) { result in var message = "Couldn't access API" if case let .success(response) = result { let jsonString = try? response.mapString() message = jsonString ?? message } self.showAlert("Zen", message: message) } } func uploadGiphy() { giphyProvider.request(.upload(gif: Giphy.animatedBirdData), callbackQueue: DispatchQueue.main, progress: progressClosure, completion: progressCompletionClosure) } func downloadMoyaLogo() { gitHubUserContentProvider.request(.downloadMoyaWebContent("logo_github.png"), callbackQueue: DispatchQueue.main, progress: progressClosure, completion: progressCompletionClosure) } // MARK: - Progress Helpers lazy var progressClosure: ProgressBlock = { response in UIView.animate(withDuration: 0.3) { self.progressView.frame.size.width = self.view.frame.size.width * CGFloat(response.progress) } } lazy var progressCompletionClosure: Completion = { result in let color: UIColor switch result { case .success: color = .green case .failure: color = .red } UIView.animate(withDuration: 0.3) { self.progressView.backgroundColor = color self.progressView.frame.size.width = self.view.frame.size.width } UIView.animate(withDuration: 0.3, delay: 1, options: [], animations: { self.progressView.alpha = 0 }, completion: { _ in self.progressView.backgroundColor = .blue self.progressView.frame.size.width = 0 self.progressView.alpha = 1 } ) } // MARK: - User Interaction @IBAction func giphyWasPressed(_ sender: UIBarButtonItem) { uploadGiphy() } @IBAction func searchWasPressed(_ sender: UIBarButtonItem) { var usernameTextField: UITextField? let promptController = UIAlertController(title: "Username", message: nil, preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default) { _ in if let username = usernameTextField?.text { self.downloadRepositories(username) } } promptController.addAction(ok) promptController.addTextField { textField in usernameTextField = textField } present(promptController, animated: true, completion: nil) } @IBAction func zenWasPressed(_ sender: UIBarButtonItem) { downloadZen() } @IBAction func downloadWasPressed(_ sender: UIBarButtonItem) { downloadMoyaLogo() } // MARK: - Table View override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repos.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell let repo = repos[indexPath.row] as? NSDictionary cell.textLabel?.text = repo?["name"] as? String return cell } }
mit
2f8c00628e6ac8ec03aa072b930dcba2
33.236111
109
0.590467
5.405702
false
false
false
false
LearningSwift2/LearningApps
SimpleCoreData/SimpleCoreData/ViewController.swift
1
2418
// // ViewController.swift // SimpleCoreData // // Created by Phil Wright on 3/3/16. // Copyright © 2016 The Iron Yard. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController { let moc = DataController().managedObjectContext override func viewDidLoad() { super.viewDidLoad() seedPersonPlusStarship() fetch() } func fetch() { let fetchPerson = NSFetchRequest(entityName: "Person") let fetchStarship = NSFetchRequest(entityName: "Starship") do { let fetchedPersons = try moc.executeFetchRequest(fetchPerson) as! [Person] for person in fetchedPersons { if let name = person.name { print(name) } } } catch { fatalError("failure to fetch person \(error)") } do { let fetchedStarships = try moc.executeFetchRequest(fetchStarship) as! [Starship] for ship in fetchedStarships { if let name = ship.name { print(name) } } } catch { fatalError("failure to fetch starship \(error)") } } func seedPersonPlusStarship() { let entity = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: moc) as! Person let today = NSDate() entity.setValue("Luke Skywalker", forKey: "name") entity.setValue("Male", forKey: "gender") entity.setValue(today, forKey: "created") let entityStarship = NSEntityDescription.insertNewObjectForEntityForName("Starship", inManagedObjectContext: moc) as! Starship entityStarship.setValue("Melennium Falcon", forKey: "name") entityStarship.setValue(today, forKey: "created") let entityStarship2 = NSEntityDescription.insertNewObjectForEntityForName("Starship", inManagedObjectContext: moc) entityStarship2.setValue("X-wing", forKey: "name") entityStarship2.setValue(today, forKey: "created") do { try moc.save() } catch { fatalError("failure to save context \(error)") } } }
apache-2.0
c47a21bc03bacb90e4a56e57555bac45
25.855556
134
0.558544
5.505695
false
false
false
false
eure/ReceptionApp
iOS/Pods/RxSwift/RxSwift/Observable+Extensions.swift
8
4435
// // Observable+Extensions.swift // Rx // // Created by Krunoslav Zaher on 2/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation extension ObservableType { /** Subscribes an event handler to an observable sequence. - parameter on: Action to invoke for each event in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result(message="http://git.io/rxs.ud") public func subscribe(on: (event: Event<E>) -> Void) -> Disposable { let observer = AnonymousObserver { e in on(event: e) } return self.subscribeSafe(observer) } /** Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is cancelled by disposing subscription) - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result(message="http://git.io/rxs.ud") public func subscribe(onNext onNext: (E -> Void)? = nil, onError: (ErrorType -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { let disposable: Disposable if let disposed = onDisposed { disposable = AnonymousDisposable(disposed) } else { disposable = NopDisposable.instance } let observer = AnonymousObserver<E> { e in switch e { case .Next(let value): onNext?(value) case .Error(let e): onError?(e) disposable.dispose() case .Completed: onCompleted?() disposable.dispose() } } return BinaryDisposable( self.subscribeSafe(observer), disposable ) } /** Subscribes an element handler to an observable sequence. - parameter onNext: Action to invoke for each element in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result(message="http://git.io/rxs.ud") public func subscribeNext(onNext: (E) -> Void) -> Disposable { let observer = AnonymousObserver<E> { e in if case .Next(let value) = e { onNext(value) } } return self.subscribeSafe(observer) } /** Subscribes an error handler to an observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result(message="http://git.io/rxs.ud") public func subscribeError(onError: (ErrorType) -> Void) -> Disposable { let observer = AnonymousObserver<E> { e in if case .Error(let error) = e { onError(error) } } return self.subscribeSafe(observer) } /** Subscribes a completion handler to an observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result(message="http://git.io/rxs.ud") public func subscribeCompleted(onCompleted: () -> Void) -> Disposable { let observer = AnonymousObserver<E> { e in if case .Completed = e { onCompleted() } } return self.subscribeSafe(observer) } } public extension ObservableType { /** All internal subscribe calls go through this method */ @warn_unused_result(message="http://git.io/rxs.ud") func subscribeSafe<O: ObserverType where O.E == E>(observer: O) -> Disposable { return self.asObservable().subscribe(observer) } }
mit
64c5d1bd635a3a98aa87d9d8a043aa65
33.640625
164
0.628778
4.845902
false
false
false
false
chadkeck/watchOS2-template
watchOS2-template/ViewController.swift
1
3969
import UIKit import WatchConnectivity class ViewController: UITableViewController, WCSessionDelegate { var isWatchAppInstalled = false var isPaired = false var isComplicationEnabled = false var isReachable = false var watchDirectoryURL: NSURL? override func viewDidLoad() { super.viewDidLoad() // remove extra empty cells at bottom of table self.tableView.tableFooterView = UIView() if WCSession.isSupported() { let session = WCSession.defaultSession() session.delegate = self session.activateSession() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if WCSession.isSupported() { let session = WCSession.defaultSession() sessionWatchStateDidChange(session) sessionReachabilityDidChange(session) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } func sessionWatchStateDidChange(session: WCSession) { isPaired = session.paired isWatchAppInstalled = session.watchAppInstalled isComplicationEnabled = session.complicationEnabled watchDirectoryURL = session.watchDirectoryURL tableView.reloadData() } func sessionReachabilityDidChange(session: WCSession) { isReachable = session.reachable tableView.reloadData() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 5 default: return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case 0: switch indexPath.row { case 0: let cell = tableView.dequeueReusableCellWithIdentifier("StatusCell", forIndexPath: indexPath) cell.textLabel?.text = "Paired with Apple Watch?" cell.detailTextLabel?.text = isPaired ? "Yes" : "No" return cell case 1: let cell = tableView.dequeueReusableCellWithIdentifier("StatusCell", forIndexPath: indexPath) cell.textLabel?.text = "Installed?" cell.detailTextLabel?.text = isWatchAppInstalled ? "Yes" : "No" return cell case 2: let cell = tableView.dequeueReusableCellWithIdentifier("StatusCell", forIndexPath: indexPath) cell.textLabel?.text = "Reachable?" cell.detailTextLabel?.text = isReachable ? "Yes" : "No" return cell case 3: let cell = tableView.dequeueReusableCellWithIdentifier("StatusCell", forIndexPath: indexPath) cell.textLabel?.text = "Complication" cell.detailTextLabel?.text = isComplicationEnabled ? "Enabled" : "Disabled" return cell case 4: let cell = tableView.dequeueReusableCellWithIdentifier("DetailCell", forIndexPath: indexPath) cell.textLabel?.text = "Watch Directory" cell.detailTextLabel?.text = watchDirectoryURL?.absoluteString return cell default: let cell = tableView.dequeueReusableCellWithIdentifier("StatusCell", forIndexPath: indexPath) cell.textLabel?.text = nil cell.detailTextLabel?.text = nil return cell } default: return UITableViewCell() } } }
mit
6cc7d015fedfcc065df0214835434009
33.824561
118
0.618292
5.968421
false
false
false
false
mruiz723/CourseiOSSwift3
MyPlayground.playground/Contents.swift
1
6577
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // Value type example (Enumerations, structures or tuples - Array, String and Dictionary) struct S { var data: Int = -1 } var a = S() var b = a // a is copied to b a.data = 42 // Changes a, not b print("\(a.data), \(b.data)") // prints "42, -1" // Reference type example (Class) class C { var data: Int = -1 } var x = C() var y = x // x is copied to y x.data = 42 // changes the instance referred to by x (and y) print("\(x.data), \(y.data)") // prints "42, 42" // Constants and Variables let maximumNumberOfLoginAttempts = 10 var currentLoginAttempt = 0 // Type Annotations var welcomeMessage: String // This is a comment. /* This is also a comment but is written over multiple lines. */ // Integers print(UInt8.max) print(UInt16.max) print(Int.max) //Depends if the device is the 32 or 64 bits // Boolean let start = true // true or false // Typealias //Define an alternative name for an existing type. You define type aliases with the typealiaskeyword. typealias AudioSample = UInt16 //Tuples //Group multiple values into a single compound value. The values within a tuple can be of any type and don’t have to be of the same type as each other. let http404Error = (404, "Not Found") // http404Error is of type (Int, String), and equals (404, "Not Found") let (statusCode, statusMessage) = http404Error print("The status code is \(statusCode)") // Prints "The status code is 404" print("The status message is \(statusMessage)") // Prints "The status message is Not Found" //Ignore parts of the tuple with an underscore (_) when you decompose the tuple: let (justTheStatusCode, _) = http404Error print("The status code is \(justTheStatusCode)") // Prints "The status code is 404" //access the individual element values in a tuple using index numbers starting at zero: print("The status code is \(http404Error.0)") // Prints "The status code is 404" print("The status message is \(http404Error.1)") // Prints "The status message is Not Found" // You can name the individual elements in a tuple when the tuple is defined: let http200Status = (statusCode: 200, description: "OK") print("The status code is \(http200Status.statusCode)") // Prints "The status code is 200" print("The status message is \(http200Status.description)") // Prints "The status message is OK" /* Tuples are particularly useful as the return values of functions. A function that tries to retrieve a web page might return the (Int, String) tuple type to describe the success or failure of the page retrieval. By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type. */ // Optionals /* You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all. */ let possibleNumber = "123" let convertedNumber = Int(possibleNumber) // convertedNumber is inferred to be of type "Int?", or "optional Int" var surveyAnswer: String? // surveyAnswer is automatically set to nil // If Statements and Forced Unwrapping if convertedNumber != nil { print("convertedNumber has an integer value of \(convertedNumber!).") } // Optional Binding if let actualNumber = Int(possibleNumber) { print("\"\(possibleNumber)\" has an integer value of \(actualNumber)") } else { print("\"\(possibleNumber)\" could not be converted to an integer") } // Prints ""123" has an integer value of 123" /* You can include as many optional bindings and Boolean conditions in a single if statement as you need to, separated by commas. If any of the values in the optional bindings are nil or any Boolean condition evaluates to false, the whole if statement’s condition is considered to be false. The following if statements are equivalent: */ if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 { print("\(firstNumber) < \(secondNumber) < 100") } // Prints "4 < 42 < 100" if let firstNumber = Int("4") { if let secondNumber = Int("42") { if firstNumber < secondNumber && secondNumber < 100 { print("\(firstNumber) < \(secondNumber) < 100") } } } // Prints "4 < 42 < 100" // Implicitly Unwrapped Optionals. let possibleString: String? = "An optional string." let forcedString: String = possibleString! // requires an exclamation mark let assumedString: String! = "An implicitly unwrapped optional string." let implicitString: String = assumedString // no need for an exclamation mark /* NOTE Don’t use an implicitly unwrapped optional when there’s a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable. */ // Error Handling /* Error Handling (During execution). Error handling allows you to determine the underlying cause of failure, and, if necessary, propagate the error to another part of your program. When a function encounters an error condition, it throws an error That function’s caller can then catch the error and respond appropriately. */ func canThrowAnError() throws { // this function may or may not throw an error } do { try canThrowAnError() // no error was thrown } catch { // an error was thrown } //Here’s an example of how error handling can be used to respond to different error conditions: enum SandwichError { case outOfCleanDishes case missingIngredients([String]) } func makeASandwich() throws { // ... } func eatASandwich() { } func washDishes() { } func buyGroceries(ingredients: [String]) { } do { try makeASandwich() eatASandwich() } catch SandwichError.outOfCleanDishes { washDishes() } catch SandwichError.missingIngredients(let ingredients) { buyGroceries(ingredients: ingredients) } // Assertions and Preconditions /* Assertions and preconditions are checks that happen at runtime. You use them to make sure an essential condition is satisfied before executing any further code. */ // Debugging with Assertions let age = -3 assert(age >= 0, "A person's age can't be less than zero.") // This assertion fails because -3 is not >= 0. // operator let apples = 3 let oranges = 5 print(apples > 3 ? "E" : "B") if apples > 1 && oranges > 2 { }
mit
6d9863740e8a467858280dcbc4838dff
29.384259
410
0.71705
3.989666
false
false
false
false
xu6148152/binea_project_for_ios
SportDemo/SportDemo/Shared/view/TableViewCell/ZPTableSectionEntity.swift
1
2343
// // ZPTableSectionEntity.swift // SportDemo // // Created by Binea Xu on 8/23/15. // Copyright (c) 2015 Binea Xu. All rights reserved. // import Foundation import UIKit class ZPTableSectionEntity{ var row: NSMutableArray? var headerType: String? var headerTitle: String? var footerTitle: String? var rows: NSArray? var rowTypes: NSArray?{ set{ } get{ let set = NSMutableSet() for row in _rows{ set.addObject((row as! ZPTableRowEntity).rowType) } return set.allObjects as NSArray } } var _rows: NSMutableArray{ set{ } get{ return self._rows } } init(){ _rows = NSArray().mutableCopy() as! NSMutableArray } static func sectionEntityFromDictionary(dictionary: NSDictionary) -> ZPTableSectionEntity{ return ZPTableSectionEntity().initWithDictionary(dictionary) } func initWithDictionary(dictionary: NSDictionary) -> ZPTableSectionEntity{ headerType = dictionary["ZPSectionHeaderType"] as? String headerTitle = NSLocalizedString(dictionary["ZPSectionHeaderTitle"] as! String, comment: dictionary["ZPSectionHeaderTitle"] as! String) footerTitle = NSLocalizedString(dictionary["ZPSectionFooterTitle"] as! String, comment: dictionary["ZPSectionFooterTitle"] as! String) _rows = NSArray().mutableCopy() as! NSMutableArray let array = dictionary["ZPSectionRows"] as! NSArray for dict in array{ _rows.addObject(ZPTableRowEntity.rowEntityFromDictionary(dict as! NSDictionary)) } return self } func registerNib(tableView: UITableView){ // for rowtype in self.rowTypes { // if rowtype as String{ // tableView.registerNib(UINib(nibName: rowtype, bundle: nil), forCellReuseIdentifier: rowtype) // } // } } func cellForRow(row: NSInteger, tableView: UITableView, withDelegate: AnyObject) -> ZPTableBaseCell { let rowEntity: ZPTableRowEntity = _rows[row] as! ZPTableRowEntity return rowEntity.cellInTableView(tableView, withDelegate: withDelegate) } }
mit
de84e885adeecccc7661bb733e640128
27.938272
142
0.612036
4.871102
false
false
false
false
dataich/TypetalkSwift
TypetalkSwift/Requests/PostMigrateToDMTopic.swift
1
884
// // PostMigrateToDMTopic.swift // TypetalkSwift // // Created by Taichiro Yoshida on 2017/10/15. // Copyright © 2017 Nulab Inc. All rights reserved. // import Alamofire // sourcery: AutoInit public struct PostMigrateToDMTopic: Request { public let accountName: String public let topicId: Int public typealias Response = PostMigrateToDMTopicResponse public var method: HTTPMethod { return .post } public var path: String { return "/messages/@\(accountName)/migrate" } public var parameters: Parameters? { var parameters: Parameters = [:] parameters["topicId"] = topicId return parameters } // sourcery:inline:auto:PostMigrateToDMTopic.AutoInit public init(accountName: String, topicId: Int) { self.accountName = accountName self.topicId = topicId } // sourcery:end } public typealias PostMigrateToDMTopicResponse = Topic
mit
0cc927afdd0bd8201b659230d387cf8a
22.864865
58
0.724802
4.069124
false
false
false
false
domenicosolazzo/practice-swift
File Management/Finding the Paths of the Most Useful Folders on Disk/Finding the Paths of the Most Useful Folders on Disk/AppDelegate.swift
1
1357
// // AppDelegate.swift // Finding the Paths of the Most Useful Folders on Disk // // Created by Domenico on 27/05/15. // License MIT // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } func getDocumentFolder() -> URL?{ let fileManager = FileManager() let urls = fileManager.urls( for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask) if urls.count > 0{ let url = urls[0] print(url) return url } return nil } func getCacheFolder() -> URL?{ let fileManager = FileManager() let urls = fileManager.urls( for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask) if urls.count > 0{ let url = urls[0] print(url) return url } return nil } func getTemporaryFolder() -> URL? { _ = NSTemporaryDirectory() return nil } }
mit
046670b7719949b83ec8f50a6dbaee02
23.672727
144
0.587325
5.34252
false
false
false
false
fjcaetano/ReCaptcha
ReCaptcha/Classes/ReCaptchaDecoder.swift
1
3250
// // ReCaptchaDecoder.swift // ReCaptcha // // Created by Flávio Caetano on 22/03/17. // Copyright © 2018 ReCaptcha. All rights reserved. // import Foundation import WebKit /** The Decoder of javascript messages from the webview */ internal class ReCaptchaDecoder: NSObject { /** The decoder result. */ enum Result { /// A result token, if any case token(String) /// Indicates that the webview containing the challenge should be displayed. case showReCaptcha /// Any errors case error(ReCaptchaError) /// Did finish loading resources case didLoad /// Logs a string onto the console case log(String) } /// The closure that receives messages fileprivate let sendMessage: ((Result) -> Void) /** - parameter didReceiveMessage: A closure that receives a ReCaptchaDecoder.Result Initializes a decoder with a completion closure. */ init(didReceiveMessage: @escaping (Result) -> Void) { sendMessage = didReceiveMessage super.init() } /** - parameter error: The error to be sent. Sends an error to the completion closure */ func send(error: ReCaptchaError) { sendMessage(.error(error)) } } // MARK: Script Handler /** Makes ReCaptchaDecoder conform to `WKScriptMessageHandler` */ extension ReCaptchaDecoder: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { guard let dict = message.body as? [String: Any] else { return sendMessage(.error(.wrongMessageFormat)) } sendMessage(Result.from(response: dict)) } } // MARK: - Result /** Private methods on `ReCaptchaDecoder.Result` */ fileprivate extension ReCaptchaDecoder.Result { /** - parameter response: A dictionary containing the message to be parsed - returns: A decoded ReCaptchaDecoder.Result Parses a dict received from the webview onto a `ReCaptchaDecoder.Result` */ static func from(response: [String: Any]) -> ReCaptchaDecoder.Result { if let token = response["token"] as? String { return .token(token) } else if let message = response["log"] as? String { return .log(message) } else if let error = response["error"] as? Int { return from(error) } if let action = response["action"] as? String { switch action { case "showReCaptcha": return .showReCaptcha case "didLoad": return .didLoad default: break } } if let message = response["log"] as? String { return .log(message) } return .error(.wrongMessageFormat) } private static func from(_ error: Int) -> ReCaptchaDecoder.Result { switch error { case 27: return .error(.failedSetup) case 28: return .error(.responseExpired) case 29: return .error(.failedRender) default: return .error(.wrongMessageFormat) } } }
mit
371f8bd364f7e7b26fd97bf03531d9dc
23.238806
119
0.604988
4.762463
false
false
false
false
customerly/Customerly-iOS-SDK
CustomerlySDK/Library/View Controllers/Cells/CyMessageTableViewCell.swift
1
4008
// // CyMessageTableViewCell.swift // Customerly // // Created by Paolo Musolino on 10/12/16. // Copyright © 2016 Customerly. All rights reserved. // import UIKit import Kingfisher class CyMessageTableViewCell: UITableViewCell { @IBOutlet weak var adminAvatar: CyImageView! @IBOutlet weak var userAvatar: CyImageView! @IBOutlet weak var messageView: UIView! @IBOutlet weak var messageTextView: CyTextView! @IBOutlet weak var dateLabel: CyLabel! @IBOutlet var messageViewLeftConstraint: NSLayoutConstraint? @IBOutlet var messageViewRightConstraint: NSLayoutConstraint? @IBOutlet weak var attachmentsStackView: CyStackView? @IBOutlet weak var attachmentsStackViewHeightConstraint: NSLayoutConstraint? var vcThatShowThisCell : CyViewController? var imagesAttachments : [String] = [] override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() messageView.layer.cornerRadius = 8.0 messageTextView.textContainerInset = UIEdgeInsets.init(top: 2, left: 0, bottom: -12, right: 0) //remove padding adminAvatar.layer.cornerRadius = adminAvatar.frame.size.width/2 //Circular avatar for admin userAvatar.layer.cornerRadius = userAvatar.frame.size.width/2 //Circular avatar for user self.backgroundColor = UIColor.clear } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setAdminVisual(bubbleColor: UIColor? = UIColor(hexString: "#ECEFF1")){ messageTextView.textAlignment = .left userAvatar.isHidden = true adminAvatar.isHidden = false messageViewRightConstraint?.isActive = false messageViewLeftConstraint?.isActive = true messageView.backgroundColor = bubbleColor } func setUserVisual(bubbleColor: UIColor? = UIColor(hexString: "#01B0FF")){ userAvatar.isHidden = false adminAvatar.isHidden = true messageTextView.textAlignment = .left messageViewRightConstraint?.isActive = true messageViewLeftConstraint?.isActive = false messageView.backgroundColor = bubbleColor } func cellContainsImages(configForImages: Bool){ guard attachmentsStackView != nil else { return } for view in attachmentsStackView!.arrangedSubviews{ attachmentsStackView?.removeArrangedSubview(view) view.removeFromSuperview() } for url in imagesAttachments{ let imageViewAttachment = CyImageView() imageViewAttachment.kf.indicatorType = .activity imageViewAttachment.kf.setImage(with: URL(string: url)) imageViewAttachment.contentMode = .scaleAspectFill imageViewAttachment.clipsToBounds = true imageViewAttachment.isUserInteractionEnabled = true let imageViewHeightConstraint = NSLayoutConstraint(item: imageViewAttachment, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 150) imageViewHeightConstraint.priority = UILayoutPriority(rawValue: 999) imageViewAttachment.addConstraint(imageViewHeightConstraint) imageViewAttachment.touchUpInside(action: { [weak self] in if imageViewAttachment.image != nil{ let galleryVC = CustomerlyGalleryViewController.instantiate() galleryVC.image = imageViewAttachment.image self?.vcThatShowThisCell?.present(galleryVC, animated: true, completion: nil) } }) attachmentsStackView?.addArrangedSubview(imageViewAttachment) } } }
apache-2.0
17fd1e91ce1ff453088cce84000884fe
39.887755
191
0.683554
5.422192
false
false
false
false
PJayRushton/stats
Stats/TextEditViewController.swift
1
2449
// // TextEditViewController.swift // Stats // // Created by Parker Rushton on 5/27/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit import Presentr import TextFieldEffects class TextEditViewController: Component, AutoStoryboardInitializable { // MARK: - Static static let presenter: Presentr = { let presenter = Presentr(presentationType: .custom(width: .fluid(percentage: 0.8), height: .custom(size: 300), center: .center)) presenter.transitionType = TransitionType.coverHorizontalFromRight return presenter }() // MARK: - IBOutlets @IBOutlet weak var topLabel: UILabel! @IBOutlet weak var textField: HoshiTextField! @IBOutlet weak var saveButton: CustomButton! @IBOutlet var keyboardView: UIView! @IBOutlet weak var keyboardSaveButton: CustomButton! // MARK: - Public properties var topLabelText = "" var editingText: String? var placeholder: String? var saveButtonTitle = NSLocalizedString("Save", comment: "") var savePressed: ((String) -> Void) = { _ in } // MARK: - ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() topLabel.text = topLabelText textField.text = editingText textField.placeholder = placeholder textField.inputAccessoryView = keyboardView saveButton.setTitle(saveButtonTitle, for: .normal) saveButton.isEnabled = false keyboardSaveButton.setTitle(saveButtonTitle, for: .normal) keyboardSaveButton.isEnabled = false } // MARK: - IBActions @IBAction func textFieldChanged(_ sender: UITextField) { guard let text = sender.text else { return } let isSavable = !text.isEmpty && text != editingText saveButton.isEnabled = isSavable keyboardSaveButton.isEnabled = isSavable } @IBAction func saveButtonPressed(_ sender: UIButton) { dismiss(animated: true, completion: nil) guard let text = textField.text else { return } savePressed(text) } @IBAction func viewTapped(_ sender: UITapGestureRecognizer) { textField.resignFirstResponder() } } extension TextEditViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
5025f605fa402d5b7b57423d204d1fdf
27.465116
136
0.662173
5.068323
false
false
false
false